Skip to main content

strata_render/
rasterizer3d.rs

1//! 3D Software Rasterizer & 2D/3D Viewport Compositing Bridge.
2
3use crate::geometry3d::{
4    generate_box, generate_custom, generate_custom_textured, generate_cylinder, generate_plane,
5    generate_sphere,
6};
7use crate::math3d::{Mat4, Vec3, Vec4};
8use crate::rasterizer::FrameBuffer;
9use crate::scene3d::{
10    Background3D, Camera3D, Geometry3D, Light3D, Material3D, Scene3D, TexturedMaterial3D,
11};
12use crate::texture3d::{
13    sample_bilinear_clamped, sample_texture, AddressMode, FilterMode, TextureStore,
14};
15use strata_layout::Rect;
16use strata_style::types::Color;
17
18/// Renders a Scene3D directly into a FrameBuffer viewport region with Z-buffering,
19/// automatically resolving any [`TextureStore`] attached to `scene`.
20pub fn render_scene_3d(
21    frame_buffer: &mut FrameBuffer,
22    viewport: Rect,
23    scene: &Scene3D,
24    clip: Option<Rect>,
25) {
26    render_scene_3d_with_textures(frame_buffer, viewport, scene, clip, scene.textures_deref());
27}
28
29/// Renders a Scene3D, resolving textured materials against `textures` (or `scene.textures_deref()`
30/// when `textures` is `None`), then draws the scene overlay pass on top.
31///
32/// When neither `textures` nor `scene.textures()` is populated, textured meshes fall back to
33/// their tint colour so a scene that references a missing texture is still
34/// visible instead of silently disappearing.
35///
36/// Overlay text uses the rasterizer installed with
37/// [`crate::scene3d::register_overlay_text_rasterizer`]; without one, labels
38/// are skipped and the geometric overlay still draws.
39pub fn render_scene_3d_with_textures(
40    frame_buffer: &mut FrameBuffer,
41    viewport: Rect,
42    scene: &Scene3D,
43    clip: Option<Rect>,
44    textures: Option<&TextureStore>,
45) {
46    let textures = textures.or_else(|| scene.textures_deref());
47    if viewport.width <= 1.0 || viewport.height <= 1.0 {
48        return;
49    }
50
51    // Background fill happens before any depth-tested geometry. Pixels are
52    // written directly, so a translucent clear colour still replaces the
53    // previous frame instead of being alpha-blended over it.
54    match scene.background() {
55        Background3D::Transparent => {}
56        Background3D::Solid(color) => fill_viewport(frame_buffer, viewport, |_| color),
57        Background3D::VerticalGradient { .. } => {
58            let height = viewport.height.max(1.0);
59            let background = scene.background();
60            fill_viewport(frame_buffer, viewport, |row| {
61                background
62                    .color_at(row as f32 / height)
63                    .unwrap_or(Color::TRANSPARENT)
64            });
65        }
66    }
67
68    let aspect = viewport.width / viewport.height;
69
70    // 1. Compute Projection and View Matrices. The near plane is needed by the
71    // clipping stage, and the combined matrix is only used by the overlay.
72    let (proj_mat, view_mat, near_plane) = match &scene.camera {
73        Camera3D::Perspective {
74            fov_horizontal_deg,
75            near,
76            far,
77            position,
78            target,
79        } => {
80            // The scene camera declares a horizontal field of view; the
81            // projection matrix takes a vertical one.
82            let fov_x = fov_horizontal_deg.to_radians();
83            let fov_y = 2.0 * ((fov_x * 0.5).tan() / aspect).atan();
84            let p = Mat4::perspective(fov_y, aspect, *near, *far);
85            let eye = Vec3::new(position[0], position[1], position[2]);
86            let tgt = Vec3::new(target[0], target[1], target[2]);
87            let v = Mat4::look_at(eye, tgt, camera_up_hint(scene, eye, tgt));
88            (p, v, *near)
89        }
90        Camera3D::Orthographic {
91            left,
92            right,
93            top,
94            bottom,
95            near,
96            far,
97            position,
98            target,
99        } => {
100            let p = Mat4::orthographic(*left, *right, *bottom, *top, *near, *far);
101            let eye = Vec3::new(position[0], position[1], position[2]);
102            let tgt = Vec3::new(target[0], target[1], target[2]);
103            let v = Mat4::look_at(eye, tgt, camera_up_hint(scene, eye, tgt));
104            (p, v, *near)
105        }
106    };
107
108    let projection = proj_mat;
109
110    // 2. Collect Scene Lights
111    let mut ambient_intensity = 0.2f32;
112    let mut ambient_color = Color::WHITE;
113    let mut dir_light_dir = Vec3::new(0.5, 1.0, 0.7).normalize();
114    let mut dir_light_color = Color::WHITE;
115    let mut dir_light_intensity = 0.8f32;
116
117    for light in &scene.lights {
118        match light {
119            Light3D::Ambient { color, intensity } => {
120                ambient_color = *color;
121                ambient_intensity = *intensity;
122            }
123            Light3D::Directional {
124                position,
125                color,
126                intensity,
127                ..
128            } => {
129                dir_light_dir = Vec3::new(position[0], position[1], position[2]).normalize();
130                dir_light_color = *color;
131                dir_light_intensity = *intensity;
132            }
133            Light3D::Point { .. } => {}
134        }
135    }
136
137    // 3. Viewport Z-Buffer
138    let vp_w = viewport.width.ceil() as usize;
139    let vp_h = viewport.height.ceil() as usize;
140    let background_filled = !matches!(scene.background(), Background3D::Transparent);
141    let mut depth = RealDepthBuffer {
142        rows: vec![1.0f32; vp_w * vp_h],
143    };
144
145    // 4. Prepare draws and project every visible triangle. Geometry is
146    // collected once, then rasterized in screen-space rows: projection is
147    // cheap, and the pixel loop is what dominates a full-screen terrain frame.
148    let mut prepared: Vec<PreparedDraw> = Vec::new();
149    let mut triangles: Vec<ScreenTriangle> = Vec::new();
150
151    for mesh in &scene.meshes {
152        let buffers = match &mesh.geometry {
153            Geometry3D::Box {
154                width,
155                height,
156                depth,
157            } => generate_box(*width, *height, *depth),
158            Geometry3D::Sphere {
159                radius,
160                width_segments,
161                height_segments,
162            } => generate_sphere(*radius, *width_segments, *height_segments),
163            Geometry3D::Plane { width, height } => generate_plane(*width, *height, 1, 1),
164            Geometry3D::Cylinder {
165                radius_top,
166                radius_bottom,
167                height,
168                radial_segments,
169            } => generate_cylinder(*radius_top, *radius_bottom, *height, *radial_segments),
170            Geometry3D::Custom { vertices, indices } => generate_custom(vertices, indices),
171            Geometry3D::CustomTextured { vertices, indices } => {
172                generate_custom_textured(vertices, indices)
173            }
174        };
175
176        let t = Vec3::new(
177            mesh.transform.position[0],
178            mesh.transform.position[1],
179            mesh.transform.position[2],
180        );
181        let r = Vec3::new(
182            mesh.transform.rotation[0],
183            mesh.transform.rotation[1],
184            mesh.transform.rotation[2],
185        );
186        let scale = Vec3::new(
187            mesh.transform.scale[0],
188            mesh.transform.scale[1],
189            mesh.transform.scale[2],
190        );
191
192        let model_mat = Mat4::from_trs(t, r, scale);
193        let normal_mat = model_mat.inverse().unwrap_or(Mat4::IDENTITY).transpose();
194        let view_model = view_mat.multiply(&model_mat);
195
196        let base_color = match &mesh.material {
197            Material3D::Standard { color, .. } => *color,
198            Material3D::Physical { color, .. } => *color,
199            Material3D::Basic { color } => *color,
200            Material3D::Shader { .. } => Color::rgba(180, 180, 220, 255),
201            Material3D::Textured(material) => material.tint,
202            Material3D::TexturedBatch(_) => Color::rgba(255, 255, 255, 255),
203        };
204
205        // One draw for an untextured or single-texture mesh, one per index
206        // range for a batch.
207        struct DrawRange<'a> {
208            material: Option<&'a TexturedMaterial3D>,
209            start: usize,
210            end: usize,
211            color: Color,
212        }
213        let mut draw_ranges: Vec<DrawRange> = Vec::new();
214        match &mesh.material {
215            Material3D::TexturedBatch(batch) => {
216                for draw in &batch.draws {
217                    let start = draw.index_start as usize;
218                    let end = (start + draw.index_count as usize).min(buffers.indices.len());
219                    draw_ranges.push(DrawRange {
220                        material: Some(&draw.material),
221                        start,
222                        end,
223                        color: draw.material.tint,
224                    });
225                }
226            }
227            Material3D::Textured(material) => draw_ranges.push(DrawRange {
228                material: Some(material),
229                start: 0,
230                end: buffers.indices.len(),
231                color: material.tint,
232            }),
233            _ => draw_ranges.push(DrawRange {
234                material: None,
235                start: 0,
236                end: buffers.indices.len(),
237                color: base_color,
238            }),
239        }
240
241        // Transform every vertex into view space first: that is where the
242        // near-plane clipping runs, so `w` never has to be trusted here.
243        let mut view_vertices = Vec::with_capacity(buffers.vertices.len());
244        for v in &buffers.vertices {
245            let position = view_model.transform_point(v.position);
246            let norm = normal_mat.transform_vector(v.normal).normalize();
247            view_vertices.push(ClipVertex {
248                position,
249                uv: v.uv,
250                world_normal: norm,
251            });
252        }
253
254        for draw in &draw_ranges {
255            if draw.start >= draw.end {
256                continue;
257            }
258            let draw_index = prepared.len();
259            prepared.push(PreparedDraw::new(draw.material, textures, draw.color));
260            for tri in buffers.indices[draw.start..draw.end].chunks_exact(3) {
261                let polygon = [
262                    view_vertices[tri[0] as usize],
263                    view_vertices[tri[1] as usize],
264                    view_vertices[tri[2] as usize],
265                ];
266                let clipped = clip_polygon_near(&polygon, near_plane.max(1e-3));
267                if clipped.len() < 3 {
268                    continue;
269                }
270                for fan in 1..clipped.len() - 1 {
271                    project_screen_triangle(
272                        &clipped[0],
273                        &clipped[fan],
274                        &clipped[fan + 1],
275                        &projection,
276                        viewport,
277                        draw_index,
278                        &mut triangles,
279                    );
280                }
281            }
282        }
283    }
284
285    rasterize_geometry_parallel(
286        frame_buffer,
287        viewport,
288        clip,
289        &mut depth,
290        background_filled,
291        &triangles,
292        &prepared,
293        ambient_color,
294        ambient_intensity,
295        dir_light_color,
296        dir_light_dir,
297        dir_light_intensity,
298        vp_w,
299        vp_h,
300    );
301
302    // 4.5. Cloud shells pass: translucent atmospheric shells drawn over geometry
303    // when coverage and opacity are nonzero.
304    for shell in scene.cloud_shells() {
305        if shell.effective_opacity() > 0.0 {
306            render_cloud_shell(frame_buffer, viewport, clip, &depth.rows, scene, shell);
307        }
308    }
309
310    // 5. Overlay pass: 2D primitives projected with the same camera basis,
311    // drawn after depth-tested geometry.
312    if let Some(overlay) = scene.overlay() {
313        if !overlay.is_empty() {
314            let frame = overlay_frame(scene, viewport);
315            if let Some(rasterizer) = crate::scene3d::overlay_text_rasterizer() {
316                overlay.render_with(frame_buffer, viewport, &frame, rasterizer);
317            } else {
318                overlay.render_geometry_only(frame_buffer, viewport, &frame);
319            }
320        }
321    }
322}
323
324/// A vertex with everything needed to rasterize and clip a triangle.
325///
326/// Positions are view space, relative to the camera eye: that is the small
327/// coordinate space where f32 still has sub-metre detail at Earth scale, and it
328/// is what keeps near-plane clipping numerically stable.
329#[derive(Clone, Copy)]
330struct ClipVertex {
331    position: Vec3,
332    uv: (f32, f32),
333    world_normal: Vec3,
334}
335
336impl ClipVertex {
337    fn lerp(&self, other: &Self, t: f32) -> Self {
338        let mix = |a: f32, b: f32| a + (b - a) * t;
339        Self {
340            position: Vec3::new(
341                mix(self.position.x, other.position.x),
342                mix(self.position.y, other.position.y),
343                mix(self.position.z, other.position.z),
344            ),
345            uv: (mix(self.uv.0, other.uv.0), mix(self.uv.1, other.uv.1)),
346            world_normal: self.world_normal * (1.0 - t) + other.world_normal * t,
347        }
348    }
349}
350
351/// Clips a view-space polygon against the near plane `-z >= near`.
352///
353/// The common case is taken first: a polygon fully in front is returned as is,
354/// and a polygon fully behind is dropped. Only a polygon that straddles the
355/// plane is interpolated, so any numerical slip in the crossing test cannot
356/// shrink geometry that is fully in front of the camera.
357fn clip_polygon_near(polygon: &[ClipVertex], near: f32) -> Vec<ClipVertex> {
358    if polygon.is_empty() {
359        return Vec::new();
360    }
361    // An entirely front-facing polygon needs no interpolation at all.
362    if polygon.iter().all(|v| -v.position.z >= near) {
363        return polygon.to_vec();
364    }
365
366    let mut out: Vec<ClipVertex> = Vec::with_capacity(polygon.len() + 2);
367    for index in 0..polygon.len() {
368        let current = &polygon[index];
369        let next = &polygon[(index + 1) % polygon.len()];
370        let current_in = -current.position.z >= near;
371        let next_in = -next.position.z >= near;
372        if current_in {
373            out.push(*current);
374        }
375        if current_in != next_in {
376            let denominator = current.position.z - next.position.z;
377            if denominator.abs() > 1e-12 {
378                let t = (-near - current.position.z) / denominator;
379                out.push(current.lerp(next, t.clamp(0.0, 1.0)));
380            }
381        }
382    }
383    out
384}
385
386/// Uses the scene's declared up vector when it is usable, otherwise falls back
387/// to an axis that is not parallel to the view direction.
388fn camera_up_hint(scene: &Scene3D, eye: Vec3, target: Vec3) -> Vec3 {
389    let forward = (target - eye).normalize();
390    if let Some(up) = scene.camera_up() {
391        let hint = Vec3::new(up[0] as f32, up[1] as f32, up[2] as f32);
392        if hint.length() > 1e-6 && forward.cross(hint).length() > 1e-4 {
393            return hint;
394        }
395    }
396    scene_up(eye, target)
397}
398
399/// Picks an up hint that is not parallel to the view direction.
400///
401/// A straight-down view has no unique right vector from the default world up,
402/// so the hint falls back to a second axis; without this, the view basis
403/// degenerates and the near plane sits at the world origin instead of the eye.
404fn scene_up(eye: Vec3, target: Vec3) -> Vec3 {
405    let forward = (target - eye).normalize();
406    if forward.cross(Vec3::UP).length() > 1e-4 {
407        Vec3::UP
408    } else if forward.cross(Vec3::new(0.0, 0.0, 1.0)).length() > 1e-4 {
409        Vec3::new(0.0, 0.0, 1.0)
410    } else {
411        Vec3::new(1.0, 0.0, 0.0)
412    }
413}
414
415/// Depth buffer for one frame.
416struct RealDepthBuffer {
417    rows: Vec<f32>,
418}
419
420/// Writes a fill colour into the viewport without alpha blending.
421fn fill_viewport(frame_buffer: &mut FrameBuffer, viewport: Rect, colour: impl Fn(usize) -> Color) {
422    let width = frame_buffer.width;
423    let x0 = viewport.x.max(0.0) as usize;
424    let y0 = viewport.y.max(0.0) as usize;
425    let x1 = (viewport.max_x().max(0.0) as usize).min(width);
426    let y1 = (viewport.max_y().max(0.0) as usize).min(frame_buffer.height);
427    for y in y0..y1 {
428        let color = colour(y - y0);
429        let (r, g, b, a) = color.to_rgba8();
430        let row_start = (y * width + x0) * 4;
431        let row_end = (y * width + x1) * 4;
432        for chunk in frame_buffer.pixels[row_start..row_end].chunks_exact_mut(4) {
433            chunk[0] = r;
434            chunk[1] = g;
435            chunk[2] = b;
436            chunk[3] = a;
437        }
438    }
439}
440
441/// A projected vertex with screen-space attributes that interpolate linearly.
442///
443/// `u_over_w` and `v_over_w` are the perspective-correct quantities: they are
444/// affine across a triangle in screen space, unlike raw UVs.
445#[derive(Clone, Copy)]
446struct ScreenVertex {
447    x: f32,
448    y: f32,
449    z: f32,
450    inv_w: f32,
451    u_over_w: f32,
452    v_over_w: f32,
453    world_normal: Vec3,
454}
455
456impl ScreenVertex {
457    fn lerp(&self, other: &Self, t: f32) -> Self {
458        let mix = |a: f32, b: f32| a + (b - a) * t;
459        Self {
460            x: mix(self.x, other.x),
461            y: mix(self.y, other.y),
462            z: mix(self.z, other.z),
463            inv_w: mix(self.inv_w, other.inv_w),
464            u_over_w: mix(self.u_over_w, other.u_over_w),
465            v_over_w: mix(self.v_over_w, other.v_over_w),
466            world_normal: self.world_normal * (1.0 - t) + other.world_normal * t,
467        }
468    }
469}
470
471/// One triangle after near-plane and screen-space clipping.
472struct ScreenTriangle {
473    vertices: [ScreenVertex; 3],
474    draw: usize,
475}
476
477/// Per-draw state hoisted out of the pixel loop.
478struct PreparedDraw<'a> {
479    material: Option<&'a TexturedMaterial3D>,
480    texture: Option<&'a crate::texture3d::Texture>,
481    fast_bilinear: bool,
482    base: [f32; 4],
483    uv_scale: [f32; 2],
484    uv_offset: [f32; 2],
485    opacity: f32,
486}
487
488impl<'a> PreparedDraw<'a> {
489    fn new(
490        material: Option<&'a TexturedMaterial3D>,
491        textures: Option<&'a TextureStore>,
492        color: Color,
493    ) -> Self {
494        let texture =
495            material.and_then(|material| textures.and_then(|store| store.get(material.texture)));
496        let fast_bilinear = texture
497            .map(|texture| {
498                texture.sampler.filter == FilterMode::Bilinear
499                    && texture.sampler.address_u == AddressMode::ClampToEdge
500                    && texture.sampler.address_v == AddressMode::ClampToEdge
501            })
502            .unwrap_or(false);
503        let (uv_scale, uv_offset, opacity) = match material {
504            Some(material) => (
505                material.uv_transform.scale,
506                material.uv_transform.offset,
507                material.opacity,
508            ),
509            None => ([1.0, 1.0], [0.0, 0.0], 1.0),
510        };
511        Self {
512            material,
513            texture,
514            fast_bilinear,
515            base: [color.r(), color.g(), color.b(), color.a()],
516            uv_scale,
517            uv_offset,
518            opacity,
519        }
520    }
521}
522
523fn project_view_vertex(
524    vertex: &ClipVertex,
525    projection: &Mat4,
526    viewport: Rect,
527) -> Option<ScreenVertex> {
528    let clip = projection.transform_vec4(Vec4::from_vec3(vertex.position, 1.0));
529    if clip.w <= 1e-6 {
530        return None;
531    }
532    let inv_w = 1.0 / clip.w;
533    Some(ScreenVertex {
534        x: (clip.x * inv_w + 1.0) * 0.5 * viewport.width,
535        y: (1.0 - clip.y * inv_w) * 0.5 * viewport.height,
536        z: clip.z * inv_w,
537        inv_w,
538        u_over_w: vertex.uv.0 * inv_w,
539        v_over_w: vertex.uv.1 * inv_w,
540        world_normal: vertex.world_normal,
541    })
542}
543
544fn clip_screen_axis(
545    polygon: &[ScreenVertex],
546    horizontal: bool,
547    bound: f32,
548    keep_greater: bool,
549) -> Vec<ScreenVertex> {
550    if polygon.is_empty() {
551        return Vec::new();
552    }
553    let distance = |v: &ScreenVertex| {
554        let value = if horizontal { v.x } else { v.y };
555        if keep_greater {
556            value - bound
557        } else {
558            bound - value
559        }
560    };
561    if polygon.iter().all(|v| distance(v) >= 0.0) {
562        return polygon.to_vec();
563    }
564    let mut out = Vec::with_capacity(polygon.len() + 2);
565    for index in 0..polygon.len() {
566        let current = &polygon[index];
567        let next = &polygon[(index + 1) % polygon.len()];
568        let d_current = distance(current);
569        let d_next = distance(next);
570        if d_current >= 0.0 {
571            out.push(*current);
572        }
573        if (d_current >= 0.0) != (d_next >= 0.0) {
574            let denominator = d_current - d_next;
575            if denominator.abs() > 1e-12 {
576                let t = (d_current / denominator).clamp(0.0, 1.0);
577                out.push(current.lerp(next, t));
578            }
579        }
580    }
581    out
582}
583
584/// Projects a view-space triangle, clips it to the viewport, and appends the
585/// resulting fan. Clipping in screen space keeps the raster bounding boxes
586/// bounded; a triangle whose corners are far outside the frame otherwise has a
587/// box covering the whole frame while covering only a sliver.
588fn project_screen_triangle(
589    v0: &ClipVertex,
590    v1: &ClipVertex,
591    v2: &ClipVertex,
592    projection: &Mat4,
593    viewport: Rect,
594    draw: usize,
595    out: &mut Vec<ScreenTriangle>,
596) {
597    let (Some(s0), Some(s1), Some(s2)) = (
598        project_view_vertex(v0, projection, viewport),
599        project_view_vertex(v1, projection, viewport),
600        project_view_vertex(v2, projection, viewport),
601    ) else {
602        return;
603    };
604
605    let w = viewport.width;
606    let h = viewport.height;
607    let mut polygon = vec![s0, s1, s2];
608    for (horizontal, bound, greater) in [
609        (true, 0.0, true),
610        (true, w, false),
611        (false, 0.0, true),
612        (false, h, false),
613    ] {
614        polygon = clip_screen_axis(&polygon, horizontal, bound, greater);
615        if polygon.len() < 3 {
616            return;
617        }
618    }
619
620    for fan in 1..polygon.len() - 1 {
621        out.push(ScreenTriangle {
622            vertices: [polygon[0], polygon[fan], polygon[fan + 1]],
623            draw,
624        });
625    }
626}
627
628/// Rasterizes every prepared triangle, splitting the viewport into horizontal
629/// bands so all available cores work on disjoint rows.
630#[allow(clippy::too_many_arguments)]
631fn rasterize_geometry_parallel(
632    frame_buffer: &mut FrameBuffer,
633    viewport: Rect,
634    clip: Option<Rect>,
635    depth: &mut RealDepthBuffer,
636    translucent_over_background: bool,
637    triangles: &[ScreenTriangle],
638    draws: &[PreparedDraw],
639    ambient_color: Color,
640    ambient_intensity: f32,
641    dir_light_color: Color,
642    dir_light_dir: Vec3,
643    dir_light_intensity: f32,
644    vp_w: usize,
645    vp_h: usize,
646) {
647    if triangles.is_empty() {
648        return;
649    }
650    let full_width = frame_buffer.width;
651    let y_origin = viewport.y.max(0.0) as usize;
652    // Bands cover framebuffer rows `y_origin .. y_origin + rows`. The pixel
653    // slice must start at the viewport origin, not at row zero, or a panel
654    // inset in the window paints shifted upward.
655    let available_rows = frame_buffer.height.saturating_sub(y_origin).min(vp_h);
656    if available_rows == 0 || vp_w == 0 {
657        return;
658    }
659    let row_bytes = full_width * 4;
660    let pixel_start = (y_origin * row_bytes).min(frame_buffer.pixels.len());
661
662    // Spawning threads costs more than it saves for a small preview widget, so
663    // tiny viewports and tiny triangle lists stay serial.
664    const PARALLEL_AREA: usize = 8_192;
665    let area = vp_w.saturating_mul(available_rows);
666    let max_threads = std::thread::available_parallelism()
667        .map(|n| n.get())
668        .unwrap_or(1)
669        .clamp(1, 16);
670    let threads = if area < PARALLEL_AREA { 1 } else { max_threads };
671    let band_rows = available_rows.div_ceil(threads).max(1);
672
673    let pixels = &mut frame_buffer.pixels[pixel_start..];
674    let depth_rows = &mut depth.rows[..available_rows * vp_w];
675    std::thread::scope(|scope| {
676        let mut pixel_rest = pixels;
677        let mut depth_rest = depth_rows;
678        let mut py_start = 0usize;
679        while py_start < available_rows {
680            // The last band is clamped so the pixel and depth slices always
681            // describe the same rows.
682            let rows = band_rows.min(available_rows - py_start);
683            let pixel_split = (rows * row_bytes).min(pixel_rest.len());
684            let depth_split = (rows * vp_w).min(depth_rest.len());
685            let (pixel_band, pixel_tail) = pixel_rest.split_at_mut(pixel_split);
686            let (depth_band, depth_tail) = depth_rest.split_at_mut(depth_split);
687            pixel_rest = pixel_tail;
688            depth_rest = depth_tail;
689
690            if threads == 1 {
691                rasterize_band(
692                    pixel_band,
693                    full_width,
694                    rows,
695                    depth_band,
696                    viewport,
697                    clip,
698                    translucent_over_background,
699                    triangles,
700                    draws,
701                    ambient_color,
702                    ambient_intensity,
703                    dir_light_color,
704                    dir_light_dir,
705                    dir_light_intensity,
706                    vp_w,
707                    py_start,
708                );
709            } else {
710                scope.spawn(move || {
711                    rasterize_band(
712                        pixel_band,
713                        full_width,
714                        rows,
715                        depth_band,
716                        viewport,
717                        clip,
718                        translucent_over_background,
719                        triangles,
720                        draws,
721                        ambient_color,
722                        ambient_intensity,
723                        dir_light_color,
724                        dir_light_dir,
725                        dir_light_intensity,
726                        vp_w,
727                        py_start,
728                    );
729                });
730            }
731            py_start += rows;
732        }
733    });
734}
735
736/// Rasterizes the triangles that intersect one row band.
737#[allow(clippy::too_many_arguments)]
738fn rasterize_band(
739    pixels: &mut [u8],
740    full_width: usize,
741    rows: usize,
742    depth: &mut [f32],
743    viewport: Rect,
744    clip: Option<Rect>,
745    translucent_over_background: bool,
746    triangles: &[ScreenTriangle],
747    draws: &[PreparedDraw],
748    ambient_color: Color,
749    ambient_intensity: f32,
750    dir_light_color: Color,
751    dir_light_dir: Vec3,
752    dir_light_intensity: f32,
753    vp_w: usize,
754    py_start: usize,
755) {
756    let band_end = py_start + rows;
757    for triangle in triangles {
758        let bbox_min_y = triangle
759            .vertices
760            .iter()
761            .map(|v| v.y)
762            .fold(f32::INFINITY, f32::min)
763            .floor() as isize;
764        let bbox_max_y = triangle
765            .vertices
766            .iter()
767            .map(|v| v.y)
768            .fold(f32::NEG_INFINITY, f32::max)
769            .ceil() as isize;
770        if bbox_max_y < py_start as isize || bbox_min_y >= band_end as isize {
771            continue;
772        }
773        rasterize_screen_triangle(
774            pixels,
775            full_width,
776            py_start,
777            rows,
778            depth,
779            viewport,
780            clip,
781            translucent_over_background,
782            &triangle.vertices[0],
783            &triangle.vertices[1],
784            &triangle.vertices[2],
785            &draws[triangle.draw],
786            ambient_color,
787            ambient_intensity,
788            dir_light_color,
789            dir_light_dir,
790            dir_light_intensity,
791            vp_w,
792        );
793    }
794}
795
796#[allow(clippy::too_many_arguments)]
797fn rasterize_screen_triangle(
798    pixels: &mut [u8],
799    full_width: usize,
800    py_start: usize,
801    rows: usize,
802    depth: &mut [f32],
803    viewport: Rect,
804    clip: Option<Rect>,
805    translucent_over_background: bool,
806    v0: &ScreenVertex,
807    v1: &ScreenVertex,
808    v2: &ScreenVertex,
809    draw: &PreparedDraw,
810    ambient_color: Color,
811    ambient_intensity: f32,
812    dir_light_color: Color,
813    dir_light_dir: Vec3,
814    dir_light_intensity: f32,
815    vp_w: usize,
816) {
817    let (x0, y0, z0, inv0) = (v0.x, v0.y, v0.z, v0.inv_w);
818    let (x1, y1, z1, inv1) = (v1.x, v1.y, v1.z, v1.inv_w);
819    let (x2, y2, z2, inv2) = (v2.x, v2.y, v2.z, v2.inv_w);
820
821    let min_x = (x0.min(x1).min(x2).floor() as isize)
822        .max(0)
823        .min(vp_w as isize) as usize;
824    let max_x = ((x0.max(x1).max(x2).ceil() as isize) + 1)
825        .max(0)
826        .min(vp_w as isize) as usize;
827    let min_y = (y0.min(y1).min(y2).floor() as isize)
828        .max(py_start as isize)
829        .min((py_start + rows) as isize) as usize;
830    let max_y = ((y0.max(y1).max(y2).ceil() as isize) + 1)
831        .max(py_start as isize)
832        .min((py_start + rows) as isize) as usize;
833
834    let denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2);
835    if denom.abs() < 1e-12 {
836        return;
837    }
838    let inv_denom = 1.0 / denom;
839
840    let (u0, v0_uv) = (v0.u_over_w, v0.v_over_w);
841    let (u1, v1_uv) = (v1.u_over_w, v1.v_over_w);
842    let (u2, v2_uv) = (v2.u_over_w, v2.v_over_w);
843
844    let needs_light = match draw.material {
845        Some(material) => material.lit,
846        None => true,
847    };
848    let (base_r, base_g, base_b, base_a) = (draw.base[0], draw.base[1], draw.base[2], draw.base[3]);
849
850    let dw0_dx = (y1 - y2) * inv_denom;
851    let dw1_dx = (y2 - y0) * inv_denom;
852    let dz_dx = dw0_dx * (z0 - z2) + dw1_dx * (z1 - z2);
853
854    for py in min_y..max_y {
855        let fy = py as f32 + 0.5;
856        let fx = min_x as f32 + 0.5;
857        let mut w0 = ((y1 - y2) * (fx - x2) + (x2 - x1) * (fy - y2)) * inv_denom;
858        let mut w1 = ((y2 - y0) * (fx - x2) + (x0 - x2) * (fy - y2)) * inv_denom;
859        let mut interp_depth = w0 * z0 + w1 * z1 + (1.0 - w0 - w1) * z2;
860        let depth_row = (py - py_start) * vp_w;
861        let pixel_row = (py - py_start) * full_width;
862
863        for px in min_x..max_x {
864            let w2 = 1.0 - w0 - w1;
865            if w0 < -1e-6 || w1 < -1e-6 || w2 < -1e-6 {
866                w0 += dw0_dx;
867                w1 += dw1_dx;
868                interp_depth += dz_dx;
869                continue;
870            }
871
872            let depth_idx = depth_row + px;
873            let (r_factor, g_factor, b_factor) = if needs_light {
874                let norm = (v0.world_normal * w0 + v1.world_normal * w1 + v2.world_normal * w2)
875                    .normalize();
876                let n_dot_l = norm.dot(dir_light_dir).max(0.0);
877                let diffuse = dir_light_intensity * n_dot_l;
878                (
879                    (ambient_color.r() * ambient_intensity + dir_light_color.r() * diffuse)
880                        .min(1.0),
881                    (ambient_color.g() * ambient_intensity + dir_light_color.g() * diffuse)
882                        .min(1.0),
883                    (ambient_color.b() * ambient_intensity + dir_light_color.b() * diffuse)
884                        .min(1.0),
885                )
886            } else {
887                (1.0, 1.0, 1.0)
888            };
889
890            let (r, g, b, a) = match draw.material {
891                Some(_) => {
892                    let sampled = match draw.texture {
893                        Some(texture) => {
894                            let inv = w0 * inv0 + w1 * inv1 + w2 * inv2;
895                            let uv = if inv.abs() > 1e-12 {
896                                (
897                                    (w0 * u0 + w1 * u1 + w2 * u2) / inv,
898                                    (w0 * v0_uv + w1 * v1_uv + w2 * v2_uv) / inv,
899                                )
900                            } else {
901                                (u0, v0_uv)
902                            };
903                            let u = uv.0 * draw.uv_scale[0] + draw.uv_offset[0];
904                            let v = uv.1 * draw.uv_scale[1] + draw.uv_offset[1];
905                            if draw.fast_bilinear {
906                                sample_bilinear_clamped(texture, u, v)
907                            } else {
908                                sample_texture(texture, (u, v))
909                            }
910                        }
911                        None => [255, 255, 255, 255],
912                    };
913
914                    let sr = sampled[0] as f32 / 255.0 * base_r;
915                    let sg = sampled[1] as f32 / 255.0 * base_g;
916                    let sb = sampled[2] as f32 / 255.0 * base_b;
917                    let sa = sampled[3] as f32 / 255.0 * draw.opacity;
918
919                    let lit = draw.material.map(|m| m.lit).unwrap_or(false);
920                    let (lr, lg, lb) = if lit {
921                        (r_factor, g_factor, b_factor)
922                    } else {
923                        (1.0, 1.0, 1.0)
924                    };
925
926                    (
927                        ((sr * lr) * 255.0).min(255.0) as u8,
928                        ((sg * lg) * 255.0).min(255.0) as u8,
929                        ((sb * lb) * 255.0).min(255.0) as u8,
930                        ((sa * base_a * 255.0) + 0.5).min(255.0) as u8,
931                    )
932                }
933                None => {
934                    let r = ((base_r * r_factor) * 255.0).min(255.0) as u8;
935                    let g = ((base_g * g_factor) * 255.0).min(255.0) as u8;
936                    let b = ((base_b * b_factor) * 255.0).min(255.0) as u8;
937                    (r, g, b, (base_a * 255.0).round() as u8)
938                }
939            };
940
941            let global_x = viewport.x as usize + px;
942            if global_x >= full_width {
943                break;
944            }
945            let global_y = viewport.y as usize + py;
946
947            let inside_clip = match clip {
948                Some(c) => {
949                    let gx = global_x as f32;
950                    let gy = global_y as f32;
951                    gx >= c.x && gx < c.max_x() && gy >= c.y && gy < c.max_y()
952                }
953                None => true,
954            };
955            if !inside_clip {
956                w0 += dw0_dx;
957                w1 += dw1_dx;
958                interp_depth += dz_dx;
959                continue;
960            }
961
962            let pixel_index = pixel_row + global_x;
963            if a == 255 {
964                if depth[depth_idx] > interp_depth && interp_depth >= 0.0 {
965                    depth[depth_idx] = interp_depth;
966                    write_opaque_band(pixels, pixel_index, r, g, b);
967                }
968            } else if a > 0 {
969                if translucent_over_background && interp_depth < depth[depth_idx] {
970                    depth[depth_idx] = depth[depth_idx].min(interp_depth);
971                }
972                blend_band(pixels, pixel_index, r, g, b, a);
973            }
974
975            w0 += dw0_dx;
976            w1 += dw1_dx;
977            interp_depth += dz_dx;
978        }
979    }
980}
981
982#[inline(always)]
983fn write_opaque_band(pixels: &mut [u8], index: usize, r: u8, g: u8, b: u8) {
984    if index * 4 + 3 >= pixels.len() {
985        return;
986    }
987    pixels[index * 4] = r;
988    pixels[index * 4 + 1] = g;
989    pixels[index * 4 + 2] = b;
990    pixels[index * 4 + 3] = 255;
991}
992
993/// Porter-Duff over into a band slice.
994#[inline]
995fn blend_band(pixels: &mut [u8], index: usize, r: u8, g: u8, b: u8, a: u8) {
996    if index * 4 + 3 >= pixels.len() {
997        return;
998    }
999    let src_a = a as f32 / 255.0;
1000    let dst = index * 4;
1001    let dst_a = pixels[dst + 3] as f32 / 255.0;
1002    let out_a = src_a + dst_a * (1.0 - src_a);
1003    if out_a <= 1e-5 {
1004        return;
1005    }
1006    for (offset, src) in [(0, r), (1, g), (2, b)] {
1007        let src_f = src as f32 / 255.0;
1008        let dst_f = pixels[dst + offset] as f32 / 255.0;
1009        let out = (src_f * src_a + dst_f * dst_a * (1.0 - src_a)) / out_a;
1010        pixels[dst + offset] = (out * 255.0).round() as u8;
1011    }
1012    pixels[dst + 3] = (out_a * 255.0).round() as u8;
1013}
1014
1015/// Builds the f64 overlay frame that shares the scene camera's eye, target, and
1016/// field of view, so overlay anchors land on the geometry they annotate.
1017///
1018/// This is the same frame the overlay pass rasterizes with; callers that need
1019/// to project their own anchors should use it rather than rebuilding a camera.
1020pub fn overlay_frame(scene: &Scene3D, viewport: Rect) -> crate::camera64::RenderFrame64 {
1021    use crate::camera64::{Camera64, DVec3, RenderFrame64};
1022    let camera = match &scene.camera {
1023        Camera3D::Perspective {
1024            fov_horizontal_deg,
1025            near,
1026            far,
1027            position,
1028            target,
1029        } => Camera64 {
1030            eye: DVec3::new(position[0] as f64, position[1] as f64, position[2] as f64),
1031            target: DVec3::new(target[0] as f64, target[1] as f64, target[2] as f64),
1032            up: scene
1033                .camera_up()
1034                .map(|u| DVec3::new(u[0], u[1], u[2]))
1035                .unwrap_or(DVec3::UP),
1036            fov_horizontal_deg: *fov_horizontal_deg as f64,
1037            near: *near as f64,
1038            far: *far as f64,
1039        },
1040        Camera3D::Orthographic {
1041            near,
1042            far,
1043            position,
1044            target,
1045            ..
1046        } => Camera64 {
1047            eye: DVec3::new(position[0] as f64, position[1] as f64, position[2] as f64),
1048            target: DVec3::new(target[0] as f64, target[1] as f64, target[2] as f64),
1049            up: scene
1050                .camera_up()
1051                .map(|u| DVec3::new(u[0], u[1], u[2]))
1052                .unwrap_or(DVec3::UP),
1053            fov_horizontal_deg: 60.0,
1054            near: *near as f64,
1055            far: *far as f64,
1056        },
1057    };
1058    RenderFrame64::from_camera(&camera, viewport.width as f64, viewport.height as f64)
1059}
1060
1061fn render_cloud_shell(
1062    frame_buffer: &mut FrameBuffer,
1063    viewport: Rect,
1064    clip: Option<Rect>,
1065    depth_buffer: &[f32],
1066    scene: &Scene3D,
1067    shell: &crate::scene3d::CloudShell3D,
1068) {
1069    let opacity = shell.effective_opacity();
1070    if opacity <= 0.0 {
1071        return;
1072    }
1073
1074    let vp_x = viewport.x.max(0.0) as usize;
1075    let vp_y = viewport.y.max(0.0) as usize;
1076    let vp_w = viewport.width.ceil().max(1.0) as usize;
1077    let vp_h = viewport.height.ceil().max(1.0) as usize;
1078
1079    let (clip_min_x, clip_max_x, clip_min_y, clip_max_y) = match clip {
1080        Some(c) => (
1081            c.x.max(viewport.x).floor() as usize,
1082            (c.x + c.width).min(viewport.x + viewport.width).ceil() as usize,
1083            c.y.max(viewport.y).floor() as usize,
1084            (c.y + c.height).min(viewport.y + viewport.height).ceil() as usize,
1085        ),
1086        None => (
1087            vp_x,
1088            (viewport.x + viewport.width).ceil() as usize,
1089            vp_y,
1090            (viewport.y + viewport.height).ceil() as usize,
1091        ),
1092    };
1093
1094    let (camera_eye, camera_target, near_plane, far_plane, fov_y_rad) = match &scene.camera {
1095        crate::scene3d::Camera3D::Perspective {
1096            position,
1097            target,
1098            near,
1099            far,
1100            fov_horizontal_deg,
1101        } => {
1102            let eye = crate::camera64::DVec3::new(
1103                position[0] as f64,
1104                position[1] as f64,
1105                position[2] as f64,
1106            );
1107            let tgt =
1108                crate::camera64::DVec3::new(target[0] as f64, target[1] as f64, target[2] as f64);
1109            let aspect = vp_w as f64 / vp_h.max(1) as f64;
1110            let fov_x = fov_horizontal_deg.to_radians() as f64;
1111            let fov_y = 2.0 * ((fov_x * 0.5).tan() / aspect).atan();
1112            (eye, tgt, *near as f64, *far as f64, fov_y)
1113        }
1114        _ => return,
1115    };
1116
1117    let forward = camera_target.sub(camera_eye).normalize();
1118    let cam_up = scene
1119        .camera_up()
1120        .map(|u| crate::camera64::DVec3::new(u[0], u[1], u[2]))
1121        .unwrap_or(crate::camera64::DVec3::UP);
1122    let up_hint = if forward.cross(cam_up).length() < 1e-6 {
1123        if forward
1124            .cross(crate::camera64::DVec3::new(0.0, 0.0, 1.0))
1125            .length()
1126            > 1e-6
1127        {
1128            crate::camera64::DVec3::new(0.0, 0.0, 1.0)
1129        } else {
1130            crate::camera64::DVec3::new(0.0, 1.0, 0.0)
1131        }
1132    } else {
1133        cam_up
1134    };
1135    let right = forward.cross(up_hint).normalize();
1136    let up = right.cross(forward).normalize();
1137
1138    let aspect = vp_w as f64 / vp_h.max(1) as f64;
1139    let tan_half_y = (fov_y_rad * 0.5).tan();
1140    let tan_half_x = tan_half_y * aspect;
1141
1142    let sphere_center =
1143        crate::camera64::DVec3::new(shell.centre[0], shell.centre[1], shell.centre[2]);
1144    let sphere_radius = shell.radius;
1145    let sphere_radius_sq = sphere_radius * sphere_radius;
1146
1147    let shell_color = shell.color;
1148    let base_alpha = opacity * shell_color.a();
1149
1150    for y in clip_min_y..clip_max_y {
1151        if y >= frame_buffer.height {
1152            break;
1153        }
1154        let row_ndc_y = 1.0 - ((y as f64 - vp_y as f64 + 0.5) / (vp_h as f64)) * 2.0;
1155        let depth_row_offset = (y - vp_y) * vp_w;
1156
1157        for x in clip_min_x..clip_max_x {
1158            if x >= frame_buffer.width {
1159                break;
1160            }
1161            let col_ndc_x = ((x as f64 - vp_x as f64 + 0.5) / (vp_w as f64)) * 2.0 - 1.0;
1162
1163            let ray_dir = right
1164                .scale(col_ndc_x * tan_half_x)
1165                .add(up.scale(row_ndc_y * tan_half_y))
1166                .add(forward)
1167                .normalize();
1168
1169            let p0 = camera_eye.sub(sphere_center);
1170            let b = 2.0 * p0.dot(ray_dir);
1171            let c = p0.dot(p0) - sphere_radius_sq;
1172            let discriminant = b * b - 4.0 * c;
1173
1174            if discriminant < 0.0 {
1175                continue;
1176            }
1177
1178            let sqrt_disc = discriminant.sqrt();
1179            let t1 = (-b - sqrt_disc) * 0.5;
1180            let t2 = (-b + sqrt_disc) * 0.5;
1181
1182            let t = if t1 >= near_plane && t1 <= far_plane {
1183                t1
1184            } else if t2 >= near_plane && t2 <= far_plane {
1185                t2
1186            } else {
1187                continue;
1188            };
1189
1190            let pixel_sub_x = x - vp_x;
1191            if pixel_sub_x < vp_w {
1192                let depth_idx = depth_row_offset + pixel_sub_x;
1193                if depth_idx < depth_buffer.len() {
1194                    let d = depth_buffer[depth_idx];
1195                    let view_z = ray_dir.scale(t).dot(forward);
1196                    let range = far_plane - near_plane;
1197                    let cloud_ndc_depth = if range.abs() > 1e-6 {
1198                        ((far_plane / range) * (1.0 - near_plane / view_z.max(near_plane))) as f32
1199                    } else {
1200                        0.5
1201                    };
1202                    if d < cloud_ndc_depth {
1203                        continue;
1204                    }
1205                }
1206            }
1207
1208            let hit_point = camera_eye.add(ray_dir.scale(t));
1209            let normal = hit_point.sub(sphere_center).normalize();
1210            let cos_theta = (-ray_dir.dot(normal)).abs().clamp(0.0, 1.0);
1211            let limb_factor = (1.0 - cos_theta * 0.4).clamp(0.6, 1.4);
1212            let pixel_alpha = (base_alpha * limb_factor as f32).clamp(0.0, 1.0);
1213
1214            let (cr, cg, cb, _) = shell_color.to_rgba8();
1215            let blend_color =
1216                strata_style::types::Color::rgba(cr, cg, cb, (pixel_alpha * 255.0).round() as u8);
1217            frame_buffer.set_pixel(x, y, blend_color);
1218        }
1219    }
1220}
1221
1222/// Evaluates the GPU Relative-To-Eye (RTE) double-single vertex shader transformation in software.
1223///
1224/// Computes `(pos_high - eye_high) + (pos_low - eye_low)` and projects via `view_proj_rel`.
1225pub fn evaluate_gpu_rte_vertex(
1226    pos_high: [f32; 3],
1227    pos_low: [f32; 3],
1228    eye_high: [f32; 3],
1229    eye_low: [f32; 3],
1230    view_proj_rel: &Mat4,
1231) -> Vec4 {
1232    let rel_x = (pos_high[0] - eye_high[0]) + (pos_low[0] - eye_low[0]);
1233    let rel_y = (pos_high[1] - eye_high[1]) + (pos_low[1] - eye_low[1]);
1234    let rel_z = (pos_high[2] - eye_high[2]) + (pos_low[2] - eye_low[2]);
1235    view_proj_rel.transform_vec4(Vec4::from_vec3(Vec3::new(rel_x, rel_y, rel_z), 1.0))
1236}