| author | |
| committer | |
| log | 85bce11eb2a2a96f516541c3de49031e337dd4eb |
| tree | f18330856d33ae8bf4d4d53bb5c592248e36ce3c |
| parent | fb5fb16260568cb4f42afb8bc53cf1c5c091c669 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
5 files changed, 573 insertions(+), 89 deletions(-)
crates/engine/src/eval/text_3d.rs+9-1| ... | ... | @@ -514,7 +514,12 @@ impl Engine { |
| 514 | 514 | return empty; |
| 515 | 515 | }; |
| 516 | 516 | |
| 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 | 523 | let mut cameras = Vec::new(); |
| 519 | 524 | let mut mesh_specs = Vec::new(); |
| 520 | 525 | let mut lights = crate::scene3d::SceneLights::default(); |
| ... | ... | @@ -549,6 +554,7 @@ impl Engine { |
| 549 | 554 | let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20); |
| 550 | 555 | hash_floats.extend_from_slice(&view_proj); |
| 551 | 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 | 558 | hash_floats.extend_from_slice(&lights.ambient); |
| 553 | 559 | for dl in &lights.dirs { |
| 554 | 560 | hash_floats.extend_from_slice(&dl.to_light); |
| ... | ... | @@ -559,6 +565,7 @@ impl Engine { |
| 559 | 565 | hash_floats.extend_from_slice(&pl.color); |
| 560 | 566 | hash_floats.push(pl.decay_type); |
| 561 | 567 | hash_floats.push(pl.decay_rate); |
| 568 | hash_floats.push(pl.shadow_density.unwrap_or(-1.0)); | |
| 562 | 569 | } |
| 563 | 570 | for sl in &lights.spots { |
| 564 | 571 | hash_floats.extend_from_slice(&sl.pos); |
| ... | ... | @@ -665,6 +672,7 @@ impl Engine { |
| 665 | 672 | cam_pos, |
| 666 | 673 | lights, |
| 667 | 674 | lighting_enabled, |
| 675 | shadows_enabled, | |
| 668 | 676 | &draw_meshes, |
| 669 | 677 | ); |
| 670 | 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 | 257 | let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; |
| 258 | 258 | let far = 5000.0_f32; |
| 259 | 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 | 264 | "LightAmbient" => { |
| 262 | let Some(color) = light_color(comp, node, time, expr) else { return }; | |
| 263 | for (acc, c) in lights.ambient.iter_mut().zip(color) { | |
| 264 | *acc += c; | |
| 265 | if let Some(color) = light_color(comp, node, time, expr) { | |
| 266 | for (acc, c) in lights.ambient.iter_mut().zip(color) { | |
| 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 | 274 | "LightDirectional" => { |
| 268 | let Some(color) = light_color(comp, node, time, expr) else { return }; | |
| 269 | // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! | |
| 270 | let dx = world[8]; | |
| 271 | let dy = world[9]; | |
| 272 | let dz = world[10]; | |
| 273 | 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 }); | |
| 275 | if let Some(color) = light_color(comp, node, time, expr) { | |
| 276 | // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! | |
| 277 | let dx = world[8]; | |
| 278 | let dy = world[9]; | |
| 279 | let dz = world[10]; | |
| 280 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | |
| 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 | 287 | "LightPoint" => { |
| 277 | let Some(color) = light_color(comp, node, time, expr) else { return }; | |
| 278 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | |
| 279 | lights.points.push(PointLight { | |
| 280 | pos: [world[12], world[13], world[14]], | |
| 281 | color, | |
| 282 | decay_type, | |
| 283 | decay_rate: 1.0, | |
| 284 | }); | |
| 288 | if let Some(color) = light_color(comp, node, time, expr) { | |
| 289 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | |
| 290 | lights.points.push(PointLight { | |
| 291 | pos: [world[12], world[13], world[14]], | |
| 292 | color, | |
| 293 | decay_type, | |
| 294 | decay_rate: 1.0, | |
| 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 | 303 | "LightSpot" => { |
| 287 | let Some(color) = light_color(comp, node, time, expr) else { return }; | |
| 288 | 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; | |
| 290 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | |
| 291 | // SpotLight shines along -Z in local space | |
| 292 | let dx = -world[8]; | |
| 293 | let dy = -world[9]; | |
| 294 | let dz = -world[10]; | |
| 295 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | |
| 296 | let half_cone = (cone_deg * 0.5).max(0.5); | |
| 297 | 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); | |
| 299 | lights.spots.push(SpotLight { | |
| 300 | pos: [world[12], world[13], world[14]], | |
| 301 | dir: [dx / len, dy / len, dz / len], | |
| 302 | color, | |
| 303 | cos_inner: inner_deg.to_radians().cos(), | |
| 304 | cos_outer: outer_deg.to_radians().cos(), | |
| 305 | decay_type, | |
| 306 | }); | |
| 304 | if let Some(color) = light_color(comp, node, time, expr) { | |
| 305 | let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; | |
| 306 | let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; | |
| 307 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | |
| 308 | // SpotLight shines along -Z in local space | |
| 309 | let dx = -world[8]; | |
| 310 | let dy = -world[9]; | |
| 311 | let dz = -world[10]; | |
| 312 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | |
| 313 | let half_cone = (cone_deg * 0.5).max(0.5); | |
| 314 | let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); | |
| 315 | let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); | |
| 316 | lights.spots.push(SpotLight { | |
| 317 | pos: [world[12], world[13], world[14]], | |
| 318 | dir: [dx / len, dy / len, dz / len], | |
| 319 | color, | |
| 320 | cos_inner: inner_deg.to_radians().cos(), | |
| 321 | cos_outer: outer_deg.to_radians().cos(), | |
| 322 | decay_type, | |
| 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 | 329 | "ImagePlane3D" => { |
| 309 | 330 | let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return }; |
| ... | ... | @@ -316,48 +337,52 @@ fn collect_scene_inner( |
| 316 | 337 | meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own)); |
| 317 | 338 | } |
| 318 | 339 | "Shape3D" => { |
| 319 | let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); | |
| 320 | let Some(own) = surface_scope(comp, node, shape_name, ovr, time, expr) else { return }; | |
| 321 | let shape = match shape_name { | |
| 322 | "SurfaceSphereInputs" => ShapeKind::Sphere { | |
| 323 | // 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, | |
| 325 | 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, | |
| 327 | }, | |
| 328 | "SurfaceCylinderInputs" => { | |
| 329 | 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; | |
| 331 | ShapeKind::Cylinder { | |
| 332 | 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, | |
| 334 | start_sweep_deg: start_sw, | |
| 335 | 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, | |
| 340 | if let Some(own) = surface_scope(comp, node, node.static_str("Shape").unwrap_or("SurfacePlaneInputs"), ovr, time, expr) { | |
| 341 | let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); | |
| 342 | let shape = match shape_name { | |
| 343 | "SurfaceSphereInputs" => ShapeKind::Sphere { | |
| 344 | // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) | |
| 345 | radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, | |
| 346 | sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, | |
| 347 | sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32, | |
| 348 | }, | |
| 349 | "SurfaceCylinderInputs" => { | |
| 350 | let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; | |
| 351 | let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; | |
| 352 | ShapeKind::Cylinder { | |
| 353 | radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32, | |
| 354 | height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32, | |
| 355 | start_sweep_deg: start_sw, | |
| 356 | end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, | |
| 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 { | |
| 340 | width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, | |
| 341 | sub: cube_subdivisions(comp, node, time, expr), | |
| 342 | faces: 0b11_1111, | |
| 343 | }, | |
| 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); | |
| 380 | mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5; | |
| 381 | meshes.push(make_mesh_instance(world, shape, mat, None, &own)); | |
| 382 | } | |
| 383 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | |
| 384 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 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 | 387 | "Cube3D" => { |
| 363 | 388 | if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) { |
| ... | ... | @@ -372,7 +397,7 @@ fn collect_scene_inner( |
| 372 | 397 | .and_then(|s| comp.find_node(s)) |
| 373 | 398 | }); |
| 374 | 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 | 401 | apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr); |
| 377 | 402 | } |
| 378 | 403 | mat.fx.wireframe = wireframe; |
| ... | ... | @@ -410,7 +435,7 @@ fn collect_scene_inner( |
| 410 | 435 | .and_then(|s| comp.find_node(s)) |
| 411 | 436 | }); |
| 412 | 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 | 439 | apply_mtl_std(&mut mat, comp, node, "", time, expr); |
| 415 | 440 | } |
| 416 | 441 | meshes.push(make_mesh_instance(world, shape, mat, None, &own)); |
| ... | ... | @@ -437,6 +462,9 @@ fn collect_scene_inner( |
| 437 | 462 | slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, |
| 438 | 463 | }; |
| 439 | 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 | 469 | "MacroOperator" | "GroupOperator" => { |
| 442 | 470 | if let Some(out_id) = node.macro_output { |
| ... | ... | @@ -457,6 +485,9 @@ struct ResolvedMaterial { |
| 457 | 485 | fx: MaterialFx, |
| 458 | 486 | /// A bare texture operator used as a surface's material renders flat, ignoring lights. |
| 459 | 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 | } |
| 461 | 492 | |
| 462 | 493 | impl Default for ResolvedMaterial { |
| ... | ... | @@ -469,6 +500,7 @@ impl Default for ResolvedMaterial { |
| 469 | 500 | specular_exponent: 50.0, |
| 470 | 501 | fx: MaterialFx::default(), |
| 471 | 502 | unlit: false, |
| 503 | has_material_shader: false, | |
| 472 | 504 | } |
| 473 | 505 | } |
| 474 | 506 | } |
| ... | ... | @@ -705,6 +737,7 @@ fn resolve_material_inner( |
| 705 | 737 | specular_exponent: spec_exp, |
| 706 | 738 | fx, |
| 707 | 739 | unlit: false, |
| 740 | has_material_shader: true, | |
| 708 | 741 | } |
| 709 | 742 | } |
| 710 | 743 | _ => ResolvedMaterial { |
| ... | ... | @@ -1268,4 +1301,22 @@ mod tests { |
| 1268 | 1301 | assert!(inv.iter().all(|v| v.is_finite())); |
| 1269 | 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 | 25 | use crate::cache::CachedTexture; |
| 26 | 26 | use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; |
| 27 | 27 | use model::NodeId; |
| 28 | use shader::{MeshUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D}; | |
| 28 | use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER}; | |
| 29 | 29 | |
| 30 | 30 | pub type Mat4 = [f32; 16]; // Column-major 4x4 |
| 31 | 31 | |
| ... | ... | @@ -36,6 +36,11 @@ pub struct Scene3DRenderer { |
| 36 | 36 | pipelines: [[wgpu::RenderPipeline; 2]; 2], |
| 37 | 37 | sampler: wgpu::Sampler, |
| 38 | 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 | } |
| 40 | 45 | |
| 41 | 46 | /// Most meshes kept resident on the GPU across frames. |
| ... | ... | @@ -322,6 +327,8 @@ pub struct PointLight { |
| 322 | 327 | pub decay_type: f32, |
| 323 | 328 | /// Unused by the shader; `Renderer3D` still folds it into its cache key. |
| 324 | 329 | pub decay_rate: f32, |
| 330 | /// Shadow density in `0..=1` when the light casts shadows. | |
| 331 | pub shadow_density: Option<f32>, | |
| 325 | 332 | } |
| 326 | 333 | |
| 327 | 334 | #[derive(Clone, Copy, Debug)] |
| ... | ... | @@ -370,14 +377,41 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey { |
| 370 | 377 | (h.finish(), aspect_bits, wireframe) |
| 371 | 378 | } |
| 372 | 379 | |
| 380 | /// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. | |
| 381 | fn 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 | ||
| 373 | 405 | impl Scene3DRenderer { |
| 374 | 406 | pub fn new(device: &wgpu::Device) -> Self { |
| 375 | 407 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 376 | 408 | label: Some("scene3d-shader"), |
| 377 | 409 | source: wgpu::ShaderSource::Wgsl( |
| 378 | 410 | SHADER_3D |
| 411 | .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) | |
| 379 | 412 | .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) |
| 380 | 413 | .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) |
| 414 | .replace("SHADOW_MAP_SIZE", &SHADOW_MAP_SIZE.to_string()) | |
| 381 | 415 | .into(), |
| 382 | 416 | ), |
| 383 | 417 | }); |
| ... | ... | @@ -410,6 +444,26 @@ impl Scene3DRenderer { |
| 410 | 444 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 411 | 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 | 469 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| ... | ... | @@ -475,7 +529,83 @@ impl Scene3DRenderer { |
| 475 | 529 | mipmap_filter: wgpu::MipmapFilterMode::Linear, |
| 476 | 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 | } |
| 480 | 610 | |
| 481 | 611 | #[allow(clippy::too_many_arguments)] |
| ... | ... | @@ -491,6 +621,7 @@ impl Scene3DRenderer { |
| 491 | 621 | cam_pos: [f32; 3], |
| 492 | 622 | lights: SceneLights, |
| 493 | 623 | lighting_enabled: bool, |
| 624 | shadows_enabled: bool, | |
| 494 | 625 | meshes: &[DrawMesh], |
| 495 | 626 | ) { |
| 496 | 627 | let depth_tex = device.create_texture(&wgpu::TextureDescriptor { |
| ... | ... | @@ -509,6 +640,68 @@ impl Scene3DRenderer { |
| 509 | 640 | }); |
| 510 | 641 | let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); |
| 511 | 642 | |
| 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 | 705 | // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. |
| 513 | 706 | let mut order: Vec<(usize, f32)> = meshes |
| 514 | 707 | .iter() |
| ... | ... | @@ -528,6 +721,8 @@ impl Scene3DRenderer { |
| 528 | 721 | /// Skip the `[back-facing, front-facing]` pass. |
| 529 | 722 | cull: [bool; 2], |
| 530 | 723 | bg: wgpu::BindGroup, |
| 724 | /// `model` for the shadow pass; `None` for meshes that cast no shadow. | |
| 725 | caster: Option<wgpu::BindGroup>, | |
| 531 | 726 | vbuf: wgpu::Buffer, |
| 532 | 727 | ibuf: wgpu::Buffer, |
| 533 | 728 | idx_count: u32, |
| ... | ... | @@ -660,18 +855,88 @@ impl Scene3DRenderer { |
| 660 | 855 | wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, |
| 661 | 856 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, |
| 662 | 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 | 865 | draw_items.push(GpuDraw { |
| 666 | 866 | wireframe: fx.wireframe, |
| 667 | 867 | cull: [fx.cull_back, fx.cull_front], |
| 668 | 868 | bg, |
| 869 | caster: (!fx.wireframe && !shadow_lights.is_empty()) | |
| 870 | .then(|| uniform_bind_group("scene3d-caster", bytemuck::cast_slice(&m.world))), | |
| 669 | 871 | vbuf, |
| 670 | 872 | ibuf, |
| 671 | 873 | idx_count, |
| 672 | 874 | }); |
| 673 | 875 | } |
| 674 | 876 | |
| 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 | 940 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 676 | 941 | label: Some("scene3d-pass"), |
| 677 | 942 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| ... | ... | @@ -864,7 +1129,7 @@ mod tests { |
| 864 | 1129 | let frame = |meshes: &[DrawMesh]| { |
| 865 | 1130 | let mut enc = device.create_command_encoder(&Default::default()); |
| 866 | 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 | 1133 | queue.submit(Some(enc.finish())); |
| 869 | 1134 | renderer.meshes.lock().unwrap().entries.len() |
| 870 | 1135 | }; |
| ... | ... | @@ -897,4 +1162,35 @@ mod tests { |
| 897 | 1162 | assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]); |
| 898 | 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 | pub(super) const MAX_LIGHTS: usize = 8; |
| 7 | 7 | /// Directional lights get this many shader slots. |
| 8 | 8 | pub(super) const MAX_DIR_LIGHTS: usize = 4; |
| 9 | /// Point lights that can cast shadows in one render. | |
| 10 | pub(super) const MAX_SHADOW_LIGHTS: usize = 4; | |
| 11 | /// Edge length in texels of each cube-map face. | |
| 12 | pub(super) const SHADOW_MAP_SIZE: u32 = 1024; | |
| 9 | 13 | |
| 10 | 14 | #[repr(C)] |
| 11 | 15 | #[derive(Clone, Copy, Debug, Pod, Zeroable)] |
| ... | ... | @@ -56,7 +60,43 @@ pub(super) struct MeshUniform { |
| 56 | 60 | pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], |
| 57 | 61 | } |
| 58 | 62 | |
| 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)] | |
| 65 | pub(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. | |
| 74 | pub(super) const SHADOW_SHADER: &str = r#" | |
| 75 | struct Caster { model: mat4x4<f32> }; | |
| 76 | struct 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 | ||
| 81 | struct VsOut { | |
| 82 | @builtin(position) clip: vec4<f32>, | |
| 83 | @location(0) world_pos: vec3<f32>, | |
| 84 | }; | |
| 85 | ||
| 86 | @vertex | |
| 87 | fn 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 | |
| 93 | fn 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. | |
| 60 | 100 | pub(super) const SHADER_3D: &str = r#" |
| 61 | 101 | struct MeshUniform { |
| 62 | 102 | mvp: mat4x4<f32>, |
| ... | ... | @@ -80,11 +120,18 @@ struct MeshUniform { |
| 80 | 120 | spot_col: array<vec4<f32>, MAX_LIGHTS>, |
| 81 | 121 | }; |
| 82 | 122 | |
| 123 | struct ShadowUniform { | |
| 124 | face_vp: array<mat4x4<f32>, 6 * MAX_SHADOW_LIGHTS>, | |
| 125 | point: array<vec4<f32>, MAX_LIGHTS>, | |
| 126 | }; | |
| 127 | ||
| 83 | 128 | override BACK_PASS: bool = false; |
| 84 | 129 | |
| 85 | 130 | @group(0) @binding(0) var<uniform> u: MeshUniform; |
| 86 | 131 | @group(0) @binding(1) var mat_tex: texture_2d<f32>; |
| 87 | 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>; | |
| 88 | 135 | |
| 89 | 136 | struct VsIn { |
| 90 | 137 | @location(0) pos: vec3<f32>, |
| ... | ... | @@ -138,6 +185,41 @@ fn light_attenuation(dist: f32, decay_type: f32) -> f32 { |
| 138 | 185 | return 1.0; |
| 139 | 186 | } |
| 140 | 187 | |
| 188 | /// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. | |
| 189 | fn 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 | ||
| 141 | 223 | fn eval_light_contrib( |
| 142 | 224 | n: vec3<f32>, |
| 143 | 225 | v: vec3<f32>, |
| ... | ... | @@ -147,12 +229,14 @@ fn eval_light_contrib( |
| 147 | 229 | spec_rgb: vec3<f32>, |
| 148 | 230 | spec_int: f32, |
| 149 | 231 | shininess: f32, |
| 232 | diffuse_vis: f32, | |
| 233 | spec_vis: f32, | |
| 150 | 234 | ) -> vec3<f32> { |
| 151 | 235 | let ndotl = max(dot(n, l), 0.0); |
| 152 | 236 | if (ndotl <= 0.0) { |
| 153 | 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 | 240 | if (spec_int > 1e-4) { |
| 157 | 241 | let h = normalize(l + v); |
| 158 | 242 | let model = i32(u.mat_fx.w + 0.5); |
| ... | ... | @@ -167,7 +251,7 @@ fn eval_light_contrib( |
| 167 | 251 | } else { |
| 168 | 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 | 256 | return out; |
| 173 | 257 | } |
| ... | ... | @@ -295,7 +379,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { |
| 295 | 379 | for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { |
| 296 | 380 | if (i >= n_dir) { break; } |
| 297 | 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 | } |
| 300 | 384 | |
| 301 | 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 | 388 | let to_l = u.point_pos[i].xyz - in.world_pos; |
| 305 | 389 | let dist = max(length(to_l), 1e-4); |
| 306 | 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 | } |
| 309 | 398 | |
| 310 | 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 | 409 | let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); |
| 321 | 410 | if (cone > 0.0) { |
| 322 | 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 | } |
| 326 | 415 |
crates/engine/src/text_engine.rs+40| ... | ... | @@ -76,10 +76,25 @@ pub fn parse_style(style: &str) -> (u16, bool) { |
| 76 | 76 | (weight, s.contains("italic") || s.contains("oblique")) |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | fn 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 | ||
| 79 | 93 | fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> { |
| 80 | 94 | let (weight, italic) = parse_style(style); |
| 81 | 95 | let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase(); |
| 82 | 96 | let id = std::iter::once(family) |
| 97 | .chain(metric_alias(family)) | |
| 83 | 98 | .chain(FALLBACK_FAMILIES) |
| 84 | 99 | .find_map(|name| pick(db, name, &wanted, weight, italic)) |
| 85 | 100 | .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) |
| ... | ... | @@ -445,4 +460,29 @@ mod tests { |
| 445 | 460 | assert!((right[2] - 480).abs() <= 6, "{right:?}"); |
| 446 | 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 | } |