forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmesh.rs
More file actions
3242 lines (2972 loc) · 128 KB
/
mesh.rs
File metadata and controls
3242 lines (2972 loc) · 128 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::material_bind_groups::{MaterialBindGroupIndex, MaterialBindGroupSlot};
use allocator::MeshAllocator;
use bevy_asset::{load_internal_asset, AssetId};
use bevy_core_pipeline::{
core_3d::{AlphaMask3d, Opaque3d, Transmissive3d, Transparent3d, CORE_3D_DEPTH_FORMAT},
deferred::{AlphaMask3dDeferred, Opaque3dDeferred},
oit::{prepare_oit_buffers, OrderIndependentTransparencySettingsOffset},
prepass::MotionVectorPrepass,
};
use bevy_derive::{Deref, DerefMut};
use bevy_diagnostic::FrameCount;
use bevy_ecs::{
prelude::*,
query::{QueryData, ROQueryItem},
system::{lifetimeless::*, SystemParamItem, SystemState},
};
use bevy_image::{BevyDefault, ImageSampler, TextureFormatPixelInfo};
use bevy_math::{Affine3, Rect, UVec2, Vec3, Vec4};
use bevy_platform::collections::{hash_map::Entry, HashMap};
use bevy_render::{
batching::{
gpu_preprocessing::{
self, GpuPreprocessingSupport, IndirectBatchSet, IndirectParametersBuffers,
IndirectParametersCpuMetadata, IndirectParametersIndexed, IndirectParametersNonIndexed,
InstanceInputUniformBuffer, UntypedPhaseIndirectParametersBuffers,
},
no_gpu_preprocessing, GetBatchData, GetFullBatchData, NoAutomaticBatching,
},
camera::Camera,
mesh::{skinning::SkinnedMesh, *},
primitives::Aabb,
render_asset::RenderAssets,
render_phase::{
BinnedRenderPhasePlugin, InputUniformIndex, PhaseItem, PhaseItemExtraIndex, RenderCommand,
RenderCommandResult, SortedRenderPhasePlugin, TrackedRenderPass,
},
render_resource::*,
renderer::{RenderAdapter, RenderDevice, RenderQueue},
sync_world::MainEntityHashSet,
texture::{DefaultImageSampler, GpuImage},
view::{
self, NoFrustumCulling, NoIndirectDrawing, RenderVisibilityRanges, RetainedViewEntity,
ViewTarget, ViewUniformOffset, ViewVisibility, VisibilityRange,
},
Extract,
};
use bevy_transform::components::GlobalTransform;
use bevy_utils::{default, Parallel, TypeIdMap};
use core::any::TypeId;
use core::mem::size_of;
use material_bind_groups::MaterialBindingId;
use tracing::{error, warn};
use self::irradiance_volume::IRRADIANCE_VOLUMES_ARE_USABLE;
use crate::environment_map::EnvironmentMapLight;
use crate::irradiance_volume::IrradianceVolume;
use crate::{
render::{
morph::{
extract_morphs, no_automatic_morph_batching, prepare_morphs, MorphIndices,
MorphUniforms,
},
skin::no_automatic_skin_batching,
},
*,
};
use bevy_core_pipeline::core_3d::Camera3d;
use bevy_core_pipeline::oit::OrderIndependentTransparencySettings;
use bevy_core_pipeline::prepass::{DeferredPrepass, DepthPrepass, NormalPrepass};
use bevy_core_pipeline::tonemapping::{DebandDither, Tonemapping};
use bevy_ecs::component::Tick;
use bevy_ecs::system::SystemChangeTick;
use bevy_render::camera::TemporalJitter;
use bevy_render::prelude::Msaa;
use bevy_render::sync_world::{MainEntity, MainEntityHashMap};
use bevy_render::view::ExtractedView;
use bevy_render::RenderSet::PrepareAssets;
use bytemuck::{Pod, Zeroable};
use nonmax::{NonMaxU16, NonMaxU32};
use smallvec::{smallvec, SmallVec};
use static_assertions::const_assert_eq;
/// Provides support for rendering 3D meshes.
pub struct MeshRenderPlugin {
/// Whether we're building [`MeshUniform`]s on GPU.
///
/// 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,
}
impl MeshRenderPlugin {
/// Creates a new [`MeshRenderPlugin`] with the given debug flags.
pub fn new(debug_flags: RenderDebugFlags) -> MeshRenderPlugin {
MeshRenderPlugin {
use_gpu_instance_buffer_builder: false,
debug_flags,
}
}
}
pub const FORWARD_IO_HANDLE: Handle<Shader> = weak_handle!("38111de1-6e35-4dbb-877b-7b6f9334baf6");
pub const MESH_VIEW_TYPES_HANDLE: Handle<Shader> =
weak_handle!("979493db-4ae1-4003-b5c6-fcbb88b152a2");
pub const MESH_VIEW_BINDINGS_HANDLE: Handle<Shader> =
weak_handle!("c6fe674b-4c21-4d4b-867a-352848da5337");
pub const MESH_TYPES_HANDLE: Handle<Shader> = weak_handle!("a4a3fc2e-a57e-4083-a8ab-2840176927f2");
pub const MESH_BINDINGS_HANDLE: Handle<Shader> =
weak_handle!("84e7f9e6-e566-4a61-914e-c568f5dabf49");
pub const MESH_FUNCTIONS_HANDLE: Handle<Shader> =
weak_handle!("c46aa0f0-6c0c-4b3a-80bf-d8213c771f12");
pub const MESH_SHADER_HANDLE: Handle<Shader> = weak_handle!("1a7bbae8-4b4f-48a7-b53b-e6822e56f321");
pub const SKINNING_HANDLE: Handle<Shader> = weak_handle!("7474e812-2506-4cbf-9de3-fe07e5c6ff24");
pub const MORPH_HANDLE: Handle<Shader> = weak_handle!("da30aac7-34cc-431d-a07f-15b1a783008c");
pub const OCCLUSION_CULLING_HANDLE: Handle<Shader> =
weak_handle!("eaea07d9-7516-482c-aa42-6f8e9927e1f0");
/// How many textures are allowed in the view bind group layout (`@group(0)`) before
/// broader compatibility with WebGL and WebGPU is at risk, due to the minimum guaranteed
/// values for `MAX_TEXTURE_IMAGE_UNITS` (in WebGL) and `maxSampledTexturesPerShaderStage` (in WebGPU),
/// currently both at 16.
///
/// We use 10 here because it still leaves us, in a worst case scenario, with 6 textures for the other bind groups.
///
/// See: <https://gpuweb.github.io/gpuweb/#limits>
#[cfg(debug_assertions)]
pub const MESH_PIPELINE_VIEW_LAYOUT_SAFE_MAX_TEXTURES: usize = 10;
impl Plugin for MeshRenderPlugin {
fn build(&self, app: &mut App) {
load_internal_asset!(app, FORWARD_IO_HANDLE, "forward_io.wgsl", Shader::from_wgsl);
load_internal_asset!(
app,
MESH_VIEW_TYPES_HANDLE,
"mesh_view_types.wgsl",
Shader::from_wgsl_with_defs,
vec![
ShaderDefVal::UInt(
"MAX_DIRECTIONAL_LIGHTS".into(),
MAX_DIRECTIONAL_LIGHTS as u32
),
ShaderDefVal::UInt(
"MAX_CASCADES_PER_LIGHT".into(),
MAX_CASCADES_PER_LIGHT as u32,
)
]
);
load_internal_asset!(
app,
MESH_VIEW_BINDINGS_HANDLE,
"mesh_view_bindings.wgsl",
Shader::from_wgsl
);
load_internal_asset!(app, MESH_TYPES_HANDLE, "mesh_types.wgsl", Shader::from_wgsl);
load_internal_asset!(
app,
MESH_FUNCTIONS_HANDLE,
"mesh_functions.wgsl",
Shader::from_wgsl
);
load_internal_asset!(app, MESH_SHADER_HANDLE, "mesh.wgsl", Shader::from_wgsl);
load_internal_asset!(app, SKINNING_HANDLE, "skinning.wgsl", Shader::from_wgsl);
load_internal_asset!(app, MORPH_HANDLE, "morph.wgsl", Shader::from_wgsl);
load_internal_asset!(
app,
OCCLUSION_CULLING_HANDLE,
"occlusion_culling.wgsl",
Shader::from_wgsl
);
if app.get_sub_app(RenderApp).is_none() {
return;
}
app.add_systems(
PostUpdate,
(no_automatic_skin_batching, no_automatic_morph_batching),
)
.add_plugins((
BinnedRenderPhasePlugin::<Opaque3d, MeshPipeline>::new(self.debug_flags),
BinnedRenderPhasePlugin::<AlphaMask3d, MeshPipeline>::new(self.debug_flags),
BinnedRenderPhasePlugin::<Shadow, MeshPipeline>::new(self.debug_flags),
BinnedRenderPhasePlugin::<Opaque3dDeferred, MeshPipeline>::new(self.debug_flags),
BinnedRenderPhasePlugin::<AlphaMask3dDeferred, MeshPipeline>::new(self.debug_flags),
SortedRenderPhasePlugin::<Transmissive3d, MeshPipeline>::new(self.debug_flags),
SortedRenderPhasePlugin::<Transparent3d, MeshPipeline>::new(self.debug_flags),
));
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<MorphUniforms>()
.init_resource::<MorphIndices>()
.init_resource::<MeshCullingDataBuffer>()
.init_resource::<RenderMaterialInstances>()
.configure_sets(
ExtractSchedule,
ExtractMeshesSet.after(view::extract_visibility_ranges),
)
.add_systems(
ExtractSchedule,
(
extract_skins,
extract_morphs,
gpu_preprocessing::clear_batched_gpu_instance_buffers::<MeshPipeline>
.before(ExtractMeshesSet),
),
)
.add_systems(
Render,
(
set_mesh_motion_vector_flags.in_set(RenderSet::PrepareMeshes),
prepare_skins.in_set(RenderSet::PrepareResources),
prepare_morphs.in_set(RenderSet::PrepareResources),
prepare_mesh_bind_groups.in_set(RenderSet::PrepareBindGroups),
prepare_mesh_view_bind_groups
.in_set(RenderSet::PrepareBindGroups)
.after(prepare_oit_buffers),
no_gpu_preprocessing::clear_batched_cpu_instance_buffers::<MeshPipeline>
.in_set(RenderSet::Cleanup)
.after(RenderSet::Render),
),
);
}
}
fn finish(&self, app: &mut App) {
let mut mesh_bindings_shader_defs = Vec::with_capacity(1);
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<ViewKeyCache>()
.init_resource::<ViewSpecializationTicks>()
.init_resource::<GpuPreprocessingSupport>()
.init_resource::<SkinUniforms>()
.add_systems(
Render,
check_views_need_specialization.in_set(PrepareAssets),
);
let gpu_preprocessing_support =
render_app.world().resource::<GpuPreprocessingSupport>();
let use_gpu_instance_buffer_builder =
self.use_gpu_instance_buffer_builder && gpu_preprocessing_support.is_available();
let render_mesh_instances = RenderMeshInstances::new(use_gpu_instance_buffer_builder);
render_app.insert_resource(render_mesh_instances);
if use_gpu_instance_buffer_builder {
render_app
.init_resource::<gpu_preprocessing::BatchedInstanceBuffers<
MeshUniform,
MeshInputUniform
>>()
.init_resource::<RenderMeshInstanceGpuQueues>()
.init_resource::<MeshesToReextractNextFrame>()
.add_systems(
ExtractSchedule,
extract_meshes_for_gpu_building.in_set(ExtractMeshesSet),
)
.add_systems(
Render,
(
gpu_preprocessing::write_batched_instance_buffers::<MeshPipeline>
.in_set(RenderSet::PrepareResourcesFlush),
gpu_preprocessing::delete_old_work_item_buffers::<MeshPipeline>
.in_set(RenderSet::PrepareResources),
collect_meshes_for_gpu_building
.in_set(RenderSet::PrepareMeshes)
// This must be before
// `set_mesh_motion_vector_flags` so it doesn't
// overwrite those flags.
.before(set_mesh_motion_vector_flags),
),
);
} else {
let render_device = render_app.world().resource::<RenderDevice>();
let cpu_batched_instance_buffer =
no_gpu_preprocessing::BatchedInstanceBuffer::<MeshUniform>::new(render_device);
render_app
.insert_resource(cpu_batched_instance_buffer)
.add_systems(
ExtractSchedule,
extract_meshes_for_cpu_building.in_set(ExtractMeshesSet),
)
.add_systems(
Render,
no_gpu_preprocessing::write_batched_instance_buffer::<MeshPipeline>
.in_set(RenderSet::PrepareResourcesFlush),
);
};
let render_device = render_app.world().resource::<RenderDevice>();
if let Some(per_object_buffer_batch_size) =
GpuArrayBuffer::<MeshUniform>::batch_size(render_device)
{
mesh_bindings_shader_defs.push(ShaderDefVal::UInt(
"PER_OBJECT_BUFFER_BATCH_SIZE".into(),
per_object_buffer_batch_size,
));
}
render_app
.init_resource::<MeshPipelineViewLayouts>()
.init_resource::<MeshPipeline>();
}
// Load the mesh_bindings shader module here as it depends on runtime information about
// whether storage buffers are supported, or the maximum uniform buffer binding size.
load_internal_asset!(
app,
MESH_BINDINGS_HANDLE,
"mesh_bindings.wgsl",
Shader::from_wgsl_with_defs,
mesh_bindings_shader_defs
);
}
}
#[derive(Resource, Deref, DerefMut, Default, Debug, Clone)]
pub struct ViewKeyCache(HashMap<RetainedViewEntity, MeshPipelineKey>);
#[derive(Resource, Deref, DerefMut, Default, Debug, Clone)]
pub struct ViewSpecializationTicks(HashMap<RetainedViewEntity, Tick>);
pub fn check_views_need_specialization(
mut view_key_cache: ResMut<ViewKeyCache>,
mut view_specialization_ticks: ResMut<ViewSpecializationTicks>,
mut views: Query<(
&ExtractedView,
&Msaa,
Option<&Tonemapping>,
Option<&DebandDither>,
Option<&ShadowFilteringMethod>,
Has<ScreenSpaceAmbientOcclusion>,
(
Has<NormalPrepass>,
Has<DepthPrepass>,
Has<MotionVectorPrepass>,
Has<DeferredPrepass>,
),
Option<&Camera3d>,
Has<TemporalJitter>,
Option<&Projection>,
Has<DistanceFog>,
(
Has<RenderViewLightProbes<EnvironmentMapLight>>,
Has<RenderViewLightProbes<IrradianceVolume>>,
),
Has<OrderIndependentTransparencySettings>,
)>,
ticks: SystemChangeTick,
) {
for (
view,
msaa,
tonemapping,
dither,
shadow_filter_method,
ssao,
(normal_prepass, depth_prepass, motion_vector_prepass, deferred_prepass),
camera_3d,
temporal_jitter,
projection,
distance_fog,
(has_environment_maps, has_irradiance_volumes),
has_oit,
) in views.iter_mut()
{
let mut view_key = MeshPipelineKey::from_msaa_samples(msaa.samples())
| MeshPipelineKey::from_hdr(view.hdr);
if normal_prepass {
view_key |= MeshPipelineKey::NORMAL_PREPASS;
}
if depth_prepass {
view_key |= MeshPipelineKey::DEPTH_PREPASS;
}
if motion_vector_prepass {
view_key |= MeshPipelineKey::MOTION_VECTOR_PREPASS;
}
if deferred_prepass {
view_key |= MeshPipelineKey::DEFERRED_PREPASS;
}
if temporal_jitter {
view_key |= MeshPipelineKey::TEMPORAL_JITTER;
}
if has_environment_maps {
view_key |= MeshPipelineKey::ENVIRONMENT_MAP;
}
if has_irradiance_volumes {
view_key |= MeshPipelineKey::IRRADIANCE_VOLUME;
}
if has_oit {
view_key |= MeshPipelineKey::OIT_ENABLED;
}
if let Some(projection) = projection {
view_key |= match projection {
Projection::Perspective(_) => MeshPipelineKey::VIEW_PROJECTION_PERSPECTIVE,
Projection::Orthographic(_) => MeshPipelineKey::VIEW_PROJECTION_ORTHOGRAPHIC,
Projection::Custom(_) => MeshPipelineKey::VIEW_PROJECTION_NONSTANDARD,
};
}
match shadow_filter_method.unwrap_or(&ShadowFilteringMethod::default()) {
ShadowFilteringMethod::Hardware2x2 => {
view_key |= MeshPipelineKey::SHADOW_FILTER_METHOD_HARDWARE_2X2;
}
ShadowFilteringMethod::Gaussian => {
view_key |= MeshPipelineKey::SHADOW_FILTER_METHOD_GAUSSIAN;
}
ShadowFilteringMethod::Temporal => {
view_key |= MeshPipelineKey::SHADOW_FILTER_METHOD_TEMPORAL;
}
}
if !view.hdr {
if let Some(tonemapping) = tonemapping {
view_key |= MeshPipelineKey::TONEMAP_IN_SHADER;
view_key |= tonemapping_pipeline_key(*tonemapping);
}
if let Some(DebandDither::Enabled) = dither {
view_key |= MeshPipelineKey::DEBAND_DITHER;
}
}
if ssao {
view_key |= MeshPipelineKey::SCREEN_SPACE_AMBIENT_OCCLUSION;
}
if distance_fog {
view_key |= MeshPipelineKey::DISTANCE_FOG;
}
if let Some(camera_3d) = camera_3d {
view_key |= screen_space_specular_transmission_pipeline_key(
camera_3d.screen_space_specular_transmission_quality,
);
}
if !view_key_cache
.get_mut(&view.retained_view_entity)
.is_some_and(|current_key| *current_key == view_key)
{
view_key_cache.insert(view.retained_view_entity, view_key);
view_specialization_ticks.insert(view.retained_view_entity, ticks.this_run());
}
}
}
#[derive(Component)]
pub struct MeshTransforms {
pub world_from_local: Affine3,
pub previous_world_from_local: Affine3,
pub flags: u32,
}
#[derive(ShaderType, Clone)]
pub struct MeshUniform {
// Affine 4x3 matrices transposed to 3x4
pub world_from_local: [Vec4; 3],
pub previous_world_from_local: [Vec4; 3],
// 3x3 matrix packed in mat2x4 and f32 as:
// [0].xyz, [1].x,
// [1].yz, [2].xy
// [2].z
pub local_from_world_transpose_a: [Vec4; 2],
pub local_from_world_transpose_b: f32,
pub flags: u32,
// Four 16-bit unsigned normalized UV values packed into a `UVec2`:
//
// <--- MSB LSB --->
// +---- min v ----+ +---- min u ----+
// lightmap_uv_rect.x: vvvvvvvv vvvvvvvv uuuuuuuu uuuuuuuu,
// +---- max v ----+ +---- max u ----+
// lightmap_uv_rect.y: VVVVVVVV VVVVVVVV UUUUUUUU UUUUUUUU,
//
// (MSB: most significant bit; LSB: least significant bit.)
pub lightmap_uv_rect: UVec2,
/// The index of this mesh's first vertex in the vertex buffer.
///
/// Multiple meshes can be packed into a single vertex buffer (see
/// [`MeshAllocator`]). This value stores the offset of the first vertex in
/// this mesh in that buffer.
pub first_vertex_index: u32,
/// The current skin index, or `u32::MAX` if there's no skin.
pub current_skin_index: u32,
/// The material and lightmap indices, packed into 32 bits.
///
/// Low 16 bits: index of the material inside the bind group data.
/// High 16 bits: index of the lightmap in the binding array.
pub material_and_lightmap_bind_group_slot: u32,
/// User supplied tag to identify this mesh instance.
pub tag: u32,
/// Padding.
pub pad: u32,
}
/// Information that has to be transferred from CPU to GPU in order to produce
/// the full [`MeshUniform`].
///
/// This is essentially a subset of the fields in [`MeshUniform`] above.
#[derive(ShaderType, Pod, Zeroable, Clone, Copy, Default, Debug)]
#[repr(C)]
pub struct MeshInputUniform {
/// Affine 4x3 matrix transposed to 3x4.
pub world_from_local: [Vec4; 3],
/// Four 16-bit unsigned normalized UV values packed into a `UVec2`:
///
/// ```text
/// <--- MSB LSB --->
/// +---- min v ----+ +---- min u ----+
/// lightmap_uv_rect.x: vvvvvvvv vvvvvvvv uuuuuuuu uuuuuuuu,
/// +---- max v ----+ +---- max u ----+
/// lightmap_uv_rect.y: VVVVVVVV VVVVVVVV UUUUUUUU UUUUUUUU,
///
/// (MSB: most significant bit; LSB: least significant bit.)
/// ```
pub lightmap_uv_rect: UVec2,
/// Various [`MeshFlags`].
pub flags: u32,
/// The index of this mesh's [`MeshInputUniform`] in the previous frame's
/// buffer, if applicable.
///
/// This is used for TAA. If not present, this will be `u32::MAX`.
pub previous_input_index: u32,
/// The index of this mesh's first vertex in the vertex buffer.
///
/// Multiple meshes can be packed into a single vertex buffer (see
/// [`MeshAllocator`]). This value stores the offset of the first vertex in
/// this mesh in that buffer.
pub first_vertex_index: u32,
/// The index of this mesh's first index in the index buffer, if any.
///
/// Multiple meshes can be packed into a single index buffer (see
/// [`MeshAllocator`]). This value stores the offset of the first index in
/// this mesh in that buffer.
///
/// If this mesh isn't indexed, this value is ignored.
pub first_index_index: u32,
/// For an indexed mesh, the number of indices that make it up; for a
/// non-indexed mesh, the number of vertices in it.
pub index_count: u32,
/// The current skin index, or `u32::MAX` if there's no skin.
pub current_skin_index: u32,
/// The material and lightmap indices, packed into 32 bits.
///
/// Low 16 bits: index of the material inside the bind group data.
/// High 16 bits: index of the lightmap in the binding array.
pub material_and_lightmap_bind_group_slot: u32,
/// The number of the frame on which this [`MeshInputUniform`] was built.
///
/// This is used to validate the previous transform and skin. If this
/// [`MeshInputUniform`] wasn't updated on this frame, then we know that
/// neither this mesh's transform nor that of its joints have been updated
/// on this frame, and therefore the transforms of both this mesh and its
/// joints must be identical to those for the previous frame.
pub timestamp: u32,
/// User supplied tag to identify this mesh instance.
pub tag: u32,
/// Padding.
pub pad: u32,
}
/// Information about each mesh instance needed to cull it on GPU.
///
/// This consists of its axis-aligned bounding box (AABB).
#[derive(ShaderType, Pod, Zeroable, Clone, Copy, Default)]
#[repr(C)]
pub struct MeshCullingData {
/// The 3D center of the AABB in model space, padded with an extra unused
/// float value.
pub aabb_center: Vec4,
/// The 3D extents of the AABB in model space, divided by two, padded with
/// an extra unused float value.
pub aabb_half_extents: Vec4,
}
/// A GPU buffer that holds the information needed to cull meshes on GPU.
///
/// At the moment, this simply holds each mesh's AABB.
///
/// To avoid wasting CPU time in the CPU culling case, this buffer will be empty
/// if GPU culling isn't in use.
#[derive(Resource, Deref, DerefMut)]
pub struct MeshCullingDataBuffer(RawBufferVec<MeshCullingData>);
impl MeshUniform {
pub fn new(
mesh_transforms: &MeshTransforms,
first_vertex_index: u32,
material_bind_group_slot: MaterialBindGroupSlot,
maybe_lightmap: Option<(LightmapSlotIndex, Rect)>,
current_skin_index: Option<u32>,
tag: Option<u32>,
) -> Self {
let (local_from_world_transpose_a, local_from_world_transpose_b) =
mesh_transforms.world_from_local.inverse_transpose_3x3();
let lightmap_bind_group_slot = match maybe_lightmap {
None => u16::MAX,
Some((slot_index, _)) => slot_index.into(),
};
Self {
world_from_local: mesh_transforms.world_from_local.to_transpose(),
previous_world_from_local: mesh_transforms.previous_world_from_local.to_transpose(),
lightmap_uv_rect: pack_lightmap_uv_rect(maybe_lightmap.map(|(_, uv_rect)| uv_rect)),
local_from_world_transpose_a,
local_from_world_transpose_b,
flags: mesh_transforms.flags,
first_vertex_index,
current_skin_index: current_skin_index.unwrap_or(u32::MAX),
material_and_lightmap_bind_group_slot: u32::from(material_bind_group_slot)
| ((lightmap_bind_group_slot as u32) << 16),
tag: tag.unwrap_or(0),
pad: 0,
}
}
}
// NOTE: These must match the bit flags in bevy_pbr/src/render/mesh_types.wgsl!
bitflags::bitflags! {
/// Various flags and tightly-packed values on a mesh.
///
/// Flags grow from the top bit down; other values grow from the bottom bit
/// up.
#[repr(transparent)]
pub struct MeshFlags: u32 {
/// Bitmask for the 16-bit index into the LOD array.
///
/// This will be `u16::MAX` if this mesh has no LOD.
const LOD_INDEX_MASK = (1 << 16) - 1;
/// Disables frustum culling for this mesh.
///
/// This corresponds to the
/// [`bevy_render::view::visibility::NoFrustumCulling`] component.
const NO_FRUSTUM_CULLING = 1 << 28;
const SHADOW_RECEIVER = 1 << 29;
const TRANSMITTED_SHADOW_RECEIVER = 1 << 30;
// Indicates the sign of the determinant of the 3x3 model matrix. If the sign is positive,
// then the flag should be set, else it should not be set.
const SIGN_DETERMINANT_MODEL_3X3 = 1 << 31;
const NONE = 0;
const UNINITIALIZED = 0xFFFFFFFF;
}
}
impl MeshFlags {
fn from_components(
transform: &GlobalTransform,
lod_index: Option<NonMaxU16>,
no_frustum_culling: bool,
not_shadow_receiver: bool,
transmitted_receiver: bool,
) -> MeshFlags {
let mut mesh_flags = if not_shadow_receiver {
MeshFlags::empty()
} else {
MeshFlags::SHADOW_RECEIVER
};
if no_frustum_culling {
mesh_flags |= MeshFlags::NO_FRUSTUM_CULLING;
}
if transmitted_receiver {
mesh_flags |= MeshFlags::TRANSMITTED_SHADOW_RECEIVER;
}
if transform.affine().matrix3.determinant().is_sign_positive() {
mesh_flags |= MeshFlags::SIGN_DETERMINANT_MODEL_3X3;
}
let lod_index_bits = match lod_index {
None => u16::MAX,
Some(lod_index) => u16::from(lod_index),
};
mesh_flags |=
MeshFlags::from_bits_retain((lod_index_bits as u32) << MeshFlags::LOD_INDEX_SHIFT);
mesh_flags
}
/// The first bit of the LOD index.
pub const LOD_INDEX_SHIFT: u32 = 0;
}
bitflags::bitflags! {
/// Various useful flags for [`RenderMeshInstance`]s.
#[derive(Clone, Copy)]
pub struct RenderMeshInstanceFlags: u8 {
/// The mesh casts shadows.
const SHADOW_CASTER = 1 << 0;
/// The mesh can participate in automatic batching.
const AUTOMATIC_BATCHING = 1 << 1;
/// The mesh had a transform last frame and so is eligible for motion
/// vector computation.
const HAS_PREVIOUS_TRANSFORM = 1 << 2;
/// The mesh had a skin last frame and so that skin should be taken into
/// account for motion vector computation.
const HAS_PREVIOUS_SKIN = 1 << 3;
/// The mesh had morph targets last frame and so they should be taken
/// into account for motion vector computation.
const HAS_PREVIOUS_MORPH = 1 << 4;
}
}
/// CPU data that the render world keeps for each entity, when *not* using GPU
/// mesh uniform building.
#[derive(Deref, DerefMut)]
pub struct RenderMeshInstanceCpu {
/// Data shared between both the CPU mesh uniform building and the GPU mesh
/// uniform building paths.
#[deref]
pub shared: RenderMeshInstanceShared,
/// The transform of the mesh.
///
/// This will be written into the [`MeshUniform`] at the appropriate time.
pub transforms: MeshTransforms,
}
/// CPU data that the render world needs to keep for each entity that contains a
/// mesh when using GPU mesh uniform building.
#[derive(Deref, DerefMut)]
pub struct RenderMeshInstanceGpu {
/// Data shared between both the CPU mesh uniform building and the GPU mesh
/// uniform building paths.
#[deref]
pub shared: RenderMeshInstanceShared,
/// The translation of the mesh.
///
/// This is the only part of the transform that we have to keep on CPU (for
/// distance sorting).
pub translation: Vec3,
/// The index of the [`MeshInputUniform`] in the buffer.
pub current_uniform_index: NonMaxU32,
}
/// CPU data that the render world needs to keep about each entity that contains
/// a mesh.
pub struct RenderMeshInstanceShared {
/// The [`AssetId`] of the mesh.
pub mesh_asset_id: AssetId<Mesh>,
/// A slot for the material bind group index.
pub material_bindings_index: MaterialBindingId,
/// Various flags.
pub flags: RenderMeshInstanceFlags,
/// Index of the slab that the lightmap resides in, if a lightmap is
/// present.
pub lightmap_slab_index: Option<LightmapSlabIndex>,
/// User supplied tag to identify this mesh instance.
pub tag: u32,
}
/// Information that is gathered during the parallel portion of mesh extraction
/// when GPU mesh uniform building is enabled.
///
/// From this, the [`MeshInputUniform`] and [`RenderMeshInstanceGpu`] are
/// prepared.
pub struct RenderMeshInstanceGpuBuilder {
/// Data that will be placed on the [`RenderMeshInstanceGpu`].
pub shared: RenderMeshInstanceShared,
/// The current transform.
pub world_from_local: Affine3,
/// Four 16-bit unsigned normalized UV values packed into a [`UVec2`]:
///
/// ```text
/// <--- MSB LSB --->
/// +---- min v ----+ +---- min u ----+
/// lightmap_uv_rect.x: vvvvvvvv vvvvvvvv uuuuuuuu uuuuuuuu,
/// +---- max v ----+ +---- max u ----+
/// lightmap_uv_rect.y: VVVVVVVV VVVVVVVV UUUUUUUU UUUUUUUU,
///
/// (MSB: most significant bit; LSB: least significant bit.)
/// ```
pub lightmap_uv_rect: UVec2,
/// The index of the previous mesh input.
pub previous_input_index: Option<NonMaxU32>,
/// Various flags.
pub mesh_flags: MeshFlags,
}
/// The per-thread queues used during [`extract_meshes_for_gpu_building`].
///
/// There are two varieties of these: one for when culling happens on CPU and
/// one for when culling happens on GPU. Having the two varieties avoids wasting
/// space if GPU culling is disabled.
#[derive(Default)]
pub enum RenderMeshInstanceGpuQueue {
/// The default value.
///
/// This becomes [`RenderMeshInstanceGpuQueue::CpuCulling`] or
/// [`RenderMeshInstanceGpuQueue::GpuCulling`] once extraction starts.
#[default]
None,
/// The version of [`RenderMeshInstanceGpuQueue`] that omits the
/// [`MeshCullingData`], so that we don't waste space when GPU
/// culling is disabled.
CpuCulling {
/// Stores GPU data for each entity that became visible or changed in
/// such a way that necessitates updating the [`MeshInputUniform`] (e.g.
/// changed transform).
changed: Vec<(MainEntity, RenderMeshInstanceGpuBuilder)>,
/// Stores the IDs of entities that became invisible this frame.
removed: Vec<MainEntity>,
},
/// The version of [`RenderMeshInstanceGpuQueue`] that contains the
/// [`MeshCullingData`], used when any view has GPU culling
/// enabled.
GpuCulling {
/// Stores GPU data for each entity that became visible or changed in
/// such a way that necessitates updating the [`MeshInputUniform`] (e.g.
/// changed transform).
changed: Vec<(MainEntity, RenderMeshInstanceGpuBuilder, MeshCullingData)>,
/// Stores the IDs of entities that became invisible this frame.
removed: Vec<MainEntity>,
},
}
/// The per-thread queues containing mesh instances, populated during the
/// extract phase.
///
/// These are filled in [`extract_meshes_for_gpu_building`] and consumed in
/// [`collect_meshes_for_gpu_building`].
#[derive(Resource, Default, Deref, DerefMut)]
pub struct RenderMeshInstanceGpuQueues(Parallel<RenderMeshInstanceGpuQueue>);
/// Holds a list of meshes that couldn't be extracted this frame because their
/// materials weren't prepared yet.
///
/// On subsequent frames, we try to reextract those meshes.
#[derive(Resource, Default, Deref, DerefMut)]
pub struct MeshesToReextractNextFrame(MainEntityHashSet);
impl RenderMeshInstanceShared {
fn from_components(
previous_transform: Option<&PreviousGlobalTransform>,
mesh: &Mesh3d,
tag: Option<&MeshTag>,
not_shadow_caster: bool,
no_automatic_batching: bool,
) -> Self {
let mut mesh_instance_flags = RenderMeshInstanceFlags::empty();
mesh_instance_flags.set(RenderMeshInstanceFlags::SHADOW_CASTER, !not_shadow_caster);
mesh_instance_flags.set(
RenderMeshInstanceFlags::AUTOMATIC_BATCHING,
!no_automatic_batching,
);
mesh_instance_flags.set(
RenderMeshInstanceFlags::HAS_PREVIOUS_TRANSFORM,
previous_transform.is_some(),
);
RenderMeshInstanceShared {
mesh_asset_id: mesh.id(),
flags: mesh_instance_flags,
// This gets filled in later, during `RenderMeshGpuBuilder::update`.
material_bindings_index: default(),
lightmap_slab_index: None,
tag: tag.map_or(0, |i| **i),
}
}
/// Returns true if this entity is eligible to participate in automatic
/// batching.
#[inline]
pub fn should_batch(&self) -> bool {
self.flags
.contains(RenderMeshInstanceFlags::AUTOMATIC_BATCHING)
}
}
/// Information that the render world keeps about each entity that contains a
/// mesh.
///
/// The set of information needed is different depending on whether CPU or GPU
/// [`MeshUniform`] building is in use.
#[derive(Resource)]
pub enum RenderMeshInstances {
/// Information needed when using CPU mesh instance data building.
CpuBuilding(RenderMeshInstancesCpu),
/// Information needed when using GPU mesh instance data building.
GpuBuilding(RenderMeshInstancesGpu),
}
/// Information that the render world keeps about each entity that contains a
/// mesh, when using CPU mesh instance data building.
#[derive(Default, Deref, DerefMut)]
pub struct RenderMeshInstancesCpu(MainEntityHashMap<RenderMeshInstanceCpu>);
/// Information that the render world keeps about each entity that contains a
/// mesh, when using GPU mesh instance data building.
#[derive(Default, Deref, DerefMut)]
pub struct RenderMeshInstancesGpu(MainEntityHashMap<RenderMeshInstanceGpu>);
impl RenderMeshInstances {
/// Creates a new [`RenderMeshInstances`] instance.
fn new(use_gpu_instance_buffer_builder: bool) -> RenderMeshInstances {
if use_gpu_instance_buffer_builder {
RenderMeshInstances::GpuBuilding(RenderMeshInstancesGpu::default())
} else {
RenderMeshInstances::CpuBuilding(RenderMeshInstancesCpu::default())
}
}
/// Returns the ID of the mesh asset attached to the given entity, if any.
pub fn mesh_asset_id(&self, entity: MainEntity) -> Option<AssetId<Mesh>> {
match *self {
RenderMeshInstances::CpuBuilding(ref instances) => instances.mesh_asset_id(entity),
RenderMeshInstances::GpuBuilding(ref instances) => instances.mesh_asset_id(entity),
}
}
/// Constructs [`RenderMeshQueueData`] for the given entity, if it has a
/// mesh attached.
pub fn render_mesh_queue_data(&self, entity: MainEntity) -> Option<RenderMeshQueueData> {
match *self {
RenderMeshInstances::CpuBuilding(ref instances) => {
instances.render_mesh_queue_data(entity)
}
RenderMeshInstances::GpuBuilding(ref instances) => {
instances.render_mesh_queue_data(entity)
}
}
}
/// Inserts the given flags into the CPU or GPU render mesh instance data
/// for the given mesh as appropriate.
fn insert_mesh_instance_flags(&mut self, entity: MainEntity, flags: RenderMeshInstanceFlags) {
match *self {
RenderMeshInstances::CpuBuilding(ref mut instances) => {
instances.insert_mesh_instance_flags(entity, flags);
}
RenderMeshInstances::GpuBuilding(ref mut instances) => {
instances.insert_mesh_instance_flags(entity, flags);
}
}
}
}
impl RenderMeshInstancesCpu {
fn mesh_asset_id(&self, entity: MainEntity) -> Option<AssetId<Mesh>> {
self.get(&entity)
.map(|render_mesh_instance| render_mesh_instance.mesh_asset_id)
}
fn render_mesh_queue_data(&self, entity: MainEntity) -> Option<RenderMeshQueueData> {
self.get(&entity)
.map(|render_mesh_instance| RenderMeshQueueData {
shared: &render_mesh_instance.shared,
translation: render_mesh_instance.transforms.world_from_local.translation,
current_uniform_index: InputUniformIndex::default(),
})
}
/// Inserts the given flags into the render mesh instance data for the given
/// mesh.
fn insert_mesh_instance_flags(&mut self, entity: MainEntity, flags: RenderMeshInstanceFlags) {
if let Some(instance) = self.get_mut(&entity) {
instance.flags.insert(flags);
}
}
}
impl RenderMeshInstancesGpu {
fn mesh_asset_id(&self, entity: MainEntity) -> Option<AssetId<Mesh>> {
self.get(&entity)
.map(|render_mesh_instance| render_mesh_instance.mesh_asset_id)
}
fn render_mesh_queue_data(&self, entity: MainEntity) -> Option<RenderMeshQueueData> {
self.get(&entity)
.map(|render_mesh_instance| RenderMeshQueueData {
shared: &render_mesh_instance.shared,
translation: render_mesh_instance.translation,
current_uniform_index: InputUniformIndex(
render_mesh_instance.current_uniform_index.into(),
),
})
}
/// Inserts the given flags into the render mesh instance data for the given
/// mesh.
fn insert_mesh_instance_flags(&mut self, entity: MainEntity, flags: RenderMeshInstanceFlags) {
if let Some(instance) = self.get_mut(&entity) {
instance.flags.insert(flags);
}
}
}
impl RenderMeshInstanceGpuQueue {
/// Clears out a [`RenderMeshInstanceGpuQueue`], creating or recreating it
/// as necessary.
///
/// `any_gpu_culling` should be set to true if any view has GPU culling
/// enabled.
fn init(&mut self, any_gpu_culling: bool) {
match (any_gpu_culling, &mut *self) {