1pub mod card;
85pub mod field;
86pub mod placement;
87pub mod shell;
88
89use crcbl_hal::{
90 BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
91 BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
92 BufferUsage, ClearValue, ColorTargetState, CompareOp, ComputePipelineHandle, DepthBias,
93 DepthStencilState, Device, DrawIndirect, FilterMode, Format, GraphicsPipelineDesc,
94 GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
95 MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveTopology, ResourceState,
96 SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
97 ShaderStages, StoreOp, check_portable_storage_buffers,
98};
99use crcbl_shaders::grass::{
100 BLADE_FAR_DRAW, BLADE_NEAR_DRAW, BLADE_STRIDE, CARD_DRAW, DRAW_ARGS_SIZE, FIELD_BLOCK_SIZE,
101 FIN_DRAW, GEN_PARAMS_SIZE, GenParams, INSTANCE_STRIDE, PARAMS_SIZE, Params, SHELL_DRAW,
102 SLOT_ARGS_SIZE, TILE_SIZE, Tile, WORKGROUP_SIZE,
103};
104use crcbl_shaders::wind::{PARAMS_SIZE as WIND_PARAMS_SIZE, WindParams};
105use crcbl_shaders::{GRASS, GRASS_GEN, Stage};
106
107use crate::draw_gen::compute_pipeline_entry;
108use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
109use crate::ssao::cached_group;
110use crate::texture::{UploadedTexture, upload_texture, upload_texture_mip_layers};
111
112pub use field::{
113 BladeLod, BladeLook, BladeNormal, BladeShape, BladeStyle, BladeType, CELLS_PER_TILE, Clumping,
114 CoverMap, GrassError, GrassField, Heightfield, MAX_BLADES, MAX_TILES, SLOT_CAPACITY, Shells,
115};
116
117#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct WindLayer {
131 pub texels: [u32; 2],
133 pub rgba8: Vec<u8>,
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct WindLayers {
140 pub direction: WindLayer,
142 pub intensity: WindLayer,
144}
145
146const CALM_DIRECTION: [u8; 4] = [255, 128, 0, 255];
153
154const CALM_INTENSITY: [u8; 4] = [0, 0, 0, 255];
162
163#[derive(Debug, thiserror::Error)]
165pub enum WindLayerError {
166 #[error("a {width}x{height} wind layer has no texels")]
168 Empty {
169 width: u32,
171 height: u32,
173 },
174 #[error("a {width}x{height} wind layer is {expected} bytes of RGBA8, and {found} arrived")]
176 Size {
177 width: u32,
179 height: u32,
181 expected: usize,
183 found: usize,
185 },
186 #[error("a wind layer could not be uploaded: {0}")]
188 Hal(#[from] HalError),
189}
190
191impl WindLayer {
192 fn check(&self) -> Result<(), WindLayerError> {
193 let [width, height] = self.texels;
194 if width == 0 || height == 0 {
195 return Err(WindLayerError::Empty { width, height });
196 }
197 let expected = width as usize * height as usize * 4;
198 if self.rgba8.len() != expected {
199 return Err(WindLayerError::Size {
200 width,
201 height,
202 expected,
203 found: self.rgba8.len(),
204 });
205 }
206 Ok(())
207 }
208}
209
210#[derive(Clone, Copy, Debug)]
230pub struct GrassBuffers {
231 pub instances: crcbl_hal::BufferHandle,
234 pub cells: crcbl_hal::BufferHandle,
237 pub args: crcbl_hal::BufferHandle,
239 pub slots: u32,
241}
242
243#[derive(Clone, Copy, Debug)]
246pub(crate) struct GrassFrame {
247 pub(crate) instances: BufferHandle,
248 pub(crate) cells: BufferHandle,
249 pub(crate) args: BufferHandle,
250 pub(crate) blades: BufferHandle,
251 pub(crate) tiles: BufferHandle,
252 pub(crate) field_block: BufferHandle,
253 pub(crate) ground: ImageViewHandle,
254 pub(crate) cover: ImageViewHandle,
255 pub(crate) card: ImageViewHandle,
256 pub(crate) wind_direction: ImageViewHandle,
257 pub(crate) wind_intensity: ImageViewHandle,
258 pub(crate) slots: u32,
260 pub(crate) shells: bool,
263 pub(crate) fins: bool,
265 pub(crate) mesh_blades: bool,
268 pub(crate) generation: GenParams,
270}
271
272impl GrassFrame {
273 pub(crate) const fn draws_per_slot(&self) -> u32 {
277 1 + self.shells as u32 + (self.shells && self.fins) as u32 + 2 * self.mesh_blades as u32
278 }
279
280 pub(crate) const fn rows(&self) -> u32 {
282 self.generation.limits[1]
283 }
284
285 pub(crate) fn gen_params(&self, camera: glam::Vec3) -> GenParams {
287 let mut params = self.generation;
288 params.camera = [camera.x, camera.y, camera.z, self.generation.camera[3]];
289 params
290 }
291}
292
293#[derive(Debug)]
296pub(crate) struct GrassScene {
297 field: Option<GrassField>,
298 live: Option<Resident>,
299 wind: Wind,
300 retired: Vec<(u64, Retired)>,
308 frames: u64,
310 depth: u64,
312}
313
314#[derive(Debug)]
316struct Resident {
317 instances: BufferHandle,
318 cells: BufferHandle,
319 args: BufferHandle,
320 blades: BufferHandle,
321 tiles: BufferHandle,
322 field_block: BufferHandle,
323 ground: UploadedTexture,
324 cover: UploadedTexture,
325 card: UploadedTexture,
326 slots: u32,
327 shells: bool,
328 fins: bool,
329 mesh_blades: bool,
330 generation: GenParams,
331}
332
333#[derive(Debug)]
335struct Wind {
336 direction: UploadedTexture,
337 intensity: UploadedTexture,
338}
339
340#[derive(Debug)]
342enum Retired {
343 Field(Box<Resident>),
344 Wind(Box<Wind>),
345}
346
347impl GrassScene {
348 pub(crate) fn new(
354 device: &dyn Device,
355 queue: crcbl_hal::QueueHandle,
356 frames: usize,
357 ) -> Result<Self, HalError> {
358 Ok(Self {
359 field: None,
360 live: None,
361 wind: Wind::calm(device, queue)?,
362 retired: Vec::new(),
363 frames: 0,
364 depth: frames as u64,
365 })
366 }
367
368 pub(crate) fn field(&self) -> Option<&GrassField> {
370 self.field.as_ref()
371 }
372
373 pub(crate) fn set(
383 &mut self,
384 device: &dyn Device,
385 queue: crcbl_hal::QueueHandle,
386 field: Option<&GrassField>,
387 ) -> Result<(), SetError> {
388 let resident = match field {
389 Some(field) => Some(Resident::upload(device, queue, field)?),
390 None => None,
391 };
392 if let Some(old) = self.live.take() {
393 self.retired
394 .push((self.frames, Retired::Field(Box::new(old))));
395 }
396 self.live = resident;
397 self.field = field.cloned();
398 Ok(())
399 }
400
401 pub(crate) fn set_wind_layers(
408 &mut self,
409 device: &dyn Device,
410 queue: crcbl_hal::QueueHandle,
411 layers: Option<&WindLayers>,
412 ) -> Result<(), WindLayerError> {
413 let wind = match layers {
414 Some(layers) => Wind::upload(device, queue, layers)?,
415 None => Wind::calm(device, queue)?,
416 };
417 let old = core::mem::replace(&mut self.wind, wind);
418 self.retired
419 .push((self.frames, Retired::Wind(Box::new(old))));
420 Ok(())
421 }
422
423 pub(crate) fn begin_frame(&mut self, device: &dyn Device) {
425 self.frames += 1;
426 let depth = self.depth;
427 let now = self.frames;
428 let mut kept = Vec::new();
429 for (at, retired) in self.retired.drain(..) {
430 if now.saturating_sub(at) > depth {
431 match retired {
432 Retired::Field(resident) => resident.destroy(device),
433 Retired::Wind(wind) => wind.destroy(device),
434 }
435 } else {
436 kept.push((at, retired));
437 }
438 }
439 self.retired = kept;
440 }
441
442 pub(crate) fn buffers(&self) -> Option<GrassBuffers> {
445 let live = self.live.as_ref()?;
446 Some(GrassBuffers {
447 instances: live.instances,
448 cells: live.cells,
449 args: live.args,
450 slots: live.slots,
451 })
452 }
453
454 pub(crate) fn frame(&self) -> Option<GrassFrame> {
456 let live = self.live.as_ref()?;
457 Some(GrassFrame {
458 instances: live.instances,
459 cells: live.cells,
460 args: live.args,
461 blades: live.blades,
462 tiles: live.tiles,
463 field_block: live.field_block,
464 ground: live.ground.view,
465 cover: live.cover.view,
466 card: live.card.view,
467 wind_direction: self.wind.direction.view,
468 wind_intensity: self.wind.intensity.view,
469 slots: live.slots,
470 shells: live.shells,
471 fins: live.fins,
472 mesh_blades: live.mesh_blades,
473 generation: live.generation,
474 })
475 }
476
477 pub(crate) fn destroy(self, device: &dyn Device) {
479 for (_, retired) in self.retired {
480 match retired {
481 Retired::Field(resident) => resident.destroy(device),
482 Retired::Wind(wind) => wind.destroy(device),
483 }
484 }
485 if let Some(live) = self.live {
486 live.destroy(device);
487 }
488 self.wind.destroy(device);
489 }
490}
491
492#[derive(Debug, thiserror::Error)]
494pub enum SetError {
495 #[error(transparent)]
497 Field(#[from] GrassError),
498 #[error("a grass field could not be uploaded: {0}")]
500 Hal(#[from] HalError),
501}
502
503impl Resident {
504 fn upload(
507 device: &dyn Device,
508 queue: crcbl_hal::QueueHandle,
509 field: &GrassField,
510 ) -> Result<Self, SetError> {
511 let ground = field.ground();
512 let cover = field.cover();
513 let ground_image = upload_texture(
514 device,
515 queue,
516 "grass ground",
517 Format::R32Float,
518 ground.texels[0],
519 ground.texels[1],
520 &ground.to_bytes(),
521 )?;
522 let cover_image = match upload_texture(
523 device,
524 queue,
525 "grass cover",
526 Format::Rgba8Unorm,
527 cover.texels[0],
528 cover.texels[1],
529 &cover.to_bytes(),
530 ) {
531 Ok(image) => image,
532 Err(error) => {
533 ground_image.destroy(device);
534 return Err(error.into());
535 }
536 };
537 let chain = card::coverage_chain(&card::blade_mask(card::CARD_EXTENT), card::CARD_EXTENT);
538 let levels: Vec<&[u8]> = chain.iter().map(Vec::as_slice).collect();
539 let card_image = match upload_texture_mip_layers(
540 device,
541 queue,
542 "grass card",
543 Format::R8Unorm,
544 card::CARD_EXTENT,
545 card::CARD_EXTENT,
546 &[&levels],
547 ) {
548 Ok(image) => image,
549 Err(error) => {
550 cover_image.destroy(device);
551 ground_image.destroy(device);
552 return Err(error.into());
553 }
554 };
555
556 let slots = field.slots();
557 let descs = [
558 (
559 "grass instances",
560 field.instance_bytes(),
561 BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
562 MemoryLocation::DeviceLocal,
563 ),
564 (
565 "grass draw args",
566 u64::from(slots) * SLOT_ARGS_SIZE as u64,
567 BufferUsage::STORAGE | BufferUsage::INDIRECT | BufferUsage::TRANSFER_SRC,
568 MemoryLocation::DeviceLocal,
569 ),
570 (
571 "grass blades",
572 field.blade_bytes(),
573 BufferUsage::STORAGE,
574 MemoryLocation::HostUpload,
575 ),
576 (
577 "grass tiles",
578 u64::from(slots) * u64::from(TILE_STRIDE),
579 BufferUsage::UNIFORM,
580 MemoryLocation::HostUpload,
581 ),
582 (
586 "grass cells",
587 field.cell_bytes(),
588 BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
589 MemoryLocation::DeviceLocal,
590 ),
591 (
592 "grass field",
593 FIELD_BLOCK_SIZE as u64,
594 BufferUsage::UNIFORM,
595 MemoryLocation::HostUpload,
596 ),
597 ];
598 let mut created: Vec<BufferHandle> = Vec::with_capacity(descs.len());
599 for (label, size, usage, memory) in descs {
600 match device.create_buffer(&BufferDesc {
601 label: Some(label),
602 size,
603 usage,
604 memory,
605 }) {
606 Ok(buffer) => created.push(buffer),
607 Err(error) => {
608 for buffer in created {
609 device.destroy_buffer(buffer);
610 }
611 card_image.destroy(device);
612 cover_image.destroy(device);
613 ground_image.destroy(device);
614 return Err(error.into());
615 }
616 }
617 }
618 let resident = Self {
619 instances: created[0],
620 args: created[1],
621 blades: created[2],
622 tiles: created[3],
623 cells: created[4],
624 field_block: created[5],
625 ground: ground_image,
626 cover: cover_image,
627 card: card_image,
628 slots,
629 shells: field.draws_shells(),
630 fins: field.shells().fins,
631 mesh_blades: field.draws_blades(),
632 generation: gen_params_of(field),
633 };
634 if let Err(error) = resident.write_static(device, field) {
635 resident.destroy(device);
636 return Err(error.into());
637 }
638 Ok(resident)
639 }
640
641 fn write_static(&self, device: &dyn Device, field: &GrassField) -> Result<(), HalError> {
649 let blades: Vec<u8> = field
650 .blades()
651 .iter()
652 .flat_map(|blade| blade.row().to_bytes())
653 .collect();
654 device.write_buffer(self.blades, 0, &blades)?;
655
656 let mut tiles = vec![0u8; self.slots as usize * TILE_STRIDE as usize];
657 for slot in 0..self.slots {
658 let [x, z] = field.tile_origin(slot);
659 let block = Tile {
660 tile: [x, z, field.tile_size(), 0.0],
661 slot: [slot, slot % field.tiles()[0], slot / field.tiles()[0], 0],
662 };
663 let at = slot as usize * TILE_STRIDE as usize;
664 tiles[at..at + TILE_SIZE].copy_from_slice(&block.to_bytes());
665 }
666 device.write_buffer(self.tiles, 0, &tiles)?;
667 device.write_buffer(
668 self.field_block,
669 0,
670 &shell::field_block_of(field).to_bytes(),
671 )
672 }
673
674 fn destroy(&self, device: &dyn Device) {
675 for buffer in [
676 self.instances,
677 self.cells,
678 self.args,
679 self.blades,
680 self.tiles,
681 self.field_block,
682 ] {
683 device.destroy_buffer(buffer);
684 }
685 self.card.destroy(device);
686 self.cover.destroy(device);
687 self.ground.destroy(device);
688 }
689}
690
691impl Wind {
692 fn calm(device: &dyn Device, queue: crcbl_hal::QueueHandle) -> Result<Self, HalError> {
693 let one = |label, texel: [u8; 4]| {
694 upload_texture(device, queue, label, Format::Rgba8Unorm, 1, 1, &texel)
695 };
696 let direction = one("wind direction", CALM_DIRECTION)?;
697 match one("wind intensity", CALM_INTENSITY) {
698 Ok(intensity) => Ok(Self {
699 direction,
700 intensity,
701 }),
702 Err(error) => {
703 direction.destroy(device);
704 Err(error)
705 }
706 }
707 }
708
709 fn upload(
710 device: &dyn Device,
711 queue: crcbl_hal::QueueHandle,
712 layers: &WindLayers,
713 ) -> Result<Self, WindLayerError> {
714 layers.direction.check()?;
715 layers.intensity.check()?;
716 let one = |label, layer: &WindLayer| {
717 upload_texture(
718 device,
719 queue,
720 label,
721 Format::Rgba8Unorm,
722 layer.texels[0],
723 layer.texels[1],
724 &layer.rgba8,
725 )
726 };
727 let direction = one("wind direction", &layers.direction)?;
728 match one("wind intensity", &layers.intensity) {
729 Ok(intensity) => Ok(Self {
730 direction,
731 intensity,
732 }),
733 Err(error) => {
734 direction.destroy(device);
735 Err(error.into())
736 }
737 }
738 }
739
740 fn destroy(&self, device: &dyn Device) {
741 self.intensity.destroy(device);
742 self.direction.destroy(device);
743 }
744}
745
746const TILE_STRIDE: u32 = 256;
756
757fn gen_params_of(field: &GrassField) -> GenParams {
760 let ground = field.ground();
761 let cover = field.cover();
762 GenParams {
763 camera: [0.0, 0.0, 0.0, field.reach()],
764 ground: [
765 ground.origin[0],
766 ground.origin[1],
767 ground.metres_per_texel,
768 1.0 / ground.metres_per_texel,
769 ],
770 cover: [
771 cover.origin[0],
772 cover.origin[1],
773 cover.metres_per_texel,
774 1.0 / cover.metres_per_texel,
775 ],
776 maps: [
777 ground.texels[0],
778 ground.texels[1],
779 cover.texels[0],
780 cover.texels[1],
781 ],
782 limits: [
783 SLOT_CAPACITY,
784 field.blades().len() as u32,
785 CELLS_PER_TILE,
786 field.slots(),
787 ],
788 looks: [field.shells().count, u32::from(field.shells().fins), 0, 0],
789 lod: [field.blade_lod().distance, 0.0, 0.0, 0.0],
790 }
791}
792
793mod gen_binding {
795 pub(super) const WIND: u32 = 0;
796 pub(super) const WIND_DIRECTION: u32 = 1;
797 pub(super) const WIND_INTENSITY: u32 = 2;
798 pub(super) const WIND_SAMPLER: u32 = 3;
799 pub(super) const PARAMS: u32 = 4;
800 pub(super) const TILE: u32 = 5;
801 pub(super) const BLADES: u32 = 6;
802 pub(super) const GROUND: u32 = 7;
803 pub(super) const COVER: u32 = 8;
804 pub(super) const INSTANCES: u32 = 9;
805 pub(super) const ARGS: u32 = 10;
806 pub(super) const CELLS: u32 = 11;
807}
808
809mod binding {
811 pub(super) const FRAME: u32 = 0;
812 pub(super) const PARAMS: u32 = 1;
813 pub(super) const TILE: u32 = 2;
814 pub(super) const INSTANCES: u32 = 3;
815 pub(super) const BLADES: u32 = 4;
816 pub(super) const CARD: u32 = 5;
817 pub(super) const CARD_SAMPLER: u32 = 6;
818 pub(super) const SHADOW_ATLAS: u32 = 7;
819 pub(super) const SHADOW_SAMPLER: u32 = 8;
820 pub(super) const LIGHTS: u32 = 9;
821 pub(super) const CLUSTER_LIGHTS: u32 = 10;
822 pub(super) const FIELD: u32 = 11;
823 pub(super) const CELLS: u32 = 12;
824 pub(super) const GROUND: u32 = 13;
825 pub(super) const WIND: u32 = 14;
826 pub(super) const WIND_DIRECTION: u32 = 15;
827 pub(super) const WIND_INTENSITY: u32 = 16;
828 pub(super) const WIND_SAMPLER: u32 = 17;
829}
830
831#[derive(Clone, Copy, Debug)]
833pub(crate) struct GrassImages {
834 pub(crate) color: ImageId,
836 pub(crate) depth: ImageId,
838 pub(crate) shadow_atlas: ImageId,
840}
841
842#[derive(Clone, Copy, Debug)]
844pub(crate) struct GrassInputs {
845 pub(crate) frame_block: BufferHandle,
847 pub(crate) lights: BufferHandle,
849 pub(crate) cluster_lights: BufferHandle,
850 pub(crate) light_grid: BufferId,
853 pub(crate) field: GrassFrame,
855}
856
857#[derive(Clone, Copy)]
862struct GenGroup {
863 layout: BindGroupLayoutHandle,
864 field: GrassFrame,
865 gen_params: BufferHandle,
866 wind_params: BufferHandle,
867 wind_sampler: SamplerHandle,
868}
869
870impl GenGroup {
871 fn build(
873 self,
874 device: &dyn Device,
875 named: &mut Option<Vec<BufferHandle>>,
876 cached: &mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
877 ) -> Option<BindGroupHandle> {
878 let field = self.field;
879 let now = vec![
882 field.instances,
883 field.cells,
884 field.args,
885 field.blades,
886 field.tiles,
887 ];
888 if named.as_ref() != Some(&now) {
889 if let Some((_, stale)) = cached.take() {
890 device.destroy_bind_group(stale);
891 }
892 *named = Some(now);
893 }
894 let buffer = |binding, buffer| BindGroupEntry {
895 binding,
896 array_index: 0,
897 resource: BindingResource::whole_buffer(buffer),
898 };
899 let view = |binding, view| BindGroupEntry {
900 binding,
901 array_index: 0,
902 resource: BindingResource::ImageView(view),
903 };
904 let entries = [
905 buffer(gen_binding::WIND, self.wind_params),
906 view(gen_binding::WIND_DIRECTION, field.wind_direction),
907 view(gen_binding::WIND_INTENSITY, field.wind_intensity),
908 BindGroupEntry {
909 binding: gen_binding::WIND_SAMPLER,
910 array_index: 0,
911 resource: BindingResource::Sampler(self.wind_sampler),
912 },
913 buffer(gen_binding::PARAMS, self.gen_params),
914 BindGroupEntry {
918 binding: gen_binding::TILE,
919 array_index: 0,
920 resource: BindingResource::Buffer {
921 buffer: field.tiles,
922 offset: 0,
923 size: TILE_SIZE as u64,
924 },
925 },
926 buffer(gen_binding::BLADES, field.blades),
927 view(gen_binding::GROUND, field.ground),
928 view(gen_binding::COVER, field.cover),
929 buffer(gen_binding::INSTANCES, field.instances),
930 buffer(gen_binding::ARGS, field.args),
931 buffer(gen_binding::CELLS, field.cells),
932 ];
933 cached_group(
934 cached,
935 device,
936 &[
937 (gen_binding::WIND_DIRECTION, field.wind_direction),
938 (gen_binding::WIND_INTENSITY, field.wind_intensity),
939 (gen_binding::GROUND, field.ground),
940 (gen_binding::COVER, field.cover),
941 ],
942 "grass generate",
943 self.layout,
944 &entries,
945 )
946 }
947}
948
949type RasterCache = (
952 Option<Vec<BufferHandle>>,
953 Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
954);
955
956#[derive(Debug)]
958pub(crate) struct Grass {
959 gen_layout: BindGroupLayoutHandle,
960 gen_pipeline_layout: PipelineLayoutHandle,
961 clear_pipeline: ComputePipelineHandle,
962 generate_pipeline: ComputePipelineHandle,
963 raster_layout: BindGroupLayoutHandle,
964 raster_pipeline_layout: PipelineLayoutHandle,
965 raster_pipeline: GraphicsPipelineHandle,
968 shell_pipeline: GraphicsPipelineHandle,
969 fin_pipeline: GraphicsPipelineHandle,
970 blade_near_pipeline: GraphicsPipelineHandle,
971 blade_far_pipeline: GraphicsPipelineHandle,
972 gen_params: Vec<BufferHandle>,
974 wind_params: Vec<BufferHandle>,
976 raster_params: Vec<BufferHandle>,
980 clear_groups: Vec<RasterCache>,
983 gen_groups: Vec<RasterCache>,
985 raster_groups: Vec<RasterCache>,
987 card_sampler: SamplerHandle,
988 wind_sampler: SamplerHandle,
989 shadow_sampler: SamplerHandle,
990}
991
992impl Grass {
993 pub(crate) const PASSES: u32 = 3;
995
996 pub(crate) fn new(
1009 device: &dyn Device,
1010 frames: usize,
1011 shadow_sampler: SamplerHandle,
1012 service: &mut dyn FnMut(),
1013 ) -> Result<Self, HalError> {
1014 let compute = ShaderStages::COMPUTE;
1015 let gen_entries = [
1016 uniform(gen_binding::WIND, compute, false),
1017 sampled(gen_binding::WIND_DIRECTION, compute, SampleType::Float),
1018 sampled(gen_binding::WIND_INTENSITY, compute, SampleType::Float),
1019 sampler(gen_binding::WIND_SAMPLER, compute),
1020 uniform(gen_binding::PARAMS, compute, false),
1021 uniform(gen_binding::TILE, compute, true),
1022 storage(gen_binding::BLADES, compute, true, BLADE_STRIDE as u32),
1023 BindGroupLayoutEntry {
1027 binding: gen_binding::GROUND,
1028 visibility: compute,
1029 kind: BindingKind::SampledImage {
1030 view_type: ImageViewType::D2,
1031 sample_type: SampleType::UnfilterableFloat,
1032 },
1033 count: 1,
1034 flags: BindingFlags::empty(),
1035 },
1036 sampled(gen_binding::COVER, compute, SampleType::Float),
1037 storage(
1038 gen_binding::INSTANCES,
1039 compute,
1040 false,
1041 INSTANCE_STRIDE as u32,
1042 ),
1043 storage(gen_binding::ARGS, compute, false, 4),
1044 storage(gen_binding::CELLS, compute, false, INSTANCE_STRIDE as u32),
1045 ];
1046 let gen_desc = BindGroupLayoutDesc {
1047 label: Some("grass generate"),
1048 entries: &gen_entries,
1049 };
1050 check_portable_storage_buffers(Some("grass generate"), &[&gen_desc])?;
1051 let gen_layout = device.create_bind_group_layout(&gen_desc)?;
1052 let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
1053 label: Some("grass generate"),
1054 bind_group_layouts: &[gen_layout],
1055 push_constants: None,
1056 })?;
1057 service();
1058 let clear_pipeline = compute_pipeline_entry(
1059 device,
1060 "grass clear",
1061 &GRASS_GEN,
1062 "clearMain",
1063 gen_pipeline_layout,
1064 WORKGROUP_SIZE,
1065 )?;
1066 service();
1067 let generate_pipeline = compute_pipeline_entry(
1068 device,
1069 "grass generate",
1070 &GRASS_GEN,
1071 "generateMain",
1072 gen_pipeline_layout,
1073 WORKGROUP_SIZE,
1074 )?;
1075
1076 let both = ShaderStages::VERTEX.union(ShaderStages::FRAGMENT);
1083 let raster_entries = [
1084 uniform(binding::FRAME, both, false),
1085 uniform(binding::PARAMS, both, false),
1086 uniform(binding::TILE, both, true),
1087 storage(binding::INSTANCES, both, true, INSTANCE_STRIDE as u32),
1088 storage(binding::BLADES, both, true, BLADE_STRIDE as u32),
1089 BindGroupLayoutEntry {
1090 binding: binding::CARD,
1091 visibility: both,
1092 kind: BindingKind::SampledImage {
1093 view_type: ImageViewType::D2Array,
1094 sample_type: SampleType::Float,
1095 },
1096 count: 1,
1097 flags: BindingFlags::empty(),
1098 },
1099 sampler(binding::CARD_SAMPLER, both),
1100 sampled(binding::SHADOW_ATLAS, both, SampleType::Depth),
1101 BindGroupLayoutEntry {
1102 binding: binding::SHADOW_SAMPLER,
1103 visibility: both,
1104 kind: BindingKind::Sampler { comparison: true },
1105 count: 1,
1106 flags: BindingFlags::empty(),
1107 },
1108 storage(
1109 binding::LIGHTS,
1110 both,
1111 true,
1112 crcbl_shaders::light::LIGHT_STRIDE as u32,
1113 ),
1114 storage(binding::CLUSTER_LIGHTS, both, true, 4),
1115 uniform(binding::FIELD, both, false),
1116 storage(binding::CELLS, both, true, INSTANCE_STRIDE as u32),
1117 BindGroupLayoutEntry {
1120 binding: binding::GROUND,
1121 visibility: both,
1122 kind: BindingKind::SampledImage {
1123 view_type: ImageViewType::D2,
1124 sample_type: SampleType::UnfilterableFloat,
1125 },
1126 count: 1,
1127 flags: BindingFlags::empty(),
1128 },
1129 uniform(binding::WIND, both, false),
1130 sampled(binding::WIND_DIRECTION, both, SampleType::Float),
1131 sampled(binding::WIND_INTENSITY, both, SampleType::Float),
1132 sampler(binding::WIND_SAMPLER, both),
1133 ];
1134 let raster_desc = BindGroupLayoutDesc {
1135 label: Some("grass"),
1136 entries: &raster_entries,
1137 };
1138 check_portable_storage_buffers(Some("grass"), &[&raster_desc])?;
1139 let raster_layout = device.create_bind_group_layout(&raster_desc)?;
1140 let raster_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
1141 label: Some("grass"),
1142 bind_group_layouts: &[raster_layout],
1143 push_constants: None,
1144 })?;
1145 let list = PrimitiveTopology::TriangleList;
1146 service();
1147 let raster_pipeline = build_raster(
1148 device,
1149 raster_pipeline_layout,
1150 ("vertexMain", "fragmentMain"),
1151 list,
1152 )?;
1153 service();
1154 let shell_pipeline = build_raster(
1155 device,
1156 raster_pipeline_layout,
1157 ("shellVertexMain", "shellFragmentMain"),
1158 list,
1159 )?;
1160 service();
1161 let fin_pipeline = build_raster(
1162 device,
1163 raster_pipeline_layout,
1164 ("finVertexMain", "shellFragmentMain"),
1165 list,
1166 )?;
1167 let strip = PrimitiveTopology::TriangleStrip;
1170 service();
1171 let blade_near_pipeline = build_raster(
1172 device,
1173 raster_pipeline_layout,
1174 ("bladeNearVertexMain", "bladeFragmentMain"),
1175 strip,
1176 )?;
1177 service();
1178 let blade_far_pipeline = build_raster(
1179 device,
1180 raster_pipeline_layout,
1181 ("bladeFarVertexMain", "bladeFragmentMain"),
1182 strip,
1183 )?;
1184
1185 let card_sampler = device.create_sampler(&SamplerDesc {
1186 label: Some("grass card"),
1187 min_filter: FilterMode::Linear,
1194 mag_filter: FilterMode::Linear,
1195 mip_filter: FilterMode::Linear,
1196 address_mode: [SamplerAddressMode::ClampToEdge; 3],
1197 ..SamplerDesc::default()
1198 })?;
1199 let wind_sampler = match device.create_sampler(&SamplerDesc {
1200 label: Some("wind layers"),
1201 min_filter: FilterMode::Linear,
1202 mag_filter: FilterMode::Linear,
1203 mip_filter: FilterMode::Nearest,
1205 address_mode: [SamplerAddressMode::Repeat; 3],
1208 ..SamplerDesc::default()
1209 }) {
1210 Ok(sampler) => sampler,
1211 Err(error) => {
1212 device.destroy_sampler(card_sampler);
1213 return Err(error);
1214 }
1215 };
1216
1217 let mut gen_params = Vec::with_capacity(frames);
1218 let mut wind_params = Vec::with_capacity(frames);
1219 let mut raster_params = Vec::with_capacity(frames);
1220 for _ in 0..frames {
1221 raster_params.push(device.create_buffer(&BufferDesc {
1222 label: Some("grass params"),
1223 size: PARAMS_SIZE as u64,
1224 usage: BufferUsage::UNIFORM,
1225 memory: MemoryLocation::HostUpload,
1226 })?);
1227 gen_params.push(device.create_buffer(&BufferDesc {
1228 label: Some("grass generate params"),
1229 size: GEN_PARAMS_SIZE as u64,
1230 usage: BufferUsage::UNIFORM,
1231 memory: MemoryLocation::HostUpload,
1232 })?);
1233 wind_params.push(device.create_buffer(&BufferDesc {
1234 label: Some("grass wind params"),
1235 size: WIND_PARAMS_SIZE as u64,
1236 usage: BufferUsage::UNIFORM,
1237 memory: MemoryLocation::HostUpload,
1238 })?);
1239 }
1240
1241 Ok(Self {
1242 gen_layout,
1243 gen_pipeline_layout,
1244 clear_pipeline,
1245 generate_pipeline,
1246 raster_layout,
1247 raster_pipeline_layout,
1248 raster_pipeline,
1249 shell_pipeline,
1250 fin_pipeline,
1251 blade_near_pipeline,
1252 blade_far_pipeline,
1253 gen_params,
1254 wind_params,
1255 raster_params,
1256 clear_groups: (0..frames).map(|_| (None, None)).collect(),
1257 gen_groups: (0..frames).map(|_| (None, None)).collect(),
1258 raster_groups: (0..frames).map(|_| (None, None)).collect(),
1259 card_sampler,
1260 wind_sampler,
1261 shadow_sampler,
1262 })
1263 }
1264
1265 pub(crate) fn begin_frame(
1279 &self,
1280 device: &dyn Device,
1281 frame: usize,
1282 generation: GenParams,
1283 wind: WindParams,
1284 raster: Params,
1285 ) -> Result<(), HalError> {
1286 device.write_buffer(self.gen_params[frame], 0, &generation.to_bytes())?;
1287 device.write_buffer(self.raster_params[frame], 0, &raster.to_bytes())?;
1288 device.write_buffer(self.wind_params[frame], 0, &wind.to_bytes())
1289 }
1290
1291 pub(crate) fn add_passes<'a>(
1297 &'a mut self,
1298 graph: &mut RenderGraph<'a>,
1299 frame: usize,
1300 images: GrassImages,
1301 inputs: GrassInputs,
1302 ) {
1303 let GrassImages {
1304 color,
1305 depth,
1306 shadow_atlas,
1307 } = images;
1308 let GrassInputs {
1309 frame_block,
1310 lights,
1311 cluster_lights,
1312 light_grid,
1313 field,
1314 } = inputs;
1315
1316 let mut imported = |label: &str, buffer| {
1317 graph.import_buffer(
1318 label,
1319 ImportedBuffer {
1320 buffer,
1321 initial: ResourceState::ShaderReadWrite,
1322 final_state: ResourceState::ShaderReadWrite,
1323 },
1324 )
1325 };
1326 let instances_id = imported("grass-instances", field.instances);
1327 let args_id = imported("grass-draw-args", field.args);
1328
1329 let slots = field.slots;
1330 let gen_layout = self.gen_layout;
1331 let gen_pipeline_layout = self.gen_pipeline_layout;
1332 let clear_pipeline = self.clear_pipeline;
1333 let generate_pipeline = self.generate_pipeline;
1334 let gen_params = self.gen_params[frame];
1335 let wind_params = self.wind_params[frame];
1336 let wind_sampler = self.wind_sampler;
1337 let group_of = GenGroup {
1338 layout: gen_layout,
1339 field,
1340 gen_params,
1341 wind_params,
1342 wind_sampler,
1343 };
1344 let (clear_named, clear_cached) = &mut self.clear_groups[frame];
1350 graph
1351 .add_compute_pass("grass-clear")
1352 .use_buffer(args_id, ResourceState::ShaderReadWrite)
1353 .execute(move |ctx| {
1354 let device = ctx.device();
1355 let Some(group) = group_of.build(device, clear_named, clear_cached) else {
1356 return;
1357 };
1358 let encoder = ctx.encoder();
1359 encoder.bind_compute_pipeline(clear_pipeline);
1360 encoder.bind_group(0, group, &[0], gen_pipeline_layout);
1361 encoder.dispatch(slots.div_ceil(WORKGROUP_SIZE), 1, 1);
1362 });
1363
1364 let (gen_named, gen_cached) = &mut self.gen_groups[frame];
1365 graph
1366 .add_compute_pass("grass-generate")
1367 .use_buffer(args_id, ResourceState::ShaderReadWrite)
1368 .use_buffer(instances_id, ResourceState::ShaderReadWrite)
1369 .execute(move |ctx| {
1370 let device = ctx.device();
1371 let Some(group) = group_of.build(device, gen_named, gen_cached) else {
1372 return;
1373 };
1374 let encoder = ctx.encoder();
1375 encoder.bind_compute_pipeline(generate_pipeline);
1376 for slot in 0..slots {
1379 encoder.bind_group(0, group, &[slot * TILE_STRIDE], gen_pipeline_layout);
1380 encoder.dispatch(
1381 (CELLS_PER_TILE * CELLS_PER_TILE).div_ceil(WORKGROUP_SIZE),
1382 1,
1383 1,
1384 );
1385 }
1386 });
1387
1388 let raster_pipeline = self.raster_pipeline;
1389 let shell_pipeline = self.shell_pipeline;
1390 let fin_pipeline = self.fin_pipeline;
1391 let blade_near_pipeline = self.blade_near_pipeline;
1392 let blade_far_pipeline = self.blade_far_pipeline;
1393 let raster_pipeline_layout = self.raster_pipeline_layout;
1394 let raster_layout = self.raster_layout;
1395 let card_sampler = self.card_sampler;
1396 let shadow_sampler = self.shadow_sampler;
1397 let raster_params = self.raster_params[frame];
1398 let (raster_named, raster_cached) = &mut self.raster_groups[frame];
1399 graph
1400 .add_render_pass("grass")
1401 .color(color, LoadOp::Load, StoreOp::Store, ClearValue::default())
1404 .depth(depth, LoadOp::Load, StoreOp::Store, ClearValue::default())
1408 .read_image(shadow_atlas)
1409 .read_buffer(instances_id)
1410 .read_buffer(light_grid)
1411 .use_buffer(args_id, ResourceState::IndirectArgument)
1412 .execute(move |ctx| {
1413 let atlas_view = ctx.image_view(shadow_atlas);
1414 let device = ctx.device();
1415 let now = vec![
1416 field.instances,
1417 field.cells,
1418 field.blades,
1419 field.tiles,
1420 field.field_block,
1421 lights,
1422 ];
1423 if raster_named.as_ref() != Some(&now) {
1424 if let Some((_, stale)) = raster_cached.take() {
1425 device.destroy_bind_group(stale);
1426 }
1427 *raster_named = Some(now);
1428 }
1429 let buffer = |binding, buffer| BindGroupEntry {
1430 binding,
1431 array_index: 0,
1432 resource: BindingResource::whole_buffer(buffer),
1433 };
1434 let entries = [
1435 buffer(binding::FRAME, frame_block),
1436 buffer(binding::PARAMS, raster_params),
1437 BindGroupEntry {
1438 binding: binding::TILE,
1439 array_index: 0,
1440 resource: BindingResource::Buffer {
1441 buffer: field.tiles,
1442 offset: 0,
1443 size: TILE_SIZE as u64,
1444 },
1445 },
1446 buffer(binding::INSTANCES, field.instances),
1447 buffer(binding::BLADES, field.blades),
1448 BindGroupEntry {
1449 binding: binding::CARD,
1450 array_index: 0,
1451 resource: BindingResource::ImageView(field.card),
1452 },
1453 BindGroupEntry {
1454 binding: binding::CARD_SAMPLER,
1455 array_index: 0,
1456 resource: BindingResource::Sampler(card_sampler),
1457 },
1458 BindGroupEntry {
1459 binding: binding::SHADOW_ATLAS,
1460 array_index: 0,
1461 resource: BindingResource::ImageView(atlas_view),
1462 },
1463 BindGroupEntry {
1464 binding: binding::SHADOW_SAMPLER,
1465 array_index: 0,
1466 resource: BindingResource::Sampler(shadow_sampler),
1467 },
1468 buffer(binding::LIGHTS, lights),
1469 buffer(binding::CLUSTER_LIGHTS, cluster_lights),
1470 buffer(binding::FIELD, field.field_block),
1471 buffer(binding::CELLS, field.cells),
1472 BindGroupEntry {
1473 binding: binding::GROUND,
1474 array_index: 0,
1475 resource: BindingResource::ImageView(field.ground),
1476 },
1477 buffer(binding::WIND, wind_params),
1478 BindGroupEntry {
1479 binding: binding::WIND_DIRECTION,
1480 array_index: 0,
1481 resource: BindingResource::ImageView(field.wind_direction),
1482 },
1483 BindGroupEntry {
1484 binding: binding::WIND_INTENSITY,
1485 array_index: 0,
1486 resource: BindingResource::ImageView(field.wind_intensity),
1487 },
1488 BindGroupEntry {
1489 binding: binding::WIND_SAMPLER,
1490 array_index: 0,
1491 resource: BindingResource::Sampler(wind_sampler),
1492 },
1493 ];
1494 let Some(group) = cached_group(
1495 raster_cached,
1496 device,
1497 &[
1498 (binding::CARD, field.card),
1499 (binding::SHADOW_ATLAS, atlas_view),
1500 (binding::GROUND, field.ground),
1501 (binding::WIND_DIRECTION, field.wind_direction),
1502 (binding::WIND_INTENSITY, field.wind_intensity),
1503 ],
1504 "grass",
1505 raster_layout,
1506 &entries,
1507 ) else {
1508 return;
1509 };
1510 let encoder = ctx.encoder();
1511 let looks = [
1518 Some((raster_pipeline, CARD_DRAW)),
1519 field.shells.then_some((shell_pipeline, SHELL_DRAW)),
1520 (field.shells && field.fins).then_some((fin_pipeline, FIN_DRAW)),
1521 field
1522 .mesh_blades
1523 .then_some((blade_near_pipeline, BLADE_NEAR_DRAW)),
1524 field
1525 .mesh_blades
1526 .then_some((blade_far_pipeline, BLADE_FAR_DRAW)),
1527 ];
1528 for (pipeline, draw) in looks.into_iter().flatten() {
1529 encoder.bind_graphics_pipeline(pipeline);
1530 for slot in 0..slots {
1531 encoder.bind_group(0, group, &[slot * TILE_STRIDE], raster_pipeline_layout);
1532 encoder.draw_indirect(&DrawIndirect {
1533 args: field.args,
1534 offset: u64::from(slot) * SLOT_ARGS_SIZE as u64
1535 + u64::from(draw) * DRAW_ARGS_SIZE as u64,
1536 draw_count: 1,
1537 stride: DRAW_ARGS_SIZE as u32,
1538 });
1539 }
1540 }
1541 });
1542 }
1543
1544 pub(crate) fn destroy(self, device: &dyn Device) {
1546 for (_, group) in self
1547 .clear_groups
1548 .into_iter()
1549 .filter_map(|(_, cached)| cached)
1550 .chain(self.gen_groups.into_iter().filter_map(|(_, cached)| cached))
1551 .chain(
1552 self.raster_groups
1553 .into_iter()
1554 .filter_map(|(_, cached)| cached),
1555 )
1556 {
1557 device.destroy_bind_group(group);
1558 }
1559 device.destroy_graphics_pipeline(self.blade_far_pipeline);
1560 device.destroy_graphics_pipeline(self.blade_near_pipeline);
1561 device.destroy_graphics_pipeline(self.fin_pipeline);
1562 device.destroy_graphics_pipeline(self.shell_pipeline);
1563 device.destroy_graphics_pipeline(self.raster_pipeline);
1564 device.destroy_pipeline_layout(self.raster_pipeline_layout);
1565 device.destroy_bind_group_layout(self.raster_layout);
1566 device.destroy_compute_pipeline(self.generate_pipeline);
1567 device.destroy_compute_pipeline(self.clear_pipeline);
1568 device.destroy_pipeline_layout(self.gen_pipeline_layout);
1569 device.destroy_bind_group_layout(self.gen_layout);
1570 device.destroy_sampler(self.wind_sampler);
1571 device.destroy_sampler(self.card_sampler);
1572 for buffer in self
1573 .gen_params
1574 .into_iter()
1575 .chain(self.wind_params)
1576 .chain(self.raster_params)
1577 {
1578 device.destroy_buffer(buffer);
1579 }
1580 }
1581}
1582
1583fn build_raster(
1588 device: &dyn Device,
1589 layout: PipelineLayoutHandle,
1590 (vertex, fragment): (&'static str, &'static str),
1591 topology: PrimitiveTopology,
1592) -> Result<GraphicsPipelineHandle, HalError> {
1593 let vertex = crate::forward::named_entry(&GRASS, vertex, Stage::Vertex)?;
1596 let fragment = crate::forward::named_entry(&GRASS, fragment, Stage::Fragment)?;
1597 let module = device.create_shader_module(&ShaderModuleDesc {
1598 label: Some(GRASS.source()),
1599 spirv: GRASS.spirv(),
1600 wgsl: GRASS.wgsl(),
1601 msl: GRASS.msl(),
1602 dxil: &GRASS.dxil_containers(),
1603 })?;
1604 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
1605 label: Some(vertex),
1606 layout,
1607 vertex: ShaderEntry {
1608 module,
1609 entry_point: vertex,
1610 },
1611 fragment: Some(ShaderEntry {
1612 module,
1613 entry_point: fragment,
1614 }),
1615 primitive: crcbl_hal::PrimitiveState {
1621 topology,
1622 ..crcbl_hal::PrimitiveState::default()
1623 },
1624 depth_stencil: Some(DepthStencilState {
1625 format: crate::forward::SCENE_DEPTH_FORMAT,
1626 depth_write: true,
1627 depth_compare: CompareOp::Greater,
1628 stencil: None,
1629 bias: DepthBias::default(),
1630 }),
1631 multisample: MultisampleState::default(),
1632 color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
1633 });
1634 device.destroy_shader_module(module);
1635 pipeline
1636}
1637
1638const fn uniform(binding: u32, visibility: ShaderStages, dynamic: bool) -> BindGroupLayoutEntry {
1640 BindGroupLayoutEntry {
1641 binding,
1642 visibility,
1643 kind: BindingKind::UniformBuffer { dynamic },
1644 count: 1,
1645 flags: BindingFlags::empty(),
1646 }
1647}
1648
1649const fn storage(
1651 binding: u32,
1652 visibility: ShaderStages,
1653 read_only: bool,
1654 stride: u32,
1655) -> BindGroupLayoutEntry {
1656 BindGroupLayoutEntry {
1657 binding,
1658 visibility,
1659 kind: BindingKind::StorageBuffer {
1660 read_only,
1661 dynamic: false,
1662 stride,
1663 },
1664 count: 1,
1665 flags: BindingFlags::empty(),
1666 }
1667}
1668
1669const fn sampled(
1671 binding: u32,
1672 visibility: ShaderStages,
1673 sample_type: SampleType,
1674) -> BindGroupLayoutEntry {
1675 BindGroupLayoutEntry {
1676 binding,
1677 visibility,
1678 kind: BindingKind::SampledImage {
1679 view_type: ImageViewType::D2,
1680 sample_type,
1681 },
1682 count: 1,
1683 flags: BindingFlags::empty(),
1684 }
1685}
1686
1687const fn sampler(binding: u32, visibility: ShaderStages) -> BindGroupLayoutEntry {
1689 BindGroupLayoutEntry {
1690 binding,
1691 visibility,
1692 kind: BindingKind::Sampler { comparison: false },
1693 count: 1,
1694 flags: BindingFlags::empty(),
1695 }
1696}
1697
1698#[cfg(all(test, not(target_arch = "wasm32")))]
1700mod tests;