authoravatarclover caruso<git@paperclover.net>2026-12-01 01:31:19-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 02:52:53-08:00
log7090cf87ebf69321576c2ab7da746e79d2b31799
treebafdd772a516d05e168dadce936eb7ed7baf0e12
parenta5e1d16ebe8cc3e59daf03d7bd093cb52249af67
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Shadow map pooling, alpha-tested casters, cube-seam fix; TextPlus font aliases and Inspector schema sync

- Renderer3D shadows require lighting; cube maps/depth are reused across renders and caster/face uniforms share one dynamic-offset buffer. - Shadow pass skips transparent meshes and alpha-tests textured casters; face pick uses the normal-offset point, guards clip.w, far derives from camera range. - metric_alias is symmetric for Times New Roman / Courier New. - WandMask Channel, ChannelBoolean And/Or/Xor/Signed Add, Loader Loop/Reverse default from the clip. Assisted-by: claude-sonnet-5.5

6 files changed, 288 insertions(+), 106 deletions(-)

crates/app/src/inspector/schemas.rs+3-1
......@@ -104,8 +104,9 @@ const MASK_CHANNELS: &[&str] = &[
104104
105105const EDGES_INT: &[(i32, &str)] = &[(0, "Canvas"), (1, "Wrap"), (2, "Duplicate"), (3, "Mirror")];
106106const CB_OPS: &[(i32, &str)] = &[
107 (0, "Copy"), (1, "Add"), (2, "Subtract"), (6, "Multiply"), (7, "Divide"),
107 (0, "Copy"), (1, "Add"), (2, "Subtract"), (3, "And"), (4, "Or"), (5, "Exclusive Or"), (6, "Multiply"), (7, "Divide"),
108108 (8, "Maximum"), (9, "Minimum"), (10, "Negative"), (11, "Solid"), (12, "Clear"), (13, "Difference"),
109 (14, "Signed Add"),
109110];
110111const CB_CHANNELS: &[(i32, &str)] = &[
111112 (0, "Red FG"), (1, "Green FG"), (2, "Blue FG"), (3, "Alpha FG"), (4, "Do Nothing"),
......@@ -601,6 +602,7 @@ pub fn schema_for_kind(kind: &str) -> &'static [ParamSpec] {
601602 v2("SelectionPoint", "Seed Point", 0.0, 1.0, [0.5, 0.5]),
602603 flt("Range", "Range", 0.0, 1.0, 0.1),
603604 flt("RangeSoftEdge", "Range Soft", 0.0, 1.0, 0.0),
605 int_enum("Channel", "Channel", &[(0, "Color"), (1, "Red"), (2, "Green"), (3, "Blue"), (4, "Alpha")], 0),
604606 int_enum("ColorSpace", "Color Space", &[(0, "RGB"), (1, "YUV")], 0),
605607 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),
606608 flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0),
crates/app/src/inspector/widgets.rs+8
......@@ -110,6 +110,14 @@ impl InspectorState {
110110 );
111111 }
112112 ParamKind::Bool { default } => {
113 // A Loader without `Inputs.Loop`/`Reverse` plays whatever its clip says.
114 let node = comp.node(node_id);
115 let clip = node.clips.first().filter(|_| node.kind == "Loader");
116 let default = match spec.name {
117 "Loop" => clip.map_or(default, |c| c.loop_clip),
118 "Reverse" => clip.map_or(default, |c| c.reverse),
119 _ => default,
120 };
113121 self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions);
114122 }
115123 ParamKind::Enum { options, default } => {
crates/engine/src/eval/text_3d.rs+7-5
......@@ -517,8 +517,9 @@ impl Engine {
517517 // Only the active renderer's lighting toggle counts; Fusion's default renderer is software.
518518 let renderer = node.static_str("RendererType").unwrap_or("RendererSoftware");
519519 let lighting_enabled = comp.eval_number(node, &format!("{renderer}.LightingEnabled"), time, 0.0, &self.expr) > 0.5;
520 // Only the OpenGL renderer shades shadows.
521 let shadows_enabled = renderer == "RendererOpenGL"
520 // Only the OpenGL renderer shades shadows, and only when lighting is on.
521 let shadows_enabled = lighting_enabled
522 && renderer == "RendererOpenGL"
522523 && comp.eval_number(node, "RendererOpenGL.ShadowsEnabled", time, 0.0, &self.expr) > 0.5;
523524 let mut cameras = Vec::new();
524525 let mut mesh_specs = Vec::new();
......@@ -538,14 +539,14 @@ impl Engine {
538539 0,
539540 );
540541
541 let (view, proj, cam_pos) = if let Some(cam) = cameras.first() {
542 let (view, proj, cam_pos, cam_far) = if let Some(cam) = cameras.first() {
542543 let v = crate::scene3d::mat4_inverse(cam.world);
543544 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);
544 (v, p, [cam.world[12], cam.world[13], cam.world[14]])
545 (v, p, [cam.world[12], cam.world[13], cam.world[14]], cam.far)
545546 } else {
546547 let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0);
547548 let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0);
548 (v, p, [0.0, 0.0, 5.0])
549 (v, p, [0.0, 0.0, 5.0], 5000.0)
549550 };
550551 let view_proj = crate::scene3d::mat4_mul(proj, view);
551552
......@@ -670,6 +671,7 @@ impl Engine {
670671 view_proj,
671672 view,
672673 cam_pos,
674 cam_far,
673675 lights,
674676 lighting_enabled,
675677 shadows_enabled,
crates/engine/src/scene3d/mod.rs+204-77
......@@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex};
2525use crate::cache::CachedTexture;
2626use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
2727use model::NodeId;
28use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER};
28use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL};
2929
3030pub type Mat4 = [f32; 16]; // Column-major 4x4
3131
......@@ -37,12 +37,28 @@ pub struct Scene3DRenderer {
3737 sampler: wgpu::Sampler,
3838 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
3939 shadow_pipeline: wgpu::RenderPipeline,
40 /// Bound for `Caster` (group 0) and `Face` (group 1) uniforms of the shadow pass.
41 shadow_uniform_bgl: wgpu::BindGroupLayout,
40 /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass.
41 shadow_caster_bgl: wgpu::BindGroupLayout,
42 /// `Face` uniform (dynamic offset): group 1 of the shadow pass.
43 shadow_face_bgl: wgpu::BindGroupLayout,
4244 /// 1x1 map bound when no light casts shadows.
4345 shadow_dummy: wgpu::TextureView,
46 /// Cube maps and depth buffer reused across renders; grown, never shrunk.
47 shadow_targets: Mutex<Option<ShadowTargets>>,
4448}
4549
50#[derive(Clone)]
51struct ShadowTargets {
52 maps: wgpu::Texture,
53 /// Array layers of `maps` (six per shadow light).
54 layers: u32,
55 depth: wgpu::TextureView,
56}
57
58/// Bytes of the shadow pass's `Caster` and `Face` uniforms.
59const CASTER_BYTES: usize = 128;
60const FACE_BYTES: usize = 80;
61
4662/// Most meshes kept resident on the GPU across frames.
4763const MESH_CACHE_CAP: usize = 64;
4864
......@@ -378,8 +394,8 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
378394}
379395
380396/// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`.
381fn cube_face_view_projections(eye: [f32; 3]) -> [Mat4; 6] {
382 let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, 1000.0);
397fn cube_face_view_projections(eye: [f32; 3], far: f32) -> [Mat4; 6] {
398 let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, far);
383399 [
384400 ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
385401 ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
......@@ -407,7 +423,7 @@ impl Scene3DRenderer {
407423 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
408424 label: Some("scene3d-shader"),
409425 source: wgpu::ShaderSource::Wgsl(
410 SHADER_3D
426 format!("{UV_XFORM_WGSL}{SHADER_3D}")
411427 .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string())
412428 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())
413429 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())
......@@ -531,24 +547,47 @@ impl Scene3DRenderer {
531547 });
532548 let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
533549 label: Some("scene3d-shadow-shader"),
534 source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()),
550 source: wgpu::ShaderSource::Wgsl(format!("{UV_XFORM_WGSL}{SHADOW_SHADER}").into()),
535551 });
536 let shadow_uniform_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
537 label: Some("scene3d-shadow-bgl"),
538 entries: &[wgpu::BindGroupLayoutEntry {
539 binding: 0,
540 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
541 ty: wgpu::BindingType::Buffer {
542 ty: wgpu::BufferBindingType::Uniform,
543 has_dynamic_offset: false,
544 min_binding_size: None,
552 let dynamic_uniform = |binding| wgpu::BindGroupLayoutEntry {
553 binding,
554 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
555 ty: wgpu::BindingType::Buffer {
556 ty: wgpu::BufferBindingType::Uniform,
557 has_dynamic_offset: true,
558 min_binding_size: None,
559 },
560 count: None,
561 };
562 let shadow_caster_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
563 label: Some("scene3d-shadow-caster-bgl"),
564 entries: &[
565 dynamic_uniform(0),
566 wgpu::BindGroupLayoutEntry {
567 binding: 1,
568 visibility: wgpu::ShaderStages::FRAGMENT,
569 ty: wgpu::BindingType::Texture {
570 sample_type: wgpu::TextureSampleType::Float { filterable: true },
571 view_dimension: wgpu::TextureViewDimension::D2,
572 multisampled: false,
573 },
574 count: None,
575 },
576 wgpu::BindGroupLayoutEntry {
577 binding: 2,
578 visibility: wgpu::ShaderStages::FRAGMENT,
579 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
580 count: None,
545581 },
546 count: None,
547 }],
582 ],
583 });
584 let shadow_face_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
585 label: Some("scene3d-shadow-face-bgl"),
586 entries: &[dynamic_uniform(0)],
548587 });
549588 let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
550589 label: Some("scene3d-shadow-pl"),
551 bind_group_layouts: &[Some(&shadow_uniform_bgl), Some(&shadow_uniform_bgl)],
590 bind_group_layouts: &[Some(&shadow_caster_bgl), Some(&shadow_face_bgl)],
552591 immediate_size: 0,
553592 });
554593 let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
......@@ -603,8 +642,10 @@ impl Scene3DRenderer {
603642 sampler,
604643 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),
605644 shadow_pipeline,
606 shadow_uniform_bgl,
645 shadow_caster_bgl,
646 shadow_face_bgl,
607647 shadow_dummy,
648 shadow_targets: Mutex::new(None),
608649 }
609650 }
610651
......@@ -619,6 +660,7 @@ impl Scene3DRenderer {
619660 view_proj: Mat4,
620661 view: Mat4,
621662 cam_pos: [f32; 3],
663 cam_far: f32,
622664 lights: SceneLights,
623665 lighting_enabled: bool,
624666 shadows_enabled: bool,
......@@ -653,9 +695,12 @@ impl Scene3DRenderer {
653695 face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS],
654696 point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS],
655697 };
698 // Receivers visible to the camera are at most `cam_far` from it, so that bounds the light's reach.
699 let distance_to_cam = |p: [f32; 3]| (0..3).map(|i| (p[i] - cam_pos[i]).powi(2)).sum::<f32>().sqrt();
656700 for (slot, &li) in shadow_lights.iter().enumerate() {
657701 let pl = &lights.points[li];
658 shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&cube_face_view_projections(pl.pos));
702 let far = cam_far + distance_to_cam(pl.pos);
703 shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&cube_face_view_projections(pl.pos, far));
659704 shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0];
660705 }
661706 let shadow_ubuf = device.create_buffer(&wgpu::BufferDescriptor {
......@@ -665,42 +710,65 @@ impl Scene3DRenderer {
665710 mapped_at_creation: false,
666711 });
667712 queue.write_buffer(&shadow_ubuf, 0, bytemuck::bytes_of(&shadow_uni));
668 let shadow_map = (!shadow_lights.is_empty()).then(|| {
669 device.create_texture(&wgpu::TextureDescriptor {
670 label: Some("scene3d-shadow-maps"),
671 size: wgpu::Extent3d {
672 width: SHADOW_MAP_SIZE,
673 height: SHADOW_MAP_SIZE,
674 depth_or_array_layers: 6 * shadow_lights.len() as u32,
675 },
676 mip_level_count: 1,
677 sample_count: 1,
678 dimension: wgpu::TextureDimension::D2,
679 format: wgpu::TextureFormat::R32Float,
680 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
681 view_formats: &[],
682 })
713 let shadow_targets = (!shadow_lights.is_empty()).then(|| {
714 let layers = 6 * shadow_lights.len() as u32;
715 let mut cache = self.shadow_targets.lock().unwrap();
716 match cache.as_ref() {
717 Some(t) if t.layers >= layers => t.clone(),
718 _ => {
719 let target = |label, format, usage, depth_or_array_layers| {
720 device.create_texture(&wgpu::TextureDescriptor {
721 label: Some(label),
722 size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers },
723 mip_level_count: 1,
724 sample_count: 1,
725 dimension: wgpu::TextureDimension::D2,
726 format,
727 usage,
728 view_formats: &[],
729 })
730 };
731 let fresh = ShadowTargets {
732 maps: target(
733 "scene3d-shadow-maps",
734 wgpu::TextureFormat::R32Float,
735 wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
736 layers,
737 ),
738 layers,
739 depth: target(
740 "scene3d-shadow-depth",
741 wgpu::TextureFormat::Depth32Float,
742 wgpu::TextureUsages::RENDER_ATTACHMENT,
743 1,
744 )
745 .create_view(&wgpu::TextureViewDescriptor::default()),
746 };
747 *cache = Some(fresh.clone());
748 fresh
749 }
750 }
683751 });
684 let shadow_view = shadow_map.as_ref().map(|t| {
685 t.create_view(&wgpu::TextureViewDescriptor {
752 let shadow_view = shadow_targets.as_ref().map(|t| {
753 t.maps.create_view(&wgpu::TextureViewDescriptor {
686754 dimension: Some(wgpu::TextureViewDimension::D2Array),
687755 ..Default::default()
688756 })
689757 });
690 let uniform_bind_group = |label: &str, bytes: &[u8]| {
691 let buf = device.create_buffer(&wgpu::BufferDescriptor {
692 label: Some(label),
693 size: bytes.len() as u64,
758 // One buffer holds every caster and face uniform of this render at dynamic offsets: casters
759 // first (at most one per mesh), then six faces per light.
760 let uniform_stride = (CASTER_BYTES as u32).next_multiple_of(device.limits().min_uniform_buffer_offset_alignment) as usize;
761 let face_base = meshes.len() * uniform_stride;
762 let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }];
763 let shadow_dyn_buf = (!shadow_lights.is_empty()).then(|| {
764 device.create_buffer(&wgpu::BufferDescriptor {
765 label: Some("scene3d-shadow-dyn"),
766 size: shadow_uniform_bytes.len() as u64,
694767 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
695768 mapped_at_creation: false,
696 });
697 queue.write_buffer(&buf, 0, bytes);
698 device.create_bind_group(&wgpu::BindGroupDescriptor {
699 label: Some(label),
700 layout: &self.shadow_uniform_bgl,
701 entries: &[wgpu::BindGroupEntry { binding: 0, resource: buf.as_entire_binding() }],
702769 })
703 };
770 });
771 let mut n_casters = 0;
704772
705773 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.
706774 let mut order: Vec<(usize, f32)> = meshes
......@@ -721,8 +789,8 @@ impl Scene3DRenderer {
721789 /// Skip the `[back-facing, front-facing]` pass.
722790 cull: [bool; 2],
723791 bg: wgpu::BindGroup,
724 /// `model` for the shadow pass; `None` for meshes that cast no shadow.
725 caster: Option<wgpu::BindGroup>,
792 /// Shadow-pass bind group and dynamic uniform offset; `None` for meshes that cast no shadow.
793 caster: Option<(wgpu::BindGroup, u32)>,
726794 vbuf: wgpu::Buffer,
727795 ibuf: wgpu::Buffer,
728796 idx_count: u32,
......@@ -862,42 +930,71 @@ impl Scene3DRenderer {
862930 },
863931 ],
864932 });
933 // A fully transparent mesh casts no shadow; textured ones are alpha-tested in the pass.
934 let caster = shadow_dyn_buf.as_ref().filter(|_| !fx.wireframe && m.diffuse_col[3] > 1e-3).map(|buf| {
935 let mut data = [0.0_f32; CASTER_BYTES / 4];
936 data[..16].copy_from_slice(&m.world);
937 data[16..20].copy_from_slice(&fx.uv.m);
938 data[20..24].copy_from_slice(&uni.uv_off_wrap);
939 data[24..28].copy_from_slice(&dod);
940 data[28..30].copy_from_slice(&[if m.tex.is_some() && !fx.bump_only { 1.0 } else { 0.0 }, m.diffuse_col[3]]);
941 let offset = n_casters * uniform_stride;
942 shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&data));
943 n_casters += 1;
944 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
945 label: Some("scene3d-shadow-caster"),
946 layout: &self.shadow_caster_bgl,
947 entries: &[
948 wgpu::BindGroupEntry {
949 binding: 0,
950 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
951 buffer: buf,
952 offset: 0,
953 size: std::num::NonZeroU64::new(CASTER_BYTES as u64),
954 }),
955 },
956 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) },
957 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
958 ],
959 });
960 (bind_group, offset as u32)
961 });
865962 draw_items.push(GpuDraw {
866963 wireframe: fx.wireframe,
867964 cull: [fx.cull_back, fx.cull_front],
868965 bg,
869 caster: (!fx.wireframe && !shadow_lights.is_empty())
870 .then(|| uniform_bind_group("scene3d-caster", bytemuck::cast_slice(&m.world))),
966 caster,
871967 vbuf,
872968 ibuf,
873969 idx_count,
874970 });
875971 }
876972
877 if let Some(map) = &shadow_map {
878 let shadow_depth_view = device
879 .create_texture(&wgpu::TextureDescriptor {
880 label: Some("scene3d-shadow-depth"),
881 size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers: 1 },
882 mip_level_count: 1,
883 sample_count: 1,
884 dimension: wgpu::TextureDimension::D2,
885 format: wgpu::TextureFormat::Depth32Float,
886 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
887 view_formats: &[],
888 })
889 .create_view(&wgpu::TextureViewDescriptor::default());
973 if let (Some(targets), Some(buf)) = (&shadow_targets, &shadow_dyn_buf) {
974 let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
975 label: Some("scene3d-shadow-face"),
976 layout: &self.shadow_face_bgl,
977 entries: &[wgpu::BindGroupEntry {
978 binding: 0,
979 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
980 buffer: buf,
981 offset: 0,
982 size: std::num::NonZeroU64::new(FACE_BYTES as u64),
983 }),
984 }],
985 });
890986 for (slot, &li) in shadow_lights.iter().enumerate() {
891987 let pos = lights.points[li].pos;
892988 for face in 0..6 {
893 let layer = (slot * 6 + face) as u32;
894 let mut uniform = [0.0_f32; 20];
895 uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer as usize]);
989 let layer = slot * 6 + face;
990 let mut uniform = [0.0_f32; FACE_BYTES / 4];
991 uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer]);
896992 uniform[16..19].copy_from_slice(&pos);
897 let face_bg = uniform_bind_group("scene3d-shadow-face", bytemuck::cast_slice(&uniform));
898 let layer_view = map.create_view(&wgpu::TextureViewDescriptor {
993 let face_offset = face_base + layer * uniform_stride;
994 shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform));
995 let layer_view = targets.maps.create_view(&wgpu::TextureViewDescriptor {
899996 dimension: Some(wgpu::TextureViewDimension::D2),
900 base_array_layer: layer,
997 base_array_layer: layer as u32,
901998 array_layer_count: Some(1),
902999 ..Default::default()
9031000 });
......@@ -913,7 +1010,7 @@ impl Scene3DRenderer {
9131010 },
9141011 })],
9151012 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
916 view: &shadow_depth_view,
1013 view: &targets.depth,
9171014 depth_ops: Some(wgpu::Operations {
9181015 load: wgpu::LoadOp::Clear(1.0),
9191016 store: wgpu::StoreOp::Discard,
......@@ -925,16 +1022,17 @@ impl Scene3DRenderer {
9251022 multiview_mask: None,
9261023 });
9271024 pass.set_pipeline(&self.shadow_pipeline);
928 pass.set_bind_group(1, &face_bg, &[]);
1025 pass.set_bind_group(1, &face_bg, &[face_offset as u32]);
9291026 for d in &draw_items {
930 let Some(caster) = &d.caster else { continue };
931 pass.set_bind_group(0, caster, &[]);
1027 let Some((caster, caster_offset)) = &d.caster else { continue };
1028 pass.set_bind_group(0, caster, &[*caster_offset]);
9321029 pass.set_vertex_buffer(0, d.vbuf.slice(..));
9331030 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
9341031 pass.draw_indexed(0..d.idx_count, 0, 0..1);
9351032 }
9361033 }
9371034 }
1035 queue.write_buffer(buf, 0, &shadow_uniform_bytes);
9381036 }
9391037
9401038 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
......@@ -1129,7 +1227,7 @@ mod tests {
11291227 let frame = |meshes: &[DrawMesh]| {
11301228 let mut enc = device.create_command_encoder(&Default::default());
11311229 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);
1132 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, false, meshes);
1230 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes);
11331231 queue.submit(Some(enc.finish()));
11341232 renderer.meshes.lock().unwrap().entries.len()
11351233 };
......@@ -1193,4 +1291,33 @@ mod tests {
11931291 let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count();
11941292 assert!(dark_pixels(&with_shad) > dark_pixels(&no_shad) + 15, "shadows should darken receiver: with={} vs without={}", dark_pixels(&with_shad), dark_pixels(&no_shad));
11951293 }
1294
1295 #[test]
1296 fn transparent_textured_casters_leave_no_shadow() {
1297 let dark_receiver_pixels = |card_alpha: u8, shadows: u8| -> Option<usize> {
1298 let src = format!(
1299 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
1300 Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }},
1301 Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = {card_alpha}, }}, }}, }},
1302 Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }},
1303 Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }},
1304 Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }},
1305 Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }},
1306 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }},
1307 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Card", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},
1308 R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }},
1309 }} }}"#
1310 );
1311 let comp = Comp::from_fusion_str(&src).expect("parse shadow comp");
1312 let mut eng = Engine::new_headless().ok()?;
1313 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0);
1314 let buf = eng.readback_rgba(&tex).ok()?;
1315 Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count())
1316 };
1317 let (Some(opaque), Some(clear), Some(off)) = (dark_receiver_pixels(255, 1), dark_receiver_pixels(0, 1), dark_receiver_pixels(0, 0)) else {
1318 return;
1319 };
1320 assert!(opaque > off + 15, "opaque card must shadow: {opaque} vs {off}");
1321 assert_eq!(clear, off, "a fully transparent card casts no shadow");
1322 }
11961323}
crates/engine/src/scene3d/shader.rs+54-23
......@@ -69,28 +69,66 @@ pub(super) struct ShadowUniform {
6969 pub(super) point: [[f32; 4]; MAX_LIGHTS],
7070}
7171
72/// Per-caster `model` plus per-face view-projection and light position; writes the distance to
73/// the light so the main pass can compare it against a fragment's own distance.
72/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines.
73pub(super) const UV_XFORM_WGSL: &str = r#"
74fn apply_uv_xform(raw_uv: vec2<f32>, m: vec4<f32>, off_wrap: vec4<f32>) -> vec2<f32> {
75 var uv = vec2<f32>(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + off_wrap.xy;
76 let wrap = i32(off_wrap.z + 0.5);
77 if (wrap == 1) {
78 uv = fract(uv);
79 } else if (wrap == 2) {
80 uv = vec2<f32>(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2<f32>(1.0));
81 }
82 return uv;
83}
84"#;
85
86/// Per-caster `model` and alpha-test inputs plus per-face view-projection and light position;
87/// writes the distance to the light so the main pass can compare it against a fragment's own
88/// distance. Textured casters discard fragments whose coverage is below half.
7489pub(super) const SHADOW_SHADER: &str = r#"
75struct Caster { model: mat4x4<f32> };
90// `alpha.x`: 1 when the bound texture alpha-tests the caster; `alpha.y`: diffuse alpha.
91struct Caster {
92 model: mat4x4<f32>,
93 uv_xform: vec4<f32>,
94 uv_off_wrap: vec4<f32>,
95 dod: vec4<f32>,
96 alpha: vec4<f32>,
97};
7698struct Face { vp: mat4x4<f32>, light_pos: vec4<f32> };
7799
78100@group(0) @binding(0) var<uniform> caster: Caster;
101@group(0) @binding(1) var mat_tex: texture_2d<f32>;
102@group(0) @binding(2) var mat_samp: sampler;
79103@group(1) @binding(0) var<uniform> face: Face;
80104
81105struct VsOut {
82106 @builtin(position) clip: vec4<f32>,
83107 @location(0) world_pos: vec3<f32>,
108 @location(1) uv: vec2<f32>,
84109};
85110
86111@vertex
87fn vs_shadow(@location(0) pos: vec3<f32>) -> VsOut {
112fn vs_shadow(@location(0) pos: vec3<f32>, @location(2) uv: vec2<f32>) -> VsOut {
88113 let wp = caster.model * vec4<f32>(pos, 1.0);
89 return VsOut(face.vp * wp, wp.xyz);
114 return VsOut(face.vp * wp, wp.xyz, uv);
90115}
91116
92117@fragment
93118fn fs_shadow(in: VsOut) -> @location(0) f32 {
119 if (caster.alpha.x > 0.5) {
120 var uv = apply_uv_xform(in.uv, caster.uv_xform, caster.uv_off_wrap);
121 if (caster.dod.z > 0.5 && caster.dod.w > 0.5) {
122 let tdims = vec2<f32>(textureDimensions(mat_tex));
123 uv = (vec2<f32>(uv.x * caster.dod.z, uv.y * caster.dod.w) - caster.dod.xy) / tdims;
124 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
125 discard;
126 }
127 }
128 if (textureSampleLevel(mat_tex, mat_samp, uv, 0.0).a * caster.alpha.y < 0.5) {
129 discard;
130 }
131 }
94132 return distance(in.world_pos, face.light_pos.xyz);
95133}
96134"#;
......@@ -192,8 +230,12 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:
192230 return 0.0;
193231 }
194232 let slot = i32(params.x + 0.5);
195 let d = world_pos - light_pos;
196 let dist = length(d);
233 let dist = length(world_pos - light_pos);
234 // World size of one texel at this distance for a 90 degree face.
235 let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE);
236 // The face is picked from the offset point so the lookup never straddles a cube seam.
237 let biased = world_pos + n * (texel * 1.5);
238 let d = biased - light_pos;
197239 let a = abs(d);
198240 var face = 4;
199241 if (a.x >= a.y && a.x >= a.z) {
......@@ -203,9 +245,10 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:
203245 } else {
204246 face = select(5, 4, d.z > 0.0);
205247 }
206 // World size of one texel at this distance for a 90 degree face.
207 let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE);
208 let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(world_pos + n * (texel * 1.5), 1.0);
248 let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(biased, 1.0);
249 if (clip.w <= 1e-5) {
250 return 0.0;
251 }
209252 let ndc = clip.xy / clip.w;
210253 let base = vec2<i32>(floor(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE)));
211254 let last = SHADOW_MAP_SIZE - 1;
......@@ -256,18 +299,6 @@ fn eval_light_contrib(
256299 return out;
257300}
258301
259fn apply_uv_xform(raw_uv: vec2<f32>) -> vec2<f32> {
260 let m = u.uv_xform;
261 var uv = vec2<f32>(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + u.uv_off_wrap.xy;
262 let wrap = i32(u.uv_off_wrap.z + 0.5);
263 if (wrap == 1) {
264 uv = fract(uv);
265 } else if (wrap == 2) {
266 uv = vec2<f32>(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2<f32>(1.0));
267 }
268 return uv;
269}
270
271302fn perturb_bump_normal(
272303 base_n: vec3<f32>,
273304 dpdx_w: vec3<f32>,
......@@ -327,7 +358,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
327358 if (facing_away != BACK_PASS) {
328359 discard;
329360 }
330 let uv_xformed = apply_uv_xform(in.uv);
361 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap);
331362 let dpdx_w = dpdx(in.world_pos);
332363 let dpdy_w = dpdy(in.world_pos);
333364 let duvdx = dpdx(uv_xformed);
crates/engine/src/text_engine.rs+12
......@@ -83,8 +83,12 @@ fn metric_alias(family: &str) -> Option<&'static str> {
8383 Some("Liberation Sans")
8484 } else if family.eq_ignore_ascii_case("Liberation Serif") {
8585 Some("Times New Roman")
86 } else if family.eq_ignore_ascii_case("Times New Roman") {
87 Some("Liberation Serif")
8688 } else if family.eq_ignore_ascii_case("Liberation Mono") {
8789 Some("Courier New")
90 } else if family.eq_ignore_ascii_case("Courier New") {
91 Some("Liberation Mono")
8892 } else {
8993 None
9094 }
......@@ -485,4 +489,12 @@ mod tests {
485489 assert!((lcx - 160).abs() <= 8 && (lcy - 90).abs() <= 8, "landscape centered ({lcx}, {lcy})");
486490 assert!((pcx - 90).abs() <= 6 && (pcy - 160).abs() <= 6, "portrait centered ({pcx}, {pcy})");
487491 }
492
493 #[test]
494 fn metric_aliases_map_both_ways() {
495 for (a, b) in [("Arial", "Liberation Sans"), ("Times New Roman", "Liberation Serif"), ("Courier New", "Liberation Mono")] {
496 assert_eq!(metric_alias(a), Some(b));
497 assert_eq!(metric_alias(b), Some(a));
498 }
499 }
488500}