authoravatarclover caruso<git@paperclover.net>2026-11-30 23:18:50-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 23:50:35-08:00
log85bce11eb2a2a96f516541c3de49031e337dd4eb
treef18330856d33ae8bf4d4d53bb5c592248e36ce3c
parentfb5fb16260568cb4f42afb8bc53cf1c5c091c669
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix TextPlus landscape aspect scaling and 3D shadows/archive parity (#46)


5 files changed, 573 insertions(+), 89 deletions(-)

crates/engine/src/eval/text_3d.rs+9-1
...@@ -514,7 +514,12 @@ impl Engine {...@@ -514,7 +514,12 @@ impl Engine {
514 return empty;514 return empty;
515 };515 };
516516
517 let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5;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");
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.
521 let shadows_enabled = renderer == "RendererOpenGL"
522 && comp.eval_number(node, "RendererOpenGL.ShadowsEnabled", time, 0.0, &self.expr) > 0.5;
518 let mut cameras = Vec::new();523 let mut cameras = Vec::new();
519 let mut mesh_specs = Vec::new();524 let mut mesh_specs = Vec::new();
520 let mut lights = crate::scene3d::SceneLights::default();525 let mut lights = crate::scene3d::SceneLights::default();
...@@ -549,6 +554,7 @@ impl Engine {...@@ -549,6 +554,7 @@ impl Engine {
549 let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20);554 let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20);
550 hash_floats.extend_from_slice(&view_proj);555 hash_floats.extend_from_slice(&view_proj);
551 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });556 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
557 hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 });
552 hash_floats.extend_from_slice(&lights.ambient);558 hash_floats.extend_from_slice(&lights.ambient);
553 for dl in &lights.dirs {559 for dl in &lights.dirs {
554 hash_floats.extend_from_slice(&dl.to_light);560 hash_floats.extend_from_slice(&dl.to_light);
...@@ -559,6 +565,7 @@ impl Engine {...@@ -559,6 +565,7 @@ impl Engine {
559 hash_floats.extend_from_slice(&pl.color);565 hash_floats.extend_from_slice(&pl.color);
560 hash_floats.push(pl.decay_type);566 hash_floats.push(pl.decay_type);
561 hash_floats.push(pl.decay_rate);567 hash_floats.push(pl.decay_rate);
568 hash_floats.push(pl.shadow_density.unwrap_or(-1.0));
562 }569 }
563 for sl in &lights.spots {570 for sl in &lights.spots {
564 hash_floats.extend_from_slice(&sl.pos);571 hash_floats.extend_from_slice(&sl.pos);
...@@ -665,6 +672,7 @@ impl Engine {...@@ -665,6 +672,7 @@ impl Engine {
665 cam_pos,672 cam_pos,
666 lights,673 lights,
667 lighting_enabled,674 lighting_enabled,
675 shadows_enabled,
668 &draw_meshes,676 &draw_meshes,
669 );677 );
670 self.cache.insert(key, dst.clone(), node.id, frame_i);678 self.cache.insert(key, dst.clone(), node.id, frame_i);
crates/engine/src/scene3d/collect.rs+130-79
...@@ -257,53 +257,74 @@ fn collect_scene_inner(...@@ -257,53 +257,74 @@ fn collect_scene_inner(
257 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;257 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;
258 let far = 5000.0_f32;258 let far = 5000.0_f32;
259 cameras.push(CameraInstance { world, vfov_rad, near, far });259 cameras.push(CameraInstance { world, vfov_rad, near, far });
260 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
261 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
262 }
260 }263 }
261 "LightAmbient" => {264 "LightAmbient" => {
262 let Some(color) = light_color(comp, node, time, expr) else { return };265 if let Some(color) = light_color(comp, node, time, expr) {
263 for (acc, c) in lights.ambient.iter_mut().zip(color) {266 for (acc, c) in lights.ambient.iter_mut().zip(color) {
264 *acc += c;267 *acc += c;
268 }
269 }
270 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
271 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
265 }272 }
266 }273 }
267 "LightDirectional" => {274 "LightDirectional" => {
268 let Some(color) = light_color(comp, node, time, expr) else { return };275 if let Some(color) = light_color(comp, node, time, expr) {
269 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!276 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
270 let dx = world[8];277 let dx = world[8];
271 let dy = world[9];278 let dy = world[9];
272 let dz = world[10];279 let dz = world[10];
273 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);280 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
274 lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color });281 lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color });
282 }
283 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
284 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
285 }
275 }286 }
276 "LightPoint" => {287 "LightPoint" => {
277 let Some(color) = light_color(comp, node, time, expr) else { return };288 if let Some(color) = light_color(comp, node, time, expr) {
278 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;289 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
279 lights.points.push(PointLight {290 lights.points.push(PointLight {
280 pos: [world[12], world[13], world[14]],291 pos: [world[12], world[13], world[14]],
281 color,292 color,
282 decay_type,293 decay_type,
283 decay_rate: 1.0,294 decay_rate: 1.0,
284 });295 shadow_density: (comp.eval_number(node, "ShadowLightInputs3D.ShadowsEnabled", time, 0.0, expr) > 0.5)
296 .then(|| comp.eval_number(node, "ShadowLightInputs3D.ShadowDensity", time, 0.5, expr).clamp(0.0, 1.0) as f32),
297 });
298 }
299 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
300 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
301 }
285 }302 }
286 "LightSpot" => {303 "LightSpot" => {
287 let Some(color) = light_color(comp, node, time, expr) else { return };304 if let Some(color) = light_color(comp, node, time, expr) {
288 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;305 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
289 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;306 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
290 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;307 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
291 // SpotLight shines along -Z in local space308 // SpotLight shines along -Z in local space
292 let dx = -world[8];309 let dx = -world[8];
293 let dy = -world[9];310 let dy = -world[9];
294 let dz = -world[10];311 let dz = -world[10];
295 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);312 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
296 let half_cone = (cone_deg * 0.5).max(0.5);313 let half_cone = (cone_deg * 0.5).max(0.5);
297 let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5);314 let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5);
298 let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg);315 let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg);
299 lights.spots.push(SpotLight {316 lights.spots.push(SpotLight {
300 pos: [world[12], world[13], world[14]],317 pos: [world[12], world[13], world[14]],
301 dir: [dx / len, dy / len, dz / len],318 dir: [dx / len, dy / len, dz / len],
302 color,319 color,
303 cos_inner: inner_deg.to_radians().cos(),320 cos_inner: inner_deg.to_radians().cos(),
304 cos_outer: outer_deg.to_radians().cos(),321 cos_outer: outer_deg.to_radians().cos(),
305 decay_type,322 decay_type,
306 });323 });
324 }
325 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
326 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
327 }
307 }328 }
308 "ImagePlane3D" => {329 "ImagePlane3D" => {
309 let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return };330 let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return };
...@@ -316,48 +337,52 @@ fn collect_scene_inner(...@@ -316,48 +337,52 @@ fn collect_scene_inner(
316 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));337 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));
317 }338 }
318 "Shape3D" => {339 "Shape3D" => {
319 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");340 if let Some(own) = surface_scope(comp, node, node.static_str("Shape").unwrap_or("SurfacePlaneInputs"), ovr, time, expr) {
320 let Some(own) = surface_scope(comp, node, shape_name, ovr, time, expr) else { return };341 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
321 let shape = match shape_name {342 let shape = match shape_name {
322 "SurfaceSphereInputs" => ShapeKind::Sphere {343 "SurfaceSphereInputs" => ShapeKind::Sphere {
323 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)344 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)
324 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32,345 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32,
325 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,346 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
326 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32,347 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32,
327 },348 },
328 "SurfaceCylinderInputs" => {349 "SurfaceCylinderInputs" => {
329 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;350 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;
330 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;351 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;
331 ShapeKind::Cylinder {352 ShapeKind::Cylinder {
332 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32,353 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32,
333 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32,354 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32,
334 start_sweep_deg: start_sw,355 start_sweep_deg: start_sw,
335 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },356 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
336 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,357 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
358 }
337 }359 }
360 "SurfaceCubeInputs" => ShapeKind::Cube {
361 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
362 sub: cube_subdivisions(comp, node, time, expr),
363 faces: 0b11_1111,
364 },
365 _ => {
366 // Fusion's plane is square: Height and SubdivisionHeight follow Width.
367 let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32;
368 let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32;
369 ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub }
370 }
371 };
372 let mat_node = ovr.material_override.or_else(|| {
373 node.connected_node("MaterialInput")
374 .and_then(|s| comp.find_node(s))
375 });
376 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
377 if !mat.has_material_shader {
378 apply_mtl_std(&mut mat, comp, node, "", time, expr);
338 }379 }
339 "SurfaceCubeInputs" => ShapeKind::Cube {380 mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5;
340 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,381 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
341 sub: cube_subdivisions(comp, node, time, expr),382 }
342 faces: 0b11_1111,383 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
343 },384 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
344 _ => {
345 // Fusion's plane is square: Height and SubdivisionHeight follow Width.
346 let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32;
347 let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32;
348 ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub }
349 }
350 };
351 let mat_node = ovr.material_override.or_else(|| {
352 node.connected_node("MaterialInput")
353 .and_then(|s| comp.find_node(s))
354 });
355 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
356 if mat_node.is_none() {
357 apply_mtl_std(&mut mat, comp, node, "", time, expr);
358 }385 }
359 mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5;
360 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
361 }386 }
362 "Cube3D" => {387 "Cube3D" => {
363 if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) {388 if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) {
...@@ -372,7 +397,7 @@ fn collect_scene_inner(...@@ -372,7 +397,7 @@ fn collect_scene_inner(
372 .and_then(|s| comp.find_node(s))397 .and_then(|s| comp.find_node(s))
373 });398 });
374 let mut mat = resolve_material(comp, mat_node, time, expr, visited);399 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
375 if mat_node.is_none() {400 if !mat.has_material_shader {
376 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);401 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);
377 }402 }
378 mat.fx.wireframe = wireframe;403 mat.fx.wireframe = wireframe;
...@@ -410,7 +435,7 @@ fn collect_scene_inner(...@@ -410,7 +435,7 @@ fn collect_scene_inner(
410 .and_then(|s| comp.find_node(s))435 .and_then(|s| comp.find_node(s))
411 });436 });
412 let mut mat = resolve_material(comp, mat_node, time, expr, visited);437 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
413 if mat_node.is_none() {438 if !mat.has_material_shader {
414 apply_mtl_std(&mut mat, comp, node, "", time, expr);439 apply_mtl_std(&mut mat, comp, node, "", time, expr);
415 }440 }
416 meshes.push(make_mesh_instance(world, shape, mat, None, &own));441 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
...@@ -437,6 +462,9 @@ fn collect_scene_inner(...@@ -437,6 +462,9 @@ fn collect_scene_inner(
437 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },462 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
438 };463 };
439 meshes.push(make_mesh_instance(world, shape, mat, Some(Text3DSpec { node_id }), ovr));464 meshes.push(make_mesh_instance(world, shape, mat, Some(Text3DSpec { node_id }), ovr));
465 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
466 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
467 }
440 }468 }
441 "MacroOperator" | "GroupOperator" => {469 "MacroOperator" | "GroupOperator" => {
442 if let Some(out_id) = node.macro_output {470 if let Some(out_id) = node.macro_output {
...@@ -457,6 +485,9 @@ struct ResolvedMaterial {...@@ -457,6 +485,9 @@ struct ResolvedMaterial {
457 fx: MaterialFx,485 fx: MaterialFx,
458 /// A bare texture operator used as a surface's material renders flat, ignoring lights.486 /// A bare texture operator used as a surface's material renders flat, ignoring lights.
459 unlit: bool,487 unlit: bool,
488 /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`),
489 /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`.
490 has_material_shader: bool,
460}491}
461492
462impl Default for ResolvedMaterial {493impl Default for ResolvedMaterial {
...@@ -469,6 +500,7 @@ impl Default for ResolvedMaterial {...@@ -469,6 +500,7 @@ impl Default for ResolvedMaterial {
469 specular_exponent: 50.0,500 specular_exponent: 50.0,
470 fx: MaterialFx::default(),501 fx: MaterialFx::default(),
471 unlit: false,502 unlit: false,
503 has_material_shader: false,
472 }504 }
473 }505 }
474}506}
...@@ -705,6 +737,7 @@ fn resolve_material_inner(...@@ -705,6 +737,7 @@ fn resolve_material_inner(
705 specular_exponent: spec_exp,737 specular_exponent: spec_exp,
706 fx,738 fx,
707 unlit: false,739 unlit: false,
740 has_material_shader: true,
708 }741 }
709 }742 }
710 _ => ResolvedMaterial {743 _ => ResolvedMaterial {
...@@ -1268,4 +1301,22 @@ mod tests {...@@ -1268,4 +1301,22 @@ mod tests {
1268 assert!(inv.iter().all(|v| v.is_finite()));1301 assert!(inv.iter().all(|v| v.is_finite()));
1269 assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0));1302 assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0));
1270 }1303 }
1304
1305 #[test]
1306 fn camera3d_passes_scene_input_and_cube3d_tints_textured_faces() {
1307 let src = comp_src(
1308 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1309 Cube = Cube3D { Inputs = {
1310 FrontMaterialInput = Input { SourceOp = "Bg", Source = "Output", },
1311 ["Front.MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.5, },
1312 ["Front.MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, },
1313 }, },
1314 Cam = Camera3D { Inputs = { SceneInput = Input { SourceOp = "Cube", Source = "Output", }, }, },"#,
1315 );
1316 let (cams, meshes, _) = collect(&src, "Cam");
1317 assert_eq!(cams.len(), 1);
1318 assert!(meshes.len() >= 2, "Camera3D must pass SceneInput Cube3D through");
1319 let front = meshes.iter().find(|m| matches!(m.shape.base_shape(), ShapeKind::Cube { faces: 1, .. })).unwrap();
1320 assert_eq!(front.diffuse_col, [1.0, 0.5, 0.0, 1.0]);
1321 }
1271}1322}
crates/engine/src/scene3d/mod.rs+299-3
...@@ -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, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D};28use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER};
2929
30pub type Mat4 = [f32; 16]; // Column-major 4x430pub type Mat4 = [f32; 16]; // Column-major 4x4
3131
...@@ -36,6 +36,11 @@ pub struct Scene3DRenderer {...@@ -36,6 +36,11 @@ pub struct Scene3DRenderer {
36 pipelines: [[wgpu::RenderPipeline; 2]; 2],36 pipelines: [[wgpu::RenderPipeline; 2]; 2],
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,
40 /// Bound for `Caster` (group 0) and `Face` (group 1) uniforms of the shadow pass.
41 shadow_uniform_bgl: wgpu::BindGroupLayout,
42 /// 1x1 map bound when no light casts shadows.
43 shadow_dummy: wgpu::TextureView,
39}44}
4045
41/// Most meshes kept resident on the GPU across frames.46/// Most meshes kept resident on the GPU across frames.
...@@ -322,6 +327,8 @@ pub struct PointLight {...@@ -322,6 +327,8 @@ pub struct PointLight {
322 pub decay_type: f32,327 pub decay_type: f32,
323 /// Unused by the shader; `Renderer3D` still folds it into its cache key.328 /// Unused by the shader; `Renderer3D` still folds it into its cache key.
324 pub decay_rate: f32,329 pub decay_rate: f32,
330 /// Shadow density in `0..=1` when the light casts shadows.
331 pub shadow_density: Option<f32>,
325}332}
326333
327#[derive(Clone, Copy, Debug)]334#[derive(Clone, Copy, Debug)]
...@@ -370,14 +377,41 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {...@@ -370,14 +377,41 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
370 (h.finish(), aspect_bits, wireframe)377 (h.finish(), aspect_bits, wireframe)
371}378}
372379
380/// 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);
383 [
384 ([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]),
386 ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
387 ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
388 ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
389 ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
390 ]
391 .map(|(f, up)| {
392 let right = [f[1] * up[2] - f[2] * up[1], f[2] * up[0] - f[0] * up[2], f[0] * up[1] - f[1] * up[0]];
393 let up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]];
394 let dot = |a: [f32; 3]| a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2];
395 let view = [
396 right[0], up[0], -f[0], 0.0,
397 right[1], up[1], -f[1], 0.0,
398 right[2], up[2], -f[2], 0.0,
399 -dot(right), -dot(up), dot(f), 1.0,
400 ];
401 mat4_mul(proj, view)
402 })
403}
404
373impl Scene3DRenderer {405impl Scene3DRenderer {
374 pub fn new(device: &wgpu::Device) -> Self {406 pub fn new(device: &wgpu::Device) -> Self {
375 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {407 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
376 label: Some("scene3d-shader"),408 label: Some("scene3d-shader"),
377 source: wgpu::ShaderSource::Wgsl(409 source: wgpu::ShaderSource::Wgsl(
378 SHADER_3D410 SHADER_3D
411 .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string())
379 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())412 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())
380 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())413 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())
414 .replace("SHADOW_MAP_SIZE", &SHADOW_MAP_SIZE.to_string())
381 .into(),415 .into(),
382 ),416 ),
383 });417 });
...@@ -410,6 +444,26 @@ impl Scene3DRenderer {...@@ -410,6 +444,26 @@ impl Scene3DRenderer {
410 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),444 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
411 count: None,445 count: None,
412 },446 },
447 wgpu::BindGroupLayoutEntry {
448 binding: 3,
449 visibility: wgpu::ShaderStages::FRAGMENT,
450 ty: wgpu::BindingType::Buffer {
451 ty: wgpu::BufferBindingType::Uniform,
452 has_dynamic_offset: false,
453 min_binding_size: None,
454 },
455 count: None,
456 },
457 wgpu::BindGroupLayoutEntry {
458 binding: 4,
459 visibility: wgpu::ShaderStages::FRAGMENT,
460 ty: wgpu::BindingType::Texture {
461 sample_type: wgpu::TextureSampleType::Float { filterable: false },
462 view_dimension: wgpu::TextureViewDimension::D2Array,
463 multisampled: false,
464 },
465 count: None,
466 },
413 ],467 ],
414 });468 });
415 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {469 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
...@@ -475,7 +529,83 @@ impl Scene3DRenderer {...@@ -475,7 +529,83 @@ impl Scene3DRenderer {
475 mipmap_filter: wgpu::MipmapFilterMode::Linear,529 mipmap_filter: wgpu::MipmapFilterMode::Linear,
476 ..Default::default()530 ..Default::default()
477 });531 });
478 Self { bgl, pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)) }532 let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
533 label: Some("scene3d-shadow-shader"),
534 source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()),
535 });
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,
545 },
546 count: None,
547 }],
548 });
549 let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
550 label: Some("scene3d-shadow-pl"),
551 bind_group_layouts: &[Some(&shadow_uniform_bgl), Some(&shadow_uniform_bgl)],
552 immediate_size: 0,
553 });
554 let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
555 label: Some("scene3d-shadow"),
556 layout: Some(&shadow_pl),
557 vertex: wgpu::VertexState {
558 module: &shadow_shader,
559 entry_point: Some("vs_shadow"),
560 compilation_options: Default::default(),
561 buffers: &[Some(vbuf_layout)],
562 },
563 fragment: Some(wgpu::FragmentState {
564 module: &shadow_shader,
565 entry_point: Some("fs_shadow"),
566 compilation_options: Default::default(),
567 targets: &[Some(wgpu::ColorTargetState {
568 format: wgpu::TextureFormat::R32Float,
569 blend: None,
570 write_mask: wgpu::ColorWrites::ALL,
571 })],
572 }),
573 primitive: wgpu::PrimitiveState::default(),
574 depth_stencil: Some(wgpu::DepthStencilState {
575 format: wgpu::TextureFormat::Depth32Float,
576 depth_write_enabled: Some(true),
577 depth_compare: Some(wgpu::CompareFunction::Less),
578 stencil: wgpu::StencilState::default(),
579 bias: wgpu::DepthBiasState::default(),
580 }),
581 multisample: wgpu::MultisampleState::default(),
582 multiview_mask: None,
583 cache: None,
584 });
585 let shadow_dummy = device
586 .create_texture(&wgpu::TextureDescriptor {
587 label: Some("scene3d-shadow-dummy"),
588 size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
589 mip_level_count: 1,
590 sample_count: 1,
591 dimension: wgpu::TextureDimension::D2,
592 format: wgpu::TextureFormat::R32Float,
593 usage: wgpu::TextureUsages::TEXTURE_BINDING,
594 view_formats: &[],
595 })
596 .create_view(&wgpu::TextureViewDescriptor {
597 dimension: Some(wgpu::TextureViewDimension::D2Array),
598 ..Default::default()
599 });
600 Self {
601 bgl,
602 pipelines,
603 sampler,
604 meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)),
605 shadow_pipeline,
606 shadow_uniform_bgl,
607 shadow_dummy,
608 }
479 }609 }
480610
481 #[allow(clippy::too_many_arguments)]611 #[allow(clippy::too_many_arguments)]
...@@ -491,6 +621,7 @@ impl Scene3DRenderer {...@@ -491,6 +621,7 @@ impl Scene3DRenderer {
491 cam_pos: [f32; 3],621 cam_pos: [f32; 3],
492 lights: SceneLights,622 lights: SceneLights,
493 lighting_enabled: bool,623 lighting_enabled: bool,
624 shadows_enabled: bool,
494 meshes: &[DrawMesh],625 meshes: &[DrawMesh],
495 ) {626 ) {
496 let depth_tex = device.create_texture(&wgpu::TextureDescriptor {627 let depth_tex = device.create_texture(&wgpu::TextureDescriptor {
...@@ -509,6 +640,68 @@ impl Scene3DRenderer {...@@ -509,6 +640,68 @@ impl Scene3DRenderer {
509 });640 });
510 let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());641 let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
511642
643 // Point-light indices that get a cube shadow map, in slot order.
644 let shadow_lights: Vec<usize> = if shadows_enabled {
645 (0..lights.points.len().min(MAX_LIGHTS))
646 .filter(|&i| lights.points[i].shadow_density.is_some())
647 .take(MAX_SHADOW_LIGHTS)
648 .collect()
649 } else {
650 Vec::new()
651 };
652 let mut shadow_uni = ShadowUniform {
653 face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS],
654 point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS],
655 };
656 for (slot, &li) in shadow_lights.iter().enumerate() {
657 let pl = &lights.points[li];
658 shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&cube_face_view_projections(pl.pos));
659 shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0];
660 }
661 let shadow_ubuf = device.create_buffer(&wgpu::BufferDescriptor {
662 label: Some("scene3d-shadow-u"),
663 size: std::mem::size_of::<ShadowUniform>() as u64,
664 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
665 mapped_at_creation: false,
666 });
667 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 })
683 });
684 let shadow_view = shadow_map.as_ref().map(|t| {
685 t.create_view(&wgpu::TextureViewDescriptor {
686 dimension: Some(wgpu::TextureViewDimension::D2Array),
687 ..Default::default()
688 })
689 });
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,
694 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
695 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 })
703 };
704
512 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.705 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.
513 let mut order: Vec<(usize, f32)> = meshes706 let mut order: Vec<(usize, f32)> = meshes
514 .iter()707 .iter()
...@@ -528,6 +721,8 @@ impl Scene3DRenderer {...@@ -528,6 +721,8 @@ impl Scene3DRenderer {
528 /// Skip the `[back-facing, front-facing]` pass.721 /// Skip the `[back-facing, front-facing]` pass.
529 cull: [bool; 2],722 cull: [bool; 2],
530 bg: wgpu::BindGroup,723 bg: wgpu::BindGroup,
724 /// `model` for the shadow pass; `None` for meshes that cast no shadow.
725 caster: Option<wgpu::BindGroup>,
531 vbuf: wgpu::Buffer,726 vbuf: wgpu::Buffer,
532 ibuf: wgpu::Buffer,727 ibuf: wgpu::Buffer,
533 idx_count: u32,728 idx_count: u32,
...@@ -660,18 +855,88 @@ impl Scene3DRenderer {...@@ -660,18 +855,88 @@ impl Scene3DRenderer {
660 wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },855 wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
661 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) },856 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) },
662 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },857 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
858 wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() },
859 wgpu::BindGroupEntry {
860 binding: 4,
861 resource: wgpu::BindingResource::TextureView(shadow_view.as_ref().unwrap_or(&self.shadow_dummy)),
862 },
663 ],863 ],
664 });864 });
665 draw_items.push(GpuDraw {865 draw_items.push(GpuDraw {
666 wireframe: fx.wireframe,866 wireframe: fx.wireframe,
667 cull: [fx.cull_back, fx.cull_front],867 cull: [fx.cull_back, fx.cull_front],
668 bg,868 bg,
869 caster: (!fx.wireframe && !shadow_lights.is_empty())
870 .then(|| uniform_bind_group("scene3d-caster", bytemuck::cast_slice(&m.world))),
669 vbuf,871 vbuf,
670 ibuf,872 ibuf,
671 idx_count,873 idx_count,
672 });874 });
673 }875 }
674876
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());
890 for (slot, &li) in shadow_lights.iter().enumerate() {
891 let pos = lights.points[li].pos;
892 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]);
896 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 {
899 dimension: Some(wgpu::TextureViewDimension::D2),
900 base_array_layer: layer,
901 array_layer_count: Some(1),
902 ..Default::default()
903 });
904 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
905 label: Some("scene3d-shadow-pass"),
906 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
907 view: &layer_view,
908 depth_slice: None,
909 resolve_target: None,
910 ops: wgpu::Operations {
911 load: wgpu::LoadOp::Clear(wgpu::Color { r: 1e30, g: 0.0, b: 0.0, a: 0.0 }),
912 store: wgpu::StoreOp::Store,
913 },
914 })],
915 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
916 view: &shadow_depth_view,
917 depth_ops: Some(wgpu::Operations {
918 load: wgpu::LoadOp::Clear(1.0),
919 store: wgpu::StoreOp::Discard,
920 }),
921 stencil_ops: None,
922 }),
923 timestamp_writes: None,
924 occlusion_query_set: None,
925 multiview_mask: None,
926 });
927 pass.set_pipeline(&self.shadow_pipeline);
928 pass.set_bind_group(1, &face_bg, &[]);
929 for d in &draw_items {
930 let Some(caster) = &d.caster else { continue };
931 pass.set_bind_group(0, caster, &[]);
932 pass.set_vertex_buffer(0, d.vbuf.slice(..));
933 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
934 pass.draw_indexed(0..d.idx_count, 0, 0..1);
935 }
936 }
937 }
938 }
939
675 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {940 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
676 label: Some("scene3d-pass"),941 label: Some("scene3d-pass"),
677 color_attachments: &[Some(wgpu::RenderPassColorAttachment {942 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
...@@ -864,7 +1129,7 @@ mod tests {...@@ -864,7 +1129,7 @@ mod tests {
864 let frame = |meshes: &[DrawMesh]| {1129 let frame = |meshes: &[DrawMesh]| {
865 let mut enc = device.create_command_encoder(&Default::default());1130 let mut enc = device.create_command_encoder(&Default::default());
866 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);1131 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);
867 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, meshes);1132 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, false, meshes);
868 queue.submit(Some(enc.finish()));1133 queue.submit(Some(enc.finish()));
869 renderer.meshes.lock().unwrap().entries.len()1134 renderer.meshes.lock().unwrap().entries.len()
870 };1135 };
...@@ -897,4 +1162,35 @@ mod tests {...@@ -897,4 +1162,35 @@ mod tests {
897 assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]);1162 assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]);
898 assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]);1163 assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]);
899 }1164 }
1165
1166 #[test]
1167 fn opengl_renderer_lighting_and_point_light_shadows() {
1168 let render_gl = |lighting: u8, shadows: u8| -> Option<Vec<u8>> {
1169 let src = format!(
1170 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
1171 Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }},
1172 Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }},
1173 Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }},
1174 Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }},
1175 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }},
1176 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},
1177 R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = {lighting}, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }},
1178 }} }}"#
1179 );
1180 let comp = Comp::from_fusion_str(&src).expect("parse shadow comp");
1181 let mut eng = Engine::new_headless().ok()?;
1182 let id = comp.find_node("R").expect("R");
1183 let (tex, _) = eng.evaluate(&comp, id, 0.0);
1184 eng.readback_rgba(&tex).ok()
1185 };
1186 let (Some(unlit), Some(no_shad), Some(with_shad)) = (render_gl(0, 0), render_gl(1, 0), render_gl(1, 1)) else {
1187 return;
1188 };
1189 // With LightingEnabled=0 under RendererOpenGL, receiver is pure flat white.
1190 let px = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4];
1191 assert_eq!(px(&unlit, 8, 32), 255);
1192 // Blocker at (0,0,0) casts a shadow onto Recv (Z=-2) to the left of center when viewed from X=1.8.
1193 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));
1195 }
900}1196}
crates/engine/src/scene3d/shader.rs+95-6
...@@ -6,6 +6,10 @@ use bytemuck::{Pod, Zeroable};...@@ -6,6 +6,10 @@ use bytemuck::{Pod, Zeroable};
6pub(super) const MAX_LIGHTS: usize = 8;6pub(super) const MAX_LIGHTS: usize = 8;
7/// Directional lights get this many shader slots.7/// Directional lights get this many shader slots.
8pub(super) const MAX_DIR_LIGHTS: usize = 4;8pub(super) const MAX_DIR_LIGHTS: usize = 4;
9/// Point lights that can cast shadows in one render.
10pub(super) const MAX_SHADOW_LIGHTS: usize = 4;
11/// Edge length in texels of each cube-map face.
12pub(super) const SHADOW_MAP_SIZE: u32 = 1024;
913
10#[repr(C)]14#[repr(C)]
11#[derive(Clone, Copy, Debug, Pod, Zeroable)]15#[derive(Clone, Copy, Debug, Pod, Zeroable)]
...@@ -56,7 +60,43 @@ pub(super) struct MeshUniform {...@@ -56,7 +60,43 @@ pub(super) struct MeshUniform {
56 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],60 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],
57}61}
5862
59/// WGSL source; `MAX_LIGHTS` and `MAX_DIR_LIGHTS` are substituted with the Rust constants at pipeline creation.63#[repr(C)]
64#[derive(Clone, Copy, Pod, Zeroable)]
65pub(super) struct ShadowUniform {
66 /// Cube-face view-projections, six per shadow slot (`+X -X +Y -Y +Z -Z`).
67 pub(super) face_vp: [[f32; 16]; 6 * MAX_SHADOW_LIGHTS],
68 /// Per point light `(shadow slot or -1, density, 0, 0)`.
69 pub(super) point: [[f32; 4]; MAX_LIGHTS],
70}
71
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.
74pub(super) const SHADOW_SHADER: &str = r#"
75struct Caster { model: mat4x4<f32> };
76struct Face { vp: mat4x4<f32>, light_pos: vec4<f32> };
77
78@group(0) @binding(0) var<uniform> caster: Caster;
79@group(1) @binding(0) var<uniform> face: Face;
80
81struct VsOut {
82 @builtin(position) clip: vec4<f32>,
83 @location(0) world_pos: vec3<f32>,
84};
85
86@vertex
87fn vs_shadow(@location(0) pos: vec3<f32>) -> VsOut {
88 let wp = caster.model * vec4<f32>(pos, 1.0);
89 return VsOut(face.vp * wp, wp.xyz);
90}
91
92@fragment
93fn fs_shadow(in: VsOut) -> @location(0) f32 {
94 return distance(in.world_pos, face.light_pos.xyz);
95}
96"#;
97
98/// WGSL source; `MAX_LIGHTS`, `MAX_DIR_LIGHTS`, `MAX_SHADOW_LIGHTS` and `SHADOW_MAP_SIZE` are
99/// substituted with the Rust constants at pipeline creation.
60pub(super) const SHADER_3D: &str = r#"100pub(super) const SHADER_3D: &str = r#"
61struct MeshUniform {101struct MeshUniform {
62 mvp: mat4x4<f32>,102 mvp: mat4x4<f32>,
...@@ -80,11 +120,18 @@ struct MeshUniform {...@@ -80,11 +120,18 @@ struct MeshUniform {
80 spot_col: array<vec4<f32>, MAX_LIGHTS>,120 spot_col: array<vec4<f32>, MAX_LIGHTS>,
81};121};
82122
123struct ShadowUniform {
124 face_vp: array<mat4x4<f32>, 6 * MAX_SHADOW_LIGHTS>,
125 point: array<vec4<f32>, MAX_LIGHTS>,
126};
127
83override BACK_PASS: bool = false;128override BACK_PASS: bool = false;
84129
85@group(0) @binding(0) var<uniform> u: MeshUniform;130@group(0) @binding(0) var<uniform> u: MeshUniform;
86@group(0) @binding(1) var mat_tex: texture_2d<f32>;131@group(0) @binding(1) var mat_tex: texture_2d<f32>;
87@group(0) @binding(2) var mat_samp: sampler;132@group(0) @binding(2) var mat_samp: sampler;
133@group(0) @binding(3) var<uniform> shadow: ShadowUniform;
134@group(0) @binding(4) var shadow_maps: texture_2d_array<f32>;
88135
89struct VsIn {136struct VsIn {
90 @location(0) pos: vec3<f32>,137 @location(0) pos: vec3<f32>,
...@@ -138,6 +185,41 @@ fn light_attenuation(dist: f32, decay_type: f32) -> f32 {...@@ -138,6 +185,41 @@ fn light_attenuation(dist: f32, decay_type: f32) -> f32 {
138 return 1.0;185 return 1.0;
139}186}
140187
188/// Fraction of PCF taps where the cube map of point light `i` records a closer occluder.
189fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos: vec3<f32>) -> f32 {
190 let params = shadow.point[i];
191 if (params.x < -0.5) {
192 return 0.0;
193 }
194 let slot = i32(params.x + 0.5);
195 let d = world_pos - light_pos;
196 let dist = length(d);
197 let a = abs(d);
198 var face = 4;
199 if (a.x >= a.y && a.x >= a.z) {
200 face = select(1, 0, d.x > 0.0);
201 } else if (a.y >= a.z) {
202 face = select(3, 2, d.y > 0.0);
203 } else {
204 face = select(5, 4, d.z > 0.0);
205 }
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);
209 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)));
211 let last = SHADOW_MAP_SIZE - 1;
212 var occluded = 0.0;
213 for (var dy: i32 = -1; dy <= 1; dy = dy + 1) {
214 for (var dx: i32 = -1; dx <= 1; dx = dx + 1) {
215 let t = clamp(base + vec2<i32>(dx, dy), vec2<i32>(0), vec2<i32>(last));
216 let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r;
217 occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored);
218 }
219 }
220 return occluded / 9.0;
221}
222
141fn eval_light_contrib(223fn eval_light_contrib(
142 n: vec3<f32>,224 n: vec3<f32>,
143 v: vec3<f32>,225 v: vec3<f32>,
...@@ -147,12 +229,14 @@ fn eval_light_contrib(...@@ -147,12 +229,14 @@ fn eval_light_contrib(
147 spec_rgb: vec3<f32>,229 spec_rgb: vec3<f32>,
148 spec_int: f32,230 spec_int: f32,
149 shininess: f32,231 shininess: f32,
232 diffuse_vis: f32,
233 spec_vis: f32,
150) -> vec3<f32> {234) -> vec3<f32> {
151 let ndotl = max(dot(n, l), 0.0);235 let ndotl = max(dot(n, l), 0.0);
152 if (ndotl <= 0.0) {236 if (ndotl <= 0.0) {
153 return vec3<f32>(0.0);237 return vec3<f32>(0.0);
154 }238 }
155 var out = albedo * light_rgb * ndotl;239 var out = albedo * light_rgb * (ndotl * diffuse_vis);
156 if (spec_int > 1e-4) {240 if (spec_int > 1e-4) {
157 let h = normalize(l + v);241 let h = normalize(l + v);
158 let model = i32(u.mat_fx.w + 0.5);242 let model = i32(u.mat_fx.w + 0.5);
...@@ -167,7 +251,7 @@ fn eval_light_contrib(...@@ -167,7 +251,7 @@ fn eval_light_contrib(
167 } else {251 } else {
168 lobe = pow(max(dot(n, h), 0.0), shininess);252 lobe = pow(max(dot(n, h), 0.0), shininess);
169 }253 }
170 out = out + light_rgb * spec_rgb * (lobe * spec_int);254 out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis);
171 }255 }
172 return out;256 return out;
173}257}
...@@ -295,7 +379,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -295,7 +379,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
295 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {379 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {
296 if (i >= n_dir) { break; }380 if (i >= n_dir) { break; }
297 let l = normalize(u.dir_to_light[i].xyz);381 let l = normalize(u.dir_to_light[i].xyz);
298 lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess);382 lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0);
299 }383 }
300384
301 let n_pt = i32(u.light_counts.x + 0.5);385 let n_pt = i32(u.light_counts.x + 0.5);
...@@ -304,7 +388,12 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -304,7 +388,12 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
304 let to_l = u.point_pos[i].xyz - in.world_pos;388 let to_l = u.point_pos[i].xyz - in.world_pos;
305 let dist = max(length(to_l), 1e-4);389 let dist = max(length(to_l), 1e-4);
306 let att = light_attenuation(dist, u.point_pos[i].w);390 let att = light_attenuation(dist, u.point_pos[i].w);
307 lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);391 // Shadow density dims only the diffuse term; specular is cut outright.
392 let occ = point_shadow_occlusion(i, in.world_pos, n, u.point_pos[i].xyz);
393 lit = lit + eval_light_contrib(
394 n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess,
395 1.0 - shadow.point[i].y * occ, 1.0 - occ,
396 );
308 }397 }
309398
310 let n_sp = i32(u.light_counts.y + 0.5);399 let n_sp = i32(u.light_counts.y + 0.5);
...@@ -320,7 +409,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -320,7 +409,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
320 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);409 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);
321 if (cone > 0.0) {410 if (cone > 0.0) {
322 let att = light_attenuation(dist, u.spot_col[i].w) * cone;411 let att = light_attenuation(dist, u.spot_col[i].w) * cone;
323 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);412 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0);
324 }413 }
325 }414 }
326415
crates/engine/src/text_engine.rs+40
...@@ -76,10 +76,25 @@ pub fn parse_style(style: &str) -> (u16, bool) {...@@ -76,10 +76,25 @@ pub fn parse_style(style: &str) -> (u16, bool) {
76 (weight, s.contains("italic") || s.contains("oblique"))76 (weight, s.contains("italic") || s.contains("oblique"))
77}77}
7878
79fn metric_alias(family: &str) -> Option<&'static str> {
80 if family.eq_ignore_ascii_case("Liberation Sans") {
81 Some("Arial")
82 } else if family.eq_ignore_ascii_case("Arial") {
83 Some("Liberation Sans")
84 } else if family.eq_ignore_ascii_case("Liberation Serif") {
85 Some("Times New Roman")
86 } else if family.eq_ignore_ascii_case("Liberation Mono") {
87 Some("Courier New")
88 } else {
89 None
90 }
91}
92
79fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {93fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {
80 let (weight, italic) = parse_style(style);94 let (weight, italic) = parse_style(style);
81 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();95 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
82 let id = std::iter::once(family)96 let id = std::iter::once(family)
97 .chain(metric_alias(family))
83 .chain(FALLBACK_FAMILIES)98 .chain(FALLBACK_FAMILIES)
84 .find_map(|name| pick(db, name, &wanted, weight, italic))99 .find_map(|name| pick(db, name, &wanted, weight, italic))
85 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))100 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
...@@ -445,4 +460,29 @@ mod tests {...@@ -445,4 +460,29 @@ mod tests {
445 assert!((right[2] - 480).abs() <= 6, "{right:?}");460 assert!((right[2] - 480).abs() <= 6, "{right:?}");
446 assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}");461 assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}");
447 }462 }
463
464 #[test]
465 fn liberation_sans_uses_metric_equivalent_and_landscape_scales_with_width() {
466 let lib_font = Font::find("Liberation Sans", "Regular").expect("Liberation Sans or metric alias");
467 let arial_font = Font::find("Arial", "Regular").expect("Arial");
468 let (lib_face, arial_face) = (lib_font.face(), arial_font.face());
469 let lib_w = shape_line(&lib_face, "Aspect 321", 50.0, 0.0).width;
470 let arial_w = shape_line(&arial_face, "Aspect 321", 50.0, 0.0).width;
471 assert!((lib_w - arial_w).abs() < 1.0, "expected Liberation Sans / Arial metric parity: {lib_w} vs {arial_w}");
472
473 let span = |dims: [u32; 2]| {
474 let mut p = params("Aspect 321");
475 p.font_family = "Liberation Sans";
476 p.size_norm = 0.18;
477 let (sz, orig, rgba) = rasterize_text_plus(dims, &p, 0);
478 let b = alpha_bounds(sz, orig, &rgba).unwrap();
479 (b[2] - b[0] + 1, b[3] - b[1] + 1, (b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
480 };
481 let (lw, lh, lcx, lcy) = span([320, 180]);
482 let (pw, ph, pcx, pcy) = span([180, 320]);
483 assert!((lw as f32 / pw as f32 - 320.0 / 180.0).abs() < 0.08, "landscape/portrait width ratio {lw}/{pw}");
484 assert!((lh as f32 / ph as f32 - 320.0 / 180.0).abs() < 0.12, "landscape/portrait height ratio {lh}/{ph}");
485 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})");
487 }
448}488}