SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Section Analysis: the cap is marked by true depth, so far edges no longer take a cap band (#6328) (#6332)
CamWightc6d361347f0a
diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rsindex 91f76f8c4d..7fc7d1b391 100644--- a/crates/gpu/src/view.rs+++ b/crates/gpu/src/view.rs@@ -1199,6 +1199,20 @@ impl Batches {}}+/// The section's pipelines (see `Renderer::tri_cut`).+struct Cut {+ /// Draws the faces and marks the stencil by their true depth: 1 where a back face (the cap)+ /// is the visible surface. Unpushed: `FACE_BIAS`'s slope part would let a front face win a+ /// band along its edge with a back face seen through the cut, and the cap would skip it (#6328).+ mark: wgpu::RenderPipeline,+ /// The faces' depth again, pushed back by `FACE_BIAS` as unsectioned faces are (after+ /// `Renderer::section_reset`), so their edges draw over them (#1434). No colour, no stencil.+ push: wgpu::RenderPipeline,+ /// The cap again, only where marked, at the section plane's depth: depth only, as the mark+ /// drew the cap's colour (#6728).+ cap: wgpu::RenderPipeline,+}+/// The viewport's pipelines and the scenes uploaded to one device, for one kind of target.pub struct Renderer {/// What the last frame drew ([`Renderer::stats`]).@@ -1212,24 +1226,24 @@ pub struct Renderer {/// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation,/// colours per vertex, indexed).tri_planned: wgpu::RenderPipeline,- tri_cut_planned: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline, wgpu::RenderPipeline)>,+ tri_cut_planned: Option<Cut>,/// `tri` and `tri_cut` for instanced meshes (shared triangles, a move and colour per/// placement).tri_instanced: wgpu::RenderPipeline,- tri_cut_instanced: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline, wgpu::RenderPipeline)>,+ tri_cut_instanced: Option<Cut>,/// `tri_instanced` and `tri_cut_instanced` for flat triangles.tri_instanced_flat: wgpu::RenderPipeline,/// `glass_far`, `glass_near` and `trans` for instanced meshes, smooth and flat.glass_far_instanced: (wgpu::RenderPipeline, wgpu::RenderPipeline),glass_near_instanced: (wgpu::RenderPipeline, wgpu::RenderPipeline),trans_instanced: (wgpu::RenderPipeline, wgpu::RenderPipeline),- tri_cut_instanced_flat: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline, wgpu::RenderPipeline)>,+ tri_cut_instanced_flat: Option<Cut>,/// The tessellation compute pipeline, where the device runs compute shaders.tess: Option<crate::TessGpu>,- /// While a section is shown (when the depth buffer has a stencil): `tri` marking where the- /// cap shows, the back faces marking it again where they lie within the faces' push of what- /// is in front of them, then the cap again at the section plane's depth, so it hides the inside.- tri_cut: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline, wgpu::RenderPipeline)>,+ /// While a section is shown (when the depth buffer has a stencil), in place of `tri`: the+ /// faces marking where the cap shows, their depth pushed back, then the cap again at the+ /// section plane's depth, so it hides the inside ([`Cut`]).+ tri_cut: Option<Cut>,/// Highlight triangles over the model (depth test ≤, no depth write).tri_hl: wgpu::RenderPipeline,/// Whole highlighted bodies, redrawn from the model's planned chunks in the hover and the@@ -1313,16 +1327,19 @@ pub struct Renderer {/// Reversed depth drawn into the window's pass: egui clears its depth to 1, which is the near/// plane then, so the viewport first sets its rectangle to the far plane (0).depth_reset: Option<wgpu::RenderPipeline>,+ /// The scene target's depth back to the far plane between the section's marking and push+ /// passes ([`Cut`]); stencil and colour untouched.+ section_reset: Option<wgpu::RenderPipeline>,}-/// A triangle over the whole viewport at depth 0 (the far plane of reversed depth), writing no-/// colour: [`Renderer::depth_reset`].+/// A triangle over the whole viewport at the far plane's depth (`FAR`), writing no colour:+/// [`depth_reset_pipeline`].const DEPTH_RESET_SHADER: &str = r#"@vertexfn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {let x = f32((i << 1u) & 2u);let y = f32(i & 2u);- return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);+ return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, FAR, 1.0);}@fragmentfn fs() -> @location(0) vec4<f32> {@@ -1823,7 +1840,7 @@ impl Renderer {// While a section is shown: the stencil marking and the cap (see `Renderer::tri_cut`).let cut = |source: TriSource| {t.depth.filter(|f| f.has_stencil_aspect()).map(|format| {- // The visible surface marks the stencil: 1 where it is a back face (the cap).+ // The visible surface, by its true depth, marks the stencil: 1 where it is a back face (the cap).use wgpu::StencilOperation::{Keep, Replace, Zero};let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op };let mark = wgpu::DepthStencilState {@@ -1831,18 +1848,7 @@ impl Renderer {depth_write_enabled: Some(true),depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff },- bias: depth_bias(reversed, FACE_BIAS),- };- // The back faces again, pulled as far forward as the faces are pushed back: where- // one meets a front face (a pocket's wall and its floor, a fillet and the face it- // runs into) the push decides which is nearer along their shared edge, and a front- // face winning there left the cap out, so edges behind the cut showed through it.- let mark_back = wgpu::DepthStencilState {- format,- depth_write_enabled: Some(false),- depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::LessEqual)),- stencil: wgpu::StencilState { front: face(Keep), back: face(Replace), read_mask: 0xff, write_mask: 0xff },- bias: depth_bias(reversed, CAP_MARK_BIAS),+ bias: Default::default(),};// Then the cap's back faces again, only there, at the section plane's depth.let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) };@@ -1853,15 +1859,15 @@ impl Renderer {stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 },bias: Default::default(),};- (- solid("sc_tris_mark", "fs_solid", None, Some(mark), source),- solid("sc_tris_mark_back", "fs_solid", Some(wgpu::Face::Front), Some(mark_back), source),+ Cut {+ mark: solid("sc_tris_mark", "fs_solid", None, Some(mark), source),+ push: solid_writes("sc_tris_push", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), source, false),// Depth only: every back face behind a marked pixel draws here, so writing// colour let the last one drawn paint the cut, other bodies behind it// included (their colours and outlines showed through it, #6328). The- // marking passes already drew the nearest back face's colour.- solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap), source, false),- )+ // marking pass already drew the nearest back face's colour.+ cap: solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap), source, false),+ }})};let access_bind = access_texture(device, None, &access_bgl, 1, &[]);@@ -1928,42 +1934,11 @@ impl Renderer {// Into the cached picture's own texture: no depth, one sample.let ss_filter = blit("fs", 1, None);let oit = oit::Pipelines::new(device, &module, &layout, t.format, t.depth, t.samples);- let depth_reset = window.depth.filter(|_| window.reversed_depth()).map(|format| {- let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("sc_depth_reset"),- source: wgpu::ShaderSource::Wgsl(DEPTH_RESET_SHADER.into()),- });- let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("sc_depth_reset"),- bind_group_layouts: &[],- immediate_size: 0,- });- device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("sc_depth_reset"),- layout: Some(&layout),- vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },- primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },- depth_stencil: Some(wgpu::DepthStencilState {- format,- depth_write_enabled: Some(true),- depth_compare: Some(wgpu::CompareFunction::Always),- stencil: Default::default(),- bias: Default::default(),- }),- multisample: wgpu::MultisampleState { count: window.samples.max(1), mask: !0, alpha_to_coverage_enabled: false },- fragment: Some(wgpu::FragmentState {- module: &module,- entry_point: Some("fs"),- targets: &[Some(wgpu::ColorTargetState { format: window.format, blend: None, write_mask: wgpu::ColorWrites::empty() })],- compilation_options: Default::default(),- }),- multiview_mask: None,- cache: None,- })- });+ let depth_reset = window.reversed_depth().then(|| depth_reset_pipeline(device, window)).flatten();Renderer {ao,depth_reset,+ section_reset: t.depth.filter(|f| f.has_stencil_aspect()).and_then(|_| depth_reset_pipeline(device, t)),target: t,window,max_texture: device.limits().max_texture_dimension_2d,@@ -2073,14 +2048,45 @@ pub const FACE_STEPS: i32 = 8;/// 3.5 px) may lose its outer edge on one side where it lies on a steep face. The section cap,/// which writes its own depth, adds the same in the shader.pub const FACE_SLOPE: f32 = 1.0;-/// The section's second marking of back faces (`Renderer::tri_cut`): pulled toward the eye as far-/// as [`FACE_BIAS`] pushes the faces back, so a back face that meets a front face along an edge-/// still marks the cap there.-const CAP_MARK_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: -FACE_STEPS, slope_scale: -FACE_SLOPE, clamp: 0.0 };/// The removed material of a preview, drawn translucent: behind the faces it shares with the new/// shape, so twice [`FACE_BIAS`].const GHOST_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: 2 * FACE_STEPS, slope_scale: 2.0 * FACE_SLOPE, clamp: 0.0 };+/// A pipeline that sets the depth of the viewport in a pass of `t`'s kind back to the far plane,+/// leaving colour and stencil as they are. None without a depth buffer.+fn depth_reset_pipeline(device: &wgpu::Device, t: GpuTarget) -> Option<wgpu::RenderPipeline> {+ let format = t.depth?;+ let far = if t.reversed_depth() { "0.0" } else { "1.0" };+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("sc_depth_reset"),+ source: wgpu::ShaderSource::Wgsl(DEPTH_RESET_SHADER.replace("FAR", far).into()),+ });+ let layout =+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_depth_reset"), bind_group_layouts: &[], immediate_size: 0 });+ Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("sc_depth_reset"),+ layout: Some(&layout),+ vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },+ primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },+ depth_stencil: Some(wgpu::DepthStencilState {+ format,+ depth_write_enabled: Some(true),+ depth_compare: Some(wgpu::CompareFunction::Always),+ stencil: Default::default(),+ bias: Default::default(),+ }),+ multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false },+ fragment: Some(wgpu::FragmentState {+ module: &module,+ entry_point: Some("fs"),+ targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: None, write_mask: wgpu::ColorWrites::empty() })],+ compilation_options: Default::default(),+ }),+ multiview_mask: None,+ cache: None,+ }))+}+fn upload(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize) -> Option<Batch> {upload_with(device, label, bytes, stride, wgpu::BufferUsages::VERTEX)}@@ -2495,26 +2501,22 @@ impl Renderer {res.tri_cut_planned.as_ref(),res.tri_cut_instanced.as_ref(),res.tri_cut_instanced_flat.as_ref(),+ res.section_reset.as_ref(),) {- (- Some((mark, back, cap)),- Some((mark_planned, back_planned, cap_planned)),- Some((mark_instanced, back_instanced, cap_instanced)),- Some((mark_flat, back_flat, cap_flat)),- ) => {+ (Some(cut), Some(cut_planned), Some(cut_instanced), Some(cut_flat), Some(reset)) => {+ let all = |pass: &mut wgpu::RenderPass<'static>, pick: fn(&Cut) -> &wgpu::RenderPipeline| {+ tris(pass, pick(cut), &m.tris);+ tris(pass, pick(cut), &pv.tris);+ planned(pass, pick(cut_planned));+ instanced(pass, pick(cut_instanced), pick(cut_flat));+ };pass.set_stencil_reference(1);- tris(pass, mark, &m.tris);- tris(pass, mark, &pv.tris);- planned(pass, mark_planned);- instanced(pass, mark_instanced, mark_flat);- tris(pass, back, &m.tris);- tris(pass, back, &pv.tris);- planned(pass, back_planned);- instanced(pass, back_instanced, back_flat);- tris(pass, cap, &m.tris);- tris(pass, cap, &pv.tris);- planned(pass, cap_planned);- instanced(pass, cap_instanced, cap_flat);+ all(pass, |c| &c.mark);+ pass.set_pipeline(reset);+ pass.draw(0..3, 0..1);+ tally.call();+ all(pass, |c| &c.push);+ all(pass, |c| &c.cap);}_ => {tris(pass, &res.tri, &m.tris);diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rsindex a9be41344e..04744bf52d 100644--- a/crates/gpu/tests/depth.rs+++ b/crates/gpu/tests/depth.rs@@ -1,6 +1,7 @@//! Depth in headless pictures, drawn with the viewport's pipelines (#1434, #1739): an edge behind//! a face stays hidden however large the design and however far the camera, and whatever lies on-//! a face (its edges, a thin label) draws over it at any angle. Each check runs with the depth the+//! a face (its edges, a thin label) draws over it at any angle, with a section shown or not, and a+//! section's cap hides what lies behind it (#6328). Each check runs with the depth the//! device draws with (a 32-bit float buffer, reversed, where it has one) and with the 24-bit//! fallback. Skipped, with the reason printed, without a GPU adapter (`SOLIDCRAFT_REQUIRE_GPU=1`//! makes that a failure).@@ -145,8 +146,10 @@ fn sheet(tilt: f64) -> Mesh {}/// A front view of `mesh` with `lines`, as part of a design of `radius`, 40 mm high on 200 px.-fn front(mesh: Mesh, lines: Vec<SceneLine>, radius: f64, fov: f64) -> (Scene, Camera) {- let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, ..Default::default() };+/// `section`: with a section that cuts nothing shown, so the section's own passes draw the faces.+fn front(mesh: Mesh, lines: Vec<SceneLine>, radius: f64, fov: f64, section: bool) -> (Scene, Camera) {+ let clip = section.then_some((Vec3::X, 1e3));+ let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, clip, ..Default::default() };let mut cam = Camera { distance: if fov > 0.0 { 25.0 / (fov * 0.5).tan() } else { 62.5 }, fov, ..Default::default() };cam.set_view(StandardView::Front);(scene, cam)@@ -161,7 +164,8 @@ fn red_pixels(c: &Capturer, scene: &Scene, cam: &Camera) -> usize {}/// An edge lying on a face draws its whole width over it, on a face seen square and on one turned-/// to 80°, in orthographic and perspective, in a small design and a large one.+/// to 80°, in orthographic and perspective, in a small design and a large one, with a section shown+/// or not (#6328: the section's marking pass draws the faces unpushed, then pushes them).#[test]fn an_edge_on_a_face_draws_whole_at_any_angle() {for (mode, c) in capturers() {@@ -170,12 +174,15 @@ fn an_edge_on_a_face_draws_whole_at_any_angle() {// Across the sheet, at z = 5: y = 5·tan(tilt).let (a, b) = (Vec3::new(-12.0, 5.0 * t, 5.0), Vec3::new(12.0, 5.0 * t, 5.0));for radius in [30.0, 17_000.0] {- for fov in [0.0, 0.6] {- let (on, cam) = front(sheet(tilt.to_radians()), vec![red_line(a, b, false)], radius, fov);- let (top, _) = front(sheet(tilt.to_radians()), vec![red_line(a, b, true)], radius, fov);+ for (fov, section) in [0.0, 0.6].into_iter().flat_map(|fov| [(fov, false), (fov, true)]) {+ let (on, cam) = front(sheet(tilt.to_radians()), vec![red_line(a, b, false)], radius, fov, section);+ let (top, _) = front(sheet(tilt.to_radians()), vec![red_line(a, b, true)], radius, fov, section);let (shown, all) = (red_pixels(c, &on, &cam), red_pixels(c, &top, &cam));assert!(all > 50, "{mode}: the line itself ({all} px)");- assert!(shown * 10 >= all * 9, "{mode} depth, tilt {tilt}°, radius {radius}, fov {fov}: {shown} of {all} px drawn");+ assert!(+ shown * 10 >= all * 9,+ "{mode} depth, tilt {tilt}°, radius {radius}, fov {fov}, section {section}: {shown} of {all} px drawn"+ );}}}@@ -202,8 +209,8 @@ fn a_selected_edge_on_a_grazing_face_draws_whole() {let (a, b) = (Vec3::new(-12.0, 5.0 * t, 5.0), Vec3::new(12.0, 5.0 * t, 5.0));for radius in [30.0, 17_000.0] {for fov in [0.0, 0.6] {- let (plain, cam) = front(sheet(tr), Vec::new(), radius, fov);- let (top, _) = front(sheet(tr), reference(a, b), radius, fov);+ let (plain, cam) = front(sheet(tr), Vec::new(), radius, fov, false);+ let (top, _) = front(sheet(tr), reference(a, b), radius, fov, false);let shown = pixels(&c.rgba_highlighted(&plain, Some(highlight(a, b, n)), &cam, 200, 200).unwrap()).filter(|p| red(*p)).count();let all = red_pixels(c, &top, &cam);assert!(all > 100, "{mode}: the band itself ({all} px)");@@ -214,7 +221,7 @@ fn a_selected_edge_on_a_grazing_face_draws_whole() {for radius in [30.0, 17_000.0] {for fov in [0.0, 0.6] {let (a, b) = (Vec3::new(-12.0, 5.0, 5.0), Vec3::new(12.0, 5.0, 5.0));- let (plain, cam) = front(sheet(0.0), Vec::new(), radius, fov);+ let (plain, cam) = front(sheet(0.0), Vec::new(), radius, fov, false);let img = c.rgba_highlighted(&plain, Some(highlight(a, b, Vec3::new(0.0, -1.0, 0.0))), &cam, 200, 200).unwrap();let n = pixels(&img).filter(|p| red(*p)).count();assert_eq!(n, 0, "{mode} depth, radius {radius}, fov {fov}: the band behind shows in {n} px");@@ -223,18 +230,19 @@ fn a_selected_edge_on_a_grazing_face_draws_whole() {}}-/// An edge 0.5 mm behind a face seen square is hidden, however large the design: lines were pulled-/// toward the eye by a share of the depth range, about 27 mm in a design 34 m across.+/// An edge 0.5 mm behind a face seen square is hidden, however large the design, with a section+/// shown or not: lines were pulled toward the eye by a share of the depth range, about 27 mm in a+/// design 34 m across.#[test]fn an_edge_just_behind_a_face_stays_hidden_on_a_large_design() {for (mode, c) in capturers() {for radius in [30.0, 17_000.0] {- for fov in [0.0, 0.6] {+ for (fov, section) in [0.0, 0.6].into_iter().flat_map(|fov| [(fov, false), (fov, true)]) {// The sheet is at y = 0; the camera looks along +y, so behind is +y.let (a, b) = (Vec3::new(-12.0, 0.5, 5.0), Vec3::new(12.0, 0.5, 5.0));- let (scene, cam) = front(sheet(0.0), vec![red_line(a, b, false)], radius, fov);+ let (scene, cam) = front(sheet(0.0), vec![red_line(a, b, false)], radius, fov, section);let n = red_pixels(c, &scene, &cam);- assert_eq!(n, 0, "{mode} depth, radius {radius}, fov {fov}: the edge behind shows in {n} px");+ assert_eq!(n, 0, "{mode} depth, radius {radius}, fov {fov}, section {section}: the edge behind shows in {n} px");}}}@@ -361,3 +369,81 @@ fn edges_of_a_cut_hub_stay_under_the_cap_as_the_view_turns() {}}}++/// #6328, bherbruck's block: 40 × 40 × 30 mm with a hole and a pocket, cut on XZ at y = -16, 2 mm in+/// front of the pocket and 12 mm in front of the hole, seen from the home view. The cap hides them:+/// it matches the plain block's cap. With the faces' slope push on the section's marking pass+/// (#1768), the pocket's and the hole's edges showed through it as dashed lines in perspective, 84+/// of the 18,328 cap pixels here (both depths); before #1768 and with the fix, none. Away from the+/// cut the plain block's picture is a box of just its kept part's: the push also let back faces win+/// a band along the far edges, which the cap hatched (58 px here in orthographic, 534 in+/// perspective; now 0 and 1). The limits leave room for an edge's exact tie, which rounding+/// settles per sample (one pixel on WARP).+#[test]+fn a_cut_hides_the_edges_behind_it() {+ let block = [+ ("sketch.create", json!({"plane": "XY", "name": "Base"})),+ ("sketch.line", json!({"points": [[-20, -20], [20, -20], [20, 20], [-20, 20]], "closed": true})),+ ("sketch.finish", json!({})),+ ("solid.extrude", json!({"distance": 30, "body_name": "Block"})),+ ];+ let behind = [+ ("sketch.create", json!({"plane": "XY", "name": "Hole"})),+ ("sketch.circle.center", json!({"center": [10, 0], "diameter": 8})),+ ("sketch.finish", json!({})),+ ("solid.extrude", json!({"distance": 30, "operation": "cut"})),+ ("sketch.create", json!({"plane": "XY", "name": "Pocket", "offset": 30})),+ ("sketch.line", json!({"points": [[-14, -14], [2, -14], [2, 2], [-14, 2]], "closed": true})),+ ("sketch.finish", json!({})),+ ("solid.extrude", json!({"distance": 18, "direction": "negative", "operation": "cut"})),+ ];+ let cut = ("inspect.section", json!({"plane": "XZ", "at": -16, "flip": true}));+ let plain = session(&[&block[..], std::slice::from_ref(&cut)].concat());+ let cut_through = session(&[&block[..], &behind[..], &[cut]].concat());+ let (w, h) = (400, 300);+ for (mode, c) in capturers() {+ for fov in [0.0, 0.6] {+ let mut cam = view::home_camera(&plain);+ cam.fov = fov;+ let radius = view::scene(&plain, &cam).radius;+ // The cap on screen: the cut's rectangle, its outline left out (2 px in).+ let corner = |x: f64, z: f64| cam.to_screen(Vec3::new(x, -16.0, z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y));+ let cap: Vec<(f64, f64)> = [(-20.0, 0.0), (20.0, 0.0), (20.0, 30.0), (-20.0, 30.0)].iter().filter_map(|(x, z)| corner(*x, *z)).collect();+ assert_eq!(cap.len(), 4, "fov {fov}: the cut is on screen");+ // Which way the corners run on screen, so a point's distance inside each edge is positive.+ let turn = (0..4).map(|i| cap[i].0 * cap[(i + 1) % 4].1 - cap[(i + 1) % 4].0 * cap[i].1).sum::<f64>().signum();+ let inside_by = |x: f64, y: f64, by: f64| {+ let side = |i: usize| {+ let ((ax, ay), (bx, by)) = (cap[i], cap[(i + 1) % 4]);+ ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / (bx - ax).hypot(by - ay)+ };+ (0..4).all(|i| side(i) * turn >= by)+ };+ let inside = |x: f64, y: f64| inside_by(x, y, 2.0);+ // Without the ground grid, whose extent follows the design.+ let shot = |s: &Session| c.rgba(&Scene { grid: Vec::new(), ..view::scene(s, &cam) }, &cam, w, h).unwrap();+ let (a, b) = (shot(&plain), shot(&cut_through));+ let (mut shown, mut all) = (0, 0);+ for (i, (p, q)) in pixels(&a).zip(pixels(&b)).enumerate() {+ if inside((i % w as usize) as f64 + 0.5, (i / w as usize) as f64 + 0.5) {+ all += 1;+ shown += usize::from(p.iter().zip(q).any(|(u, v)| u.abs_diff(v) > 24));+ }+ }+ assert!(all > 5000, "{mode}, fov {fov}: the cap ({all} px)");+ assert!(shown <= 8, "{mode} depth, fov {fov}: {shown} of {all} cap px show what lies behind the cut");+ // Away from the cut, the picture is a box of just the kept part's (no cap along the far+ // edges either).+ let kept = shot(&session(&[("solid.box", json!({"length": 40, "width": 36, "height": 30, "corner": [-20, -16, 0]}))]));+ let fringe = pixels(&a)+ .zip(pixels(&kept))+ .enumerate()+ .filter(|(i, (p, q))| {+ !inside_by((i % w as usize) as f64 + 0.5, (i / w as usize) as f64 + 0.5, -8.0)+ && p.iter().zip(q).any(|(u, v)| u.abs_diff(*v) > 24)+ })+ .count();+ assert!(fringe <= 8, "{mode} depth, fov {fov}: {fringe} px away from the cut differ from the kept part alone");+ }+ }+}