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] = &[...@@ -104,8 +104,9 @@ const MASK_CHANNELS: &[&str] = &[
104104
105const EDGES_INT: &[(i32, &str)] = &[(0, "Canvas"), (1, "Wrap"), (2, "Duplicate"), (3, "Mirror")];105const EDGES_INT: &[(i32, &str)] = &[(0, "Canvas"), (1, "Wrap"), (2, "Duplicate"), (3, "Mirror")];
106const CB_OPS: &[(i32, &str)] = &[106const 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"),
108 (8, "Maximum"), (9, "Minimum"), (10, "Negative"), (11, "Solid"), (12, "Clear"), (13, "Difference"),108 (8, "Maximum"), (9, "Minimum"), (10, "Negative"), (11, "Solid"), (12, "Clear"), (13, "Difference"),
109 (14, "Signed Add"),
109];110];
110const CB_CHANNELS: &[(i32, &str)] = &[111const CB_CHANNELS: &[(i32, &str)] = &[
111 (0, "Red FG"), (1, "Green FG"), (2, "Blue FG"), (3, "Alpha FG"), (4, "Do Nothing"),112 (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] {...@@ -601,6 +602,7 @@ pub fn schema_for_kind(kind: &str) -> &'static [ParamSpec] {
601 v2("SelectionPoint", "Seed Point", 0.0, 1.0, [0.5, 0.5]),602 v2("SelectionPoint", "Seed Point", 0.0, 1.0, [0.5, 0.5]),
602 flt("Range", "Range", 0.0, 1.0, 0.1),603 flt("Range", "Range", 0.0, 1.0, 0.1),
603 flt("RangeSoftEdge", "Range Soft", 0.0, 1.0, 0.0),604 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),
604 int_enum("ColorSpace", "Color Space", &[(0, "RGB"), (1, "YUV")], 0),606 int_enum("ColorSpace", "Color Space", &[(0, "RGB"), (1, "YUV")], 0),
605 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),607 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),
606 flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0),608 flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0),
crates/app/src/inspector/widgets.rs+8
...@@ -110,6 +110,14 @@ impl InspectorState {...@@ -110,6 +110,14 @@ impl InspectorState {
110 );110 );
111 }111 }
112 ParamKind::Bool { default } => {112 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 };
113 self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions);121 self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions);
114 }122 }
115 ParamKind::Enum { options, default } => {123 ParamKind::Enum { options, default } => {
crates/engine/src/eval/text_3d.rs+7-5
...@@ -517,8 +517,9 @@ impl Engine {...@@ -517,8 +517,9 @@ impl Engine {
517 // Only the active renderer's lighting toggle counts; Fusion's default renderer is software.517 // Only the active renderer's lighting toggle counts; Fusion's default renderer is software.
518 let renderer = node.static_str("RendererType").unwrap_or("RendererSoftware");518 let renderer = node.static_str("RendererType").unwrap_or("RendererSoftware");
519 let lighting_enabled = comp.eval_number(node, &format!("{renderer}.LightingEnabled"), time, 0.0, &self.expr) > 0.5;519 let lighting_enabled = comp.eval_number(node, &format!("{renderer}.LightingEnabled"), time, 0.0, &self.expr) > 0.5;
520 // Only the OpenGL renderer shades shadows.520 // Only the OpenGL renderer shades shadows, and only when lighting is on.
521 let shadows_enabled = renderer == "RendererOpenGL"521 let shadows_enabled = lighting_enabled
522 && renderer == "RendererOpenGL"
522 && comp.eval_number(node, "RendererOpenGL.ShadowsEnabled", time, 0.0, &self.expr) > 0.5;523 && comp.eval_number(node, "RendererOpenGL.ShadowsEnabled", time, 0.0, &self.expr) > 0.5;
523 let mut cameras = Vec::new();524 let mut cameras = Vec::new();
524 let mut mesh_specs = Vec::new();525 let mut mesh_specs = Vec::new();
...@@ -538,14 +539,14 @@ impl Engine {...@@ -538,14 +539,14 @@ impl Engine {
538 0,539 0,
539 );540 );
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() {
542 let v = crate::scene3d::mat4_inverse(cam.world);543 let v = crate::scene3d::mat4_inverse(cam.world);
543 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);544 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)
545 } else {546 } else {
546 let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0);547 let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0);
547 let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0);548 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)
549 };550 };
550 let view_proj = crate::scene3d::mat4_mul(proj, view);551 let view_proj = crate::scene3d::mat4_mul(proj, view);
551552
...@@ -670,6 +671,7 @@ impl Engine {...@@ -670,6 +671,7 @@ impl Engine {
670 view_proj,671 view_proj,
671 view,672 view,
672 cam_pos,673 cam_pos,
674 cam_far,
673 lights,675 lights,
674 lighting_enabled,676 lighting_enabled,
675 shadows_enabled,677 shadows_enabled,
crates/engine/src/scene3d/mod.rs+204-77
...@@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex};...@@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex};
25use crate::cache::CachedTexture;25use crate::cache::CachedTexture;
26use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};26use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
27use model::NodeId;27use 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
30pub type Mat4 = [f32; 16]; // Column-major 4x430pub type Mat4 = [f32; 16]; // Column-major 4x4
3131
...@@ -37,12 +37,28 @@ pub struct Scene3DRenderer {...@@ -37,12 +37,28 @@ pub struct Scene3DRenderer {
37 sampler: wgpu::Sampler,37 sampler: wgpu::Sampler,
38 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,38 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
39 shadow_pipeline: wgpu::RenderPipeline,39 shadow_pipeline: wgpu::RenderPipeline,
40 /// Bound for `Caster` (group 0) and `Face` (group 1) uniforms of the shadow pass.40 /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass.
41 shadow_uniform_bgl: wgpu::BindGroupLayout,41 shadow_caster_bgl: wgpu::BindGroupLayout,
42 /// `Face` uniform (dynamic offset): group 1 of the shadow pass.
43 shadow_face_bgl: wgpu::BindGroupLayout,
42 /// 1x1 map bound when no light casts shadows.44 /// 1x1 map bound when no light casts shadows.
43 shadow_dummy: wgpu::TextureView,45 shadow_dummy: wgpu::TextureView,
46 /// Cube maps and depth buffer reused across renders; grown, never shrunk.
47 shadow_targets: Mutex<Option<ShadowTargets>>,
44}48}
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
46/// Most meshes kept resident on the GPU across frames.62/// Most meshes kept resident on the GPU across frames.
47const MESH_CACHE_CAP: usize = 64;63const MESH_CACHE_CAP: usize = 64;
4864
...@@ -378,8 +394,8 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {...@@ -378,8 +394,8 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
378}394}
379395
380/// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`.396/// 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] {397fn cube_face_view_projections(eye: [f32; 3], far: f32) -> [Mat4; 6] {
382 let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, 1000.0);398 let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, far);
383 [399 [
384 ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),400 ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
385 ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),401 ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
...@@ -407,7 +423,7 @@ impl Scene3DRenderer {...@@ -407,7 +423,7 @@ impl Scene3DRenderer {
407 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {423 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
408 label: Some("scene3d-shader"),424 label: Some("scene3d-shader"),
409 source: wgpu::ShaderSource::Wgsl(425 source: wgpu::ShaderSource::Wgsl(
410 SHADER_3D426 format!("{UV_XFORM_WGSL}{SHADER_3D}")
411 .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string())427 .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string())
412 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())428 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())
413 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())429 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())
...@@ -531,24 +547,47 @@ impl Scene3DRenderer {...@@ -531,24 +547,47 @@ impl Scene3DRenderer {
531 });547 });
532 let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {548 let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
533 label: Some("scene3d-shadow-shader"),549 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()),
535 });551 });
536 let shadow_uniform_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {552 let dynamic_uniform = |binding| wgpu::BindGroupLayoutEntry {
537 label: Some("scene3d-shadow-bgl"),553 binding,
538 entries: &[wgpu::BindGroupLayoutEntry {554 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
539 binding: 0,555 ty: wgpu::BindingType::Buffer {
540 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,556 ty: wgpu::BufferBindingType::Uniform,
541 ty: wgpu::BindingType::Buffer {557 has_dynamic_offset: true,
542 ty: wgpu::BufferBindingType::Uniform,558 min_binding_size: None,
543 has_dynamic_offset: false,559 },
544 min_binding_size: None,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,
545 },581 },
546 count: None,582 ],
547 }],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)],
548 });587 });
549 let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {588 let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
550 label: Some("scene3d-shadow-pl"),589 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)],
552 immediate_size: 0,591 immediate_size: 0,
553 });592 });
554 let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {593 let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
...@@ -603,8 +642,10 @@ impl Scene3DRenderer {...@@ -603,8 +642,10 @@ impl Scene3DRenderer {
603 sampler,642 sampler,
604 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),643 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),
605 shadow_pipeline,644 shadow_pipeline,
606 shadow_uniform_bgl,645 shadow_caster_bgl,
646 shadow_face_bgl,
607 shadow_dummy,647 shadow_dummy,
648 shadow_targets: Mutex::new(None),
608 }649 }
609 }650 }
610651
...@@ -619,6 +660,7 @@ impl Scene3DRenderer {...@@ -619,6 +660,7 @@ impl Scene3DRenderer {
619 view_proj: Mat4,660 view_proj: Mat4,
620 view: Mat4,661 view: Mat4,
621 cam_pos: [f32; 3],662 cam_pos: [f32; 3],
663 cam_far: f32,
622 lights: SceneLights,664 lights: SceneLights,
623 lighting_enabled: bool,665 lighting_enabled: bool,
624 shadows_enabled: bool,666 shadows_enabled: bool,
...@@ -653,9 +695,12 @@ impl Scene3DRenderer {...@@ -653,9 +695,12 @@ impl Scene3DRenderer {
653 face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS],695 face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS],
654 point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS],696 point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS],
655 };697 };
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();
656 for (slot, &li) in shadow_lights.iter().enumerate() {700 for (slot, &li) in shadow_lights.iter().enumerate() {
657 let pl = &lights.points[li];701 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));
659 shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0];704 shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0];
660 }705 }
661 let shadow_ubuf = device.create_buffer(&wgpu::BufferDescriptor {706 let shadow_ubuf = device.create_buffer(&wgpu::BufferDescriptor {
...@@ -665,42 +710,65 @@ impl Scene3DRenderer {...@@ -665,42 +710,65 @@ impl Scene3DRenderer {
665 mapped_at_creation: false,710 mapped_at_creation: false,
666 });711 });
667 queue.write_buffer(&shadow_ubuf, 0, bytemuck::bytes_of(&shadow_uni));712 queue.write_buffer(&shadow_ubuf, 0, bytemuck::bytes_of(&shadow_uni));
668 let shadow_map = (!shadow_lights.is_empty()).then(|| {713 let shadow_targets = (!shadow_lights.is_empty()).then(|| {
669 device.create_texture(&wgpu::TextureDescriptor {714 let layers = 6 * shadow_lights.len() as u32;
670 label: Some("scene3d-shadow-maps"),715 let mut cache = self.shadow_targets.lock().unwrap();
671 size: wgpu::Extent3d {716 match cache.as_ref() {
672 width: SHADOW_MAP_SIZE,717 Some(t) if t.layers >= layers => t.clone(),
673 height: SHADOW_MAP_SIZE,718 _ => {
674 depth_or_array_layers: 6 * shadow_lights.len() as u32,719 let target = |label, format, usage, depth_or_array_layers| {
675 },720 device.create_texture(&wgpu::TextureDescriptor {
676 mip_level_count: 1,721 label: Some(label),
677 sample_count: 1,722 size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers },
678 dimension: wgpu::TextureDimension::D2,723 mip_level_count: 1,
679 format: wgpu::TextureFormat::R32Float,724 sample_count: 1,
680 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,725 dimension: wgpu::TextureDimension::D2,
681 view_formats: &[],726 format,
682 })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 }
683 });751 });
684 let shadow_view = shadow_map.as_ref().map(|t| {752 let shadow_view = shadow_targets.as_ref().map(|t| {
685 t.create_view(&wgpu::TextureViewDescriptor {753 t.maps.create_view(&wgpu::TextureViewDescriptor {
686 dimension: Some(wgpu::TextureViewDimension::D2Array),754 dimension: Some(wgpu::TextureViewDimension::D2Array),
687 ..Default::default()755 ..Default::default()
688 })756 })
689 });757 });
690 let uniform_bind_group = |label: &str, bytes: &[u8]| {758 // One buffer holds every caster and face uniform of this render at dynamic offsets: casters
691 let buf = device.create_buffer(&wgpu::BufferDescriptor {759 // first (at most one per mesh), then six faces per light.
692 label: Some(label),760 let uniform_stride = (CASTER_BYTES as u32).next_multiple_of(device.limits().min_uniform_buffer_offset_alignment) as usize;
693 size: bytes.len() as u64,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,
694 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,767 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
695 mapped_at_creation: false,768 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() }],
702 })769 })
703 };770 });
771 let mut n_casters = 0;
704772
705 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.773 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.
706 let mut order: Vec<(usize, f32)> = meshes774 let mut order: Vec<(usize, f32)> = meshes
...@@ -721,8 +789,8 @@ impl Scene3DRenderer {...@@ -721,8 +789,8 @@ impl Scene3DRenderer {
721 /// Skip the `[back-facing, front-facing]` pass.789 /// Skip the `[back-facing, front-facing]` pass.
722 cull: [bool; 2],790 cull: [bool; 2],
723 bg: wgpu::BindGroup,791 bg: wgpu::BindGroup,
724 /// `model` for the shadow pass; `None` for meshes that cast no shadow.792 /// Shadow-pass bind group and dynamic uniform offset; `None` for meshes that cast no shadow.
725 caster: Option<wgpu::BindGroup>,793 caster: Option<(wgpu::BindGroup, u32)>,
726 vbuf: wgpu::Buffer,794 vbuf: wgpu::Buffer,
727 ibuf: wgpu::Buffer,795 ibuf: wgpu::Buffer,
728 idx_count: u32,796 idx_count: u32,
...@@ -862,42 +930,71 @@ impl Scene3DRenderer {...@@ -862,42 +930,71 @@ impl Scene3DRenderer {
862 },930 },
863 ],931 ],
864 });932 });
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 });
865 draw_items.push(GpuDraw {962 draw_items.push(GpuDraw {
866 wireframe: fx.wireframe,963 wireframe: fx.wireframe,
867 cull: [fx.cull_back, fx.cull_front],964 cull: [fx.cull_back, fx.cull_front],
868 bg,965 bg,
869 caster: (!fx.wireframe && !shadow_lights.is_empty())966 caster,
870 .then(|| uniform_bind_group("scene3d-caster", bytemuck::cast_slice(&m.world))),
871 vbuf,967 vbuf,
872 ibuf,968 ibuf,
873 idx_count,969 idx_count,
874 });970 });
875 }971 }
876972
877 if let Some(map) = &shadow_map {973 if let (Some(targets), Some(buf)) = (&shadow_targets, &shadow_dyn_buf) {
878 let shadow_depth_view = device974 let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
879 .create_texture(&wgpu::TextureDescriptor {975 label: Some("scene3d-shadow-face"),
880 label: Some("scene3d-shadow-depth"),976 layout: &self.shadow_face_bgl,
881 size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers: 1 },977 entries: &[wgpu::BindGroupEntry {
882 mip_level_count: 1,978 binding: 0,
883 sample_count: 1,979 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
884 dimension: wgpu::TextureDimension::D2,980 buffer: buf,
885 format: wgpu::TextureFormat::Depth32Float,981 offset: 0,
886 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,982 size: std::num::NonZeroU64::new(FACE_BYTES as u64),
887 view_formats: &[],983 }),
888 })984 }],
889 .create_view(&wgpu::TextureViewDescriptor::default());985 });
890 for (slot, &li) in shadow_lights.iter().enumerate() {986 for (slot, &li) in shadow_lights.iter().enumerate() {
891 let pos = lights.points[li].pos;987 let pos = lights.points[li].pos;
892 for face in 0..6 {988 for face in 0..6 {
893 let layer = (slot * 6 + face) as u32;989 let layer = slot * 6 + face;
894 let mut uniform = [0.0_f32; 20];990 let mut uniform = [0.0_f32; FACE_BYTES / 4];
895 uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer as usize]);991 uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer]);
896 uniform[16..19].copy_from_slice(&pos);992 uniform[16..19].copy_from_slice(&pos);
897 let face_bg = uniform_bind_group("scene3d-shadow-face", bytemuck::cast_slice(&uniform));993 let face_offset = face_base + layer * uniform_stride;
898 let layer_view = map.create_view(&wgpu::TextureViewDescriptor {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 {
899 dimension: Some(wgpu::TextureViewDimension::D2),996 dimension: Some(wgpu::TextureViewDimension::D2),
900 base_array_layer: layer,997 base_array_layer: layer as u32,
901 array_layer_count: Some(1),998 array_layer_count: Some(1),
902 ..Default::default()999 ..Default::default()
903 });1000 });
...@@ -913,7 +1010,7 @@ impl Scene3DRenderer {...@@ -913,7 +1010,7 @@ impl Scene3DRenderer {
913 },1010 },
914 })],1011 })],
915 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {1012 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
916 view: &shadow_depth_view,1013 view: &targets.depth,
917 depth_ops: Some(wgpu::Operations {1014 depth_ops: Some(wgpu::Operations {
918 load: wgpu::LoadOp::Clear(1.0),1015 load: wgpu::LoadOp::Clear(1.0),
919 store: wgpu::StoreOp::Discard,1016 store: wgpu::StoreOp::Discard,
...@@ -925,16 +1022,17 @@ impl Scene3DRenderer {...@@ -925,16 +1022,17 @@ impl Scene3DRenderer {
925 multiview_mask: None,1022 multiview_mask: None,
926 });1023 });
927 pass.set_pipeline(&self.shadow_pipeline);1024 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]);
929 for d in &draw_items {1026 for d in &draw_items {
930 let Some(caster) = &d.caster else { continue };1027 let Some((caster, caster_offset)) = &d.caster else { continue };
931 pass.set_bind_group(0, caster, &[]);1028 pass.set_bind_group(0, caster, &[*caster_offset]);
932 pass.set_vertex_buffer(0, d.vbuf.slice(..));1029 pass.set_vertex_buffer(0, d.vbuf.slice(..));
933 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);1030 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
934 pass.draw_indexed(0..d.idx_count, 0, 0..1);1031 pass.draw_indexed(0..d.idx_count, 0, 0..1);
935 }1032 }
936 }1033 }
937 }1034 }
1035 queue.write_buffer(buf, 0, &shadow_uniform_bytes);
938 }1036 }
9391037
940 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {1038 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
...@@ -1129,7 +1227,7 @@ mod tests {...@@ -1129,7 +1227,7 @@ mod tests {
1129 let frame = |meshes: &[DrawMesh]| {1227 let frame = |meshes: &[DrawMesh]| {
1130 let mut enc = device.create_command_encoder(&Default::default());1228 let mut enc = device.create_command_encoder(&Default::default());
1131 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);1229 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);
1133 queue.submit(Some(enc.finish()));1231 queue.submit(Some(enc.finish()));
1134 renderer.meshes.lock().unwrap().entries.len()1232 renderer.meshes.lock().unwrap().entries.len()
1135 };1233 };
...@@ -1193,4 +1291,33 @@ mod tests {...@@ -1193,4 +1291,33 @@ mod tests {
1193 let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count();1291 let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count();
1194 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));1292 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));
1195 }1293 }
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 }
1196}1323}
crates/engine/src/scene3d/shader.rs+54-23
...@@ -69,28 +69,66 @@ pub(super) struct ShadowUniform {...@@ -69,28 +69,66 @@ pub(super) struct ShadowUniform {
69 pub(super) point: [[f32; 4]; MAX_LIGHTS],69 pub(super) point: [[f32; 4]; MAX_LIGHTS],
70}70}
7171
72/// Per-caster `model` plus per-face view-projection and light position; writes the distance to72/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines.
73/// the light so the main pass can compare it against a fragment's own distance.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.
74pub(super) const SHADOW_SHADER: &str = r#"89pub(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};
76struct Face { vp: mat4x4<f32>, light_pos: vec4<f32> };98struct Face { vp: mat4x4<f32>, light_pos: vec4<f32> };
7799
78@group(0) @binding(0) var<uniform> caster: Caster;100@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;
79@group(1) @binding(0) var<uniform> face: Face;103@group(1) @binding(0) var<uniform> face: Face;
80104
81struct VsOut {105struct VsOut {
82 @builtin(position) clip: vec4<f32>,106 @builtin(position) clip: vec4<f32>,
83 @location(0) world_pos: vec3<f32>,107 @location(0) world_pos: vec3<f32>,
108 @location(1) uv: vec2<f32>,
84};109};
85110
86@vertex111@vertex
87fn vs_shadow(@location(0) pos: vec3<f32>) -> VsOut {112fn vs_shadow(@location(0) pos: vec3<f32>, @location(2) uv: vec2<f32>) -> VsOut {
88 let wp = caster.model * vec4<f32>(pos, 1.0);113 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);
90}115}
91116
92@fragment117@fragment
93fn fs_shadow(in: VsOut) -> @location(0) f32 {118fn 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 }
94 return distance(in.world_pos, face.light_pos.xyz);132 return distance(in.world_pos, face.light_pos.xyz);
95}133}
96"#;134"#;
...@@ -192,8 +230,12 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:...@@ -192,8 +230,12 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:
192 return 0.0;230 return 0.0;
193 }231 }
194 let slot = i32(params.x + 0.5);232 let slot = i32(params.x + 0.5);
195 let d = world_pos - light_pos;233 let dist = length(world_pos - light_pos);
196 let dist = length(d);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;
197 let a = abs(d);239 let a = abs(d);
198 var face = 4;240 var face = 4;
199 if (a.x >= a.y && a.x >= a.z) {241 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:...@@ -203,9 +245,10 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:
203 } else {245 } else {
204 face = select(5, 4, d.z > 0.0);246 face = select(5, 4, d.z > 0.0);
205 }247 }
206 // World size of one texel at this distance for a 90 degree face.248 let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(biased, 1.0);
207 let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE);249 if (clip.w <= 1e-5) {
208 let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(world_pos + n * (texel * 1.5), 1.0);250 return 0.0;
251 }
209 let ndc = clip.xy / clip.w;252 let ndc = clip.xy / clip.w;
210 let base = vec2<i32>(floor(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE)));253 let base = vec2<i32>(floor(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE)));
211 let last = SHADOW_MAP_SIZE - 1;254 let last = SHADOW_MAP_SIZE - 1;
...@@ -256,18 +299,6 @@ fn eval_light_contrib(...@@ -256,18 +299,6 @@ fn eval_light_contrib(
256 return out;299 return out;
257}300}
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
271fn perturb_bump_normal(302fn perturb_bump_normal(
272 base_n: vec3<f32>,303 base_n: vec3<f32>,
273 dpdx_w: vec3<f32>,304 dpdx_w: vec3<f32>,
...@@ -327,7 +358,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -327,7 +358,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
327 if (facing_away != BACK_PASS) {358 if (facing_away != BACK_PASS) {
328 discard;359 discard;
329 }360 }
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);
331 let dpdx_w = dpdx(in.world_pos);362 let dpdx_w = dpdx(in.world_pos);
332 let dpdy_w = dpdy(in.world_pos);363 let dpdy_w = dpdy(in.world_pos);
333 let duvdx = dpdx(uv_xformed);364 let duvdx = dpdx(uv_xformed);
crates/engine/src/text_engine.rs+12
...@@ -83,8 +83,12 @@ fn metric_alias(family: &str) -> Option<&'static str> {...@@ -83,8 +83,12 @@ fn metric_alias(family: &str) -> Option<&'static str> {
83 Some("Liberation Sans")83 Some("Liberation Sans")
84 } else if family.eq_ignore_ascii_case("Liberation Serif") {84 } else if family.eq_ignore_ascii_case("Liberation Serif") {
85 Some("Times New Roman")85 Some("Times New Roman")
86 } else if family.eq_ignore_ascii_case("Times New Roman") {
87 Some("Liberation Serif")
86 } else if family.eq_ignore_ascii_case("Liberation Mono") {88 } else if family.eq_ignore_ascii_case("Liberation Mono") {
87 Some("Courier New")89 Some("Courier New")
90 } else if family.eq_ignore_ascii_case("Courier New") {
91 Some("Liberation Mono")
88 } else {92 } else {
89 None93 None
90 }94 }
...@@ -485,4 +489,12 @@ mod tests {...@@ -485,4 +489,12 @@ mod tests {
485 assert!((lcx - 160).abs() <= 8 && (lcy - 90).abs() <= 8, "landscape centered ({lcx}, {lcy})");489 assert!((lcx - 160).abs() <= 8 && (lcy - 90).abs() <= 8, "landscape centered ({lcx}, {lcy})");
486 assert!((pcx - 90).abs() <= 6 && (pcy - 160).abs() <= 6, "portrait centered ({pcx}, {pcy})");490 assert!((pcx - 90).abs() <= 6 && (pcy - 160).abs() <= 6, "portrait centered ({pcx}, {pcy})");
487 }491 }
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 }
488}500}