-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathlib.rs
More file actions
464 lines (428 loc) · 16.5 KB
/
lib.rs
File metadata and controls
464 lines (428 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
extern crate alloc;
#[cfg(feature = "meshlet")]
mod meshlet;
pub mod wireframe;
/// Experimental features that are not yet finished. Please report any issues you encounter!
///
/// Expect bugs, missing features, compatibility issues, low performance, and/or future breaking changes.
#[cfg(feature = "meshlet")]
pub mod experimental {
/// Render high-poly 3d meshes using an efficient GPU-driven method.
/// See [`MeshletPlugin`](meshlet::MeshletPlugin) and [`MeshletMesh`](meshlet::MeshletMesh) for details.
pub mod meshlet {
pub use crate::meshlet::*;
}
}
mod atmosphere;
mod cluster;
pub mod contact_shadows;
#[cfg(feature = "bevy_gltf")]
mod gltf;
use bevy_light::cluster::GlobalClusterSettings;
use bevy_render::sync_component::SyncComponent;
pub use contact_shadows::{
ContactShadows, ContactShadowsBuffer, ContactShadowsPlugin, ContactShadowsUniform,
ViewContactShadowsUniformOffset,
};
pub mod decal;
pub mod deferred;
pub mod diagnostic;
mod extended_material;
mod fog;
mod light_probe;
mod lightmap;
mod material;
mod material_bind_groups;
mod medium;
mod mesh_material;
mod parallax;
mod pbr_material;
mod prepass;
mod render;
mod ssao;
mod ssr;
mod transmission;
mod volumetric_fog;
use bevy_color::{Color, LinearRgba};
pub use atmosphere::*;
use bevy_light::{
AmbientLight, DirectionalLight, PointLight, RectLight, ShadowFilteringMethod, SpotLight,
};
use bevy_shader::{load_shader_library, ShaderRef};
pub use cluster::*;
pub use decal::clustered::ClusteredDecalPlugin;
pub use extended_material::*;
pub use fog::*;
pub use light_probe::*;
pub use lightmap::*;
pub use material::*;
pub use material_bind_groups::*;
pub use medium::*;
pub use mesh_material::*;
pub use parallax::*;
pub use pbr_material::*;
pub use prepass::*;
pub use render::*;
pub use ssao::*;
pub use ssr::*;
pub use transmission::*;
pub use volumetric_fog::VolumetricFogPlugin;
/// The PBR prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
contact_shadows::ContactShadowsPlugin,
fog::{DistanceFog, FogFalloff},
material::{Material, MaterialPlugin},
mesh_material::MeshMaterial3d,
parallax::ParallaxMappingMethod,
pbr_material::StandardMaterial,
ssao::ScreenSpaceAmbientOcclusionPlugin,
};
}
use crate::gpu::GpuClusteringPlugin;
use crate::{deferred::DeferredPbrLightingPlugin, gpu::extract_clusters_for_gpu_clustering};
use bevy_app::prelude::*;
use bevy_asset::{AssetApp, AssetPath, Assets, Handle, RenderAssetUsages};
use bevy_core_pipeline::mip_generation::experimental::depth::early_downsample_depth;
use bevy_core_pipeline::schedule::{Core3d, Core3dSystems};
use bevy_ecs::prelude::*;
use bevy_image::{CompressedImageFormats, Image, ImageSampler, ImageType};
use bevy_material::AlphaMode;
use bevy_render::{
camera::sort_cameras,
extract_resource::ExtractResourcePlugin,
render_resource::{
Extent3d, TextureDataOrder, TextureDescriptor, TextureDimension, TextureFormat,
TextureUsages,
},
sync_component::SyncComponentPlugin,
ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderDebugFlags, RenderStartup,
RenderSystems,
};
use std::path::PathBuf;
fn shader_ref(path: PathBuf) -> ShaderRef {
ShaderRef::Path(AssetPath::from_path_buf(path).with_source("embedded"))
}
pub const TONEMAPPING_LUT_TEXTURE_BINDING_INDEX: u32 = 19;
pub const TONEMAPPING_LUT_SAMPLER_BINDING_INDEX: u32 = 20;
/// Sets up the entire PBR infrastructure of bevy.
pub struct PbrPlugin {
/// Controls if the prepass is enabled for the [`StandardMaterial`].
/// For more information about what a prepass is, see the [`bevy_core_pipeline::prepass`] docs.
pub prepass_enabled: bool,
/// Controls if [`DeferredPbrLightingPlugin`] is added.
pub add_default_deferred_lighting_plugin: bool,
/// Controls if GPU [`MeshUniform`] building is enabled.
///
/// This requires compute shader support and so will be forcibly disabled if
/// the platform doesn't support those.
pub use_gpu_instance_buffer_builder: bool,
/// Debugging flags that can optionally be set when constructing the renderer.
pub debug_flags: RenderDebugFlags,
/// Builds and inserts `StandardMaterial` when loading glTF files
pub gltf_enable_standard_materials: bool,
}
impl Default for PbrPlugin {
fn default() -> Self {
Self {
prepass_enabled: true,
add_default_deferred_lighting_plugin: true,
use_gpu_instance_buffer_builder: true,
debug_flags: RenderDebugFlags::default(),
gltf_enable_standard_materials: true,
}
}
}
/// A resource that stores the spatio-temporal blue noise texture.
#[derive(Resource)]
pub struct Bluenoise {
/// Texture handle for spatio-temporal blue noise
pub texture: Handle<Image>,
}
/// LTC (Linearly Transformed Cosines) LUT textures for area light shading.
///
/// `ltc_1` encodes the 4 non-trivial elements of the inverse GGX LTC matrix.
/// `ltc_2` encodes amplitude and Fresnel-related weights.
///
/// [LUT source and fitting code](https://github.com/selfshadow/ltc_code/blob/master/fit/results)
#[derive(Resource, Clone)]
pub struct LtcLuts {
pub ltc_1: Handle<Image>,
pub ltc_2: Handle<Image>,
}
impl Plugin for PbrPlugin {
fn build(&self, app: &mut App) {
load_shader_library!(app, "render/pbr_types.wgsl");
load_shader_library!(app, "render/pbr_bindings.wgsl");
load_shader_library!(app, "render/utils.wgsl");
load_shader_library!(app, "render/clustered_forward.wgsl");
load_shader_library!(app, "render/pbr_lighting.wgsl");
load_shader_library!(app, "render/shadows.wgsl");
load_shader_library!(app, "deferred/pbr_deferred_types.wgsl");
load_shader_library!(app, "deferred/pbr_deferred_functions.wgsl");
load_shader_library!(app, "render/shadow_sampling.wgsl");
load_shader_library!(app, "render/pbr_functions.wgsl");
load_shader_library!(app, "render/rgb9e5.wgsl");
load_shader_library!(app, "render/pbr_ambient.wgsl");
load_shader_library!(app, "render/pbr_fragment.wgsl");
load_shader_library!(app, "render/pbr.wgsl");
load_shader_library!(app, "render/pbr_prepass_functions.wgsl");
load_shader_library!(app, "render/pbr_prepass.wgsl");
load_shader_library!(app, "render/parallax_mapping.wgsl");
load_shader_library!(app, "render/view_transformations.wgsl");
// Setup dummy shaders for when MeshletPlugin is not used to prevent shader import errors.
load_shader_library!(app, "meshlet/dummy_visibility_buffer_resolve.wgsl");
app.register_asset_reflect::<StandardMaterial>()
.init_resource::<DefaultOpaqueRendererMethod>()
.add_plugins((
MeshRenderPlugin {
use_gpu_instance_buffer_builder: self.use_gpu_instance_buffer_builder,
debug_flags: self.debug_flags,
},
MaterialsPlugin {
debug_flags: self.debug_flags,
},
MaterialPlugin::<StandardMaterial> {
debug_flags: self.debug_flags,
..Default::default()
},
ScreenSpaceAmbientOcclusionPlugin,
FogPlugin,
ExtractResourcePlugin::<DefaultOpaqueRendererMethod>::default(),
SyncComponentPlugin::<ShadowFilteringMethod, Self>::default(),
LightmapPlugin,
LightProbePlugin,
GpuMeshPreprocessPlugin {
use_gpu_instance_buffer_builder: self.use_gpu_instance_buffer_builder,
},
VolumetricFogPlugin,
ScreenSpaceReflectionsPlugin,
ScreenSpaceTransmissionPlugin,
ClusteredDecalPlugin,
ContactShadowsPlugin,
))
.add_plugins((
decal::ForwardDecalPlugin,
SyncComponentPlugin::<DirectionalLight, Self>::default(),
SyncComponentPlugin::<PointLight, Self>::default(),
SyncComponentPlugin::<SpotLight, Self>::default(),
SyncComponentPlugin::<RectLight, Self>::default(),
SyncComponentPlugin::<AmbientLight, Self>::default(),
))
.add_plugins((
ScatteringMediumPlugin,
AtmospherePlugin,
GpuClusteringPlugin,
));
#[cfg(feature = "bevy_gltf")]
if self.gltf_enable_standard_materials {
gltf::add_gltf(app);
}
if self.add_default_deferred_lighting_plugin {
app.add_plugins(DeferredPbrLightingPlugin);
}
// Initialize the default material handle.
app.world_mut()
.resource_mut::<Assets<StandardMaterial>>()
.insert(
&Handle::<StandardMaterial>::default(),
StandardMaterial {
base_color: Color::srgb(1.0, 0.0, 0.5),
..Default::default()
},
)
.unwrap();
let has_bluenoise = app
.get_sub_app(RenderApp)
.is_some_and(|render_app| render_app.world().is_resource_added::<Bluenoise>());
if !has_bluenoise {
let mut images = app.world_mut().resource_mut::<Assets<Image>>();
#[cfg(feature = "bluenoise_texture")]
let handle = {
let image = Image::from_buffer(
include_bytes!("bluenoise/stbn.ktx2"),
ImageType::Extension("ktx2"),
CompressedImageFormats::NONE,
false,
ImageSampler::Default,
RenderAssetUsages::RENDER_WORLD,
)
.expect("Failed to decode embedded blue-noise texture");
images.add(image)
};
#[cfg(not(feature = "bluenoise_texture"))]
let handle = { images.add(stbn_placeholder()) };
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.world_mut()
.insert_resource(Bluenoise { texture: handle });
}
}
let has_ltc_luts = app
.get_sub_app(RenderApp)
.is_some_and(|render_app| render_app.world().is_resource_added::<LtcLuts>());
if !has_ltc_luts {
let mut images = app.world_mut().resource_mut::<Assets<Image>>();
let ltc_luts = LtcLuts {
ltc_1: images.add(
Image::from_buffer(
include_bytes!("ltc/ltc1.ktx2"),
ImageType::Extension("ktx2"),
CompressedImageFormats::NONE,
false,
ImageSampler::linear(),
RenderAssetUsages::RENDER_WORLD,
)
.expect("Failed to decode embedded LTC LUT 1"),
),
ltc_2: images.add(
Image::from_buffer(
include_bytes!("ltc/ltc2.ktx2"),
ImageType::Extension("ktx2"),
CompressedImageFormats::NONE,
false,
ImageSampler::linear(),
RenderAssetUsages::RENDER_WORLD,
)
.expect("Failed to decode embedded LTC LUT 2"),
),
};
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.world_mut().insert_resource(ltc_luts);
}
}
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
// Extract the required data from the main world
render_app
.add_systems(
RenderStartup,
(
init_shadow_samplers,
init_global_clusterable_object_meta,
init_fallback_bindless_resources,
),
)
.add_systems(
ExtractSchedule,
(
extract_clusters_for_cpu_clustering
.run_if(not(gpu_clustering_is_enabled_during_extraction)),
extract_clusters_for_gpu_clustering
.run_if(gpu_clustering_is_enabled_during_extraction),
),
)
.add_systems(
ExtractSchedule,
(
extract_lights,
extract_ambient_light_resource,
extract_ambient_light,
extract_shadow_filtering_method,
late_sweep_material_instances,
),
)
.add_systems(
Render,
(
prepare_lights
.in_set(RenderSystems::CreateViews)
.after(sort_cameras),
prepare_clusters_for_cpu_clustering
.in_set(RenderSystems::PrepareResources)
.run_if(
|global_cluster_settings: Res<GlobalClusterSettings>| -> bool {
global_cluster_settings.gpu_clustering.is_none()
},
),
),
)
.init_gpu_resource::<LightMeta>()
.init_gpu_resource::<RenderMaterialBindings>()
.allow_ambiguous_resource::<RenderMaterialBindings>();
render_app.world_mut().add_observer(add_light_view_entities);
render_app
.world_mut()
.add_observer(remove_light_view_entities);
render_app.world_mut().add_observer(extracted_light_removed);
render_app.add_systems(
Core3d,
(
per_view_shadow_pass::<EARLY_SHADOW_PASS>
.after(early_prepass_build_indirect_parameters)
.before(early_downsample_depth)
.before(per_view_shadow_pass::<LATE_SHADOW_PASS>),
per_view_shadow_pass::<LATE_SHADOW_PASS>
.after(late_prepass_build_indirect_parameters)
.before(main_build_indirect_parameters)
.before(Core3dSystems::MainPass),
shared_shadow_pass::<EARLY_SHADOW_PASS>
.after(early_prepass_build_indirect_parameters)
.before(early_downsample_depth)
.before(per_view_shadow_pass::<LATE_SHADOW_PASS>),
shared_shadow_pass::<LATE_SHADOW_PASS>
.after(late_prepass_build_indirect_parameters)
.before(main_build_indirect_parameters)
.before(Core3dSystems::MainPass),
),
);
}
fn finish(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
let global_cluster_settings = make_global_cluster_settings(render_app.world());
app.insert_resource(global_cluster_settings);
}
}
pub fn stbn_placeholder() -> Image {
let format = TextureFormat::Rgba8Unorm;
let data = vec![255, 0, 255, 255];
Image {
data: Some(data),
data_order: TextureDataOrder::default(),
texture_descriptor: TextureDescriptor {
size: Extent3d::default(),
format,
dimension: TextureDimension::D2,
label: None,
mip_level_count: 1,
sample_count: 1,
usage: TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
sampler: ImageSampler::Default,
texture_view_descriptor: None,
asset_usage: RenderAssetUsages::RENDER_WORLD,
copy_on_resize: false,
}
}
impl SyncComponent<PbrPlugin> for DirectionalLight {
type Target = Self;
}
impl SyncComponent<PbrPlugin> for PointLight {
type Target = Self;
}
impl SyncComponent<PbrPlugin> for SpotLight {
type Target = Self;
}
impl SyncComponent<PbrPlugin> for RectLight {
type Target = Self;
}
impl SyncComponent<PbrPlugin> for AmbientLight {
type Target = Self;
}
impl SyncComponent<PbrPlugin> for ShadowFilteringMethod {
type Target = Self;
}