1use crate::{Camera, ClipDepth, Color, MeshCache, RenderItem, Vec3, Vec4, vec2};
2
3pub const MAX_DIMENSION: u32 = 8192;
5pub const MAX_PIXELS: usize = 16_777_216;
6const CLIP_VERTEX_CAPACITY: usize = 12;
7const MAX_STRIPS: usize = 32;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum RenderError {
11 InvalidDimensions,
12 InvalidCamera,
13 InvalidSettings,
14}
15impl std::fmt::Display for RenderError {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 write!(f, "software renderer: {self:?}")
18 }
19}
20impl std::error::Error for RenderError {}
21
22pub struct Framebuffer {
23 pub(crate) width: u32,
24 pub(crate) height: u32,
25 pixels: Vec<[u8; 4]>,
26 depth: Vec<f32>,
27}
28impl Framebuffer {
29 pub fn new(width: u32, height: u32) -> Result<Self, RenderError> {
30 let count = (width as usize)
31 .checked_mul(height as usize)
32 .ok_or(RenderError::InvalidDimensions)?;
33 if width == 0
34 || height == 0
35 || width > MAX_DIMENSION
36 || height > MAX_DIMENSION
37 || count > MAX_PIXELS
38 {
39 return Err(RenderError::InvalidDimensions);
40 }
41 Ok(Self {
42 width,
43 height,
44 pixels: vec![[0, 0, 0, 255]; count],
45 depth: vec![f32::INFINITY; count],
46 })
47 }
48 pub const fn width(&self) -> u32 {
49 self.width
50 }
51 pub const fn height(&self) -> u32 {
52 self.height
53 }
54 pub fn pixels_mut(&mut self) -> &mut [[u8; 4]] {
56 &mut self.pixels
57 }
58 pub fn pixels(&self) -> &[[u8; 4]] {
59 &self.pixels
60 }
61 pub fn depths(&self) -> &[f32] {
62 &self.depth
63 }
64 pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
65 if x >= self.width || y >= self.height {
66 None
67 } else {
68 Some(self.pixels[(y * self.width + x) as usize])
69 }
70 }
71 pub fn clear(&mut self, color: Color) {
72 self.pixels.fill(color.to_rgba());
73 self.depth.fill(f32::INFINITY);
74 }
75}
76#[derive(Clone, Copy, Debug)]
77pub struct Fog {
78 pub color: Color,
79 pub start: f32,
80 pub end: f32,
81}
82#[derive(Clone, Copy, Debug)]
83pub struct RenderSettings {
84 pub look: crate::Look,
85 pub clear_color: Color,
86 pub light_direction: Vec3,
88 pub ambient: f32,
89 pub diffuse: f32,
90 pub fog: Option<Fog>,
91 pub cull_backfaces: bool,
92}
93impl Default for RenderSettings {
94 fn default() -> Self {
95 Self {
96 look: crate::Look::Authored,
97 clear_color: Color::from_hex(0x293945),
98 light_direction: Vec3::new(-0.4, 0.8, 0.3),
99 ambient: 0.35,
100 diffuse: 0.65,
101 fog: None,
102 cull_backfaces: true,
103 }
104 }
105}
106impl RenderSettings {
107 fn valid(self) -> bool {
108 self.clear_color.to_vec().is_finite()
109 && self.light_direction.is_finite()
110 && self.ambient.is_finite()
111 && self.diffuse.is_finite()
112 && self.ambient >= 0.0
113 && self.diffuse >= 0.0
114 && self.fog.is_none_or(|f| {
115 f.color.to_vec().is_finite()
116 && f.start.is_finite()
117 && f.end.is_finite()
118 && f.start >= 0.0
119 && f.end > f.start
120 })
121 }
122}
123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124pub struct RenderStats {
125 pub submitted_instances: u64,
126 pub visible_instances: u64,
127 pub culled_instances: u64,
128 pub invalid_instances: u64,
129 pub submitted_triangles: u64,
130 pub clipped_triangles: u64,
131 pub rasterized_triangles: u64,
132 pub shaded_pixels: u64,
133}
134#[derive(Clone, Copy, Default)]
135struct ClipVertex {
136 clip: Vec4,
137 world: Vec3,
138 color: Vec4,
139 screen_x: f32,
140 screen_y: f32,
141 inv_w: f32,
142 mask: u8,
144 fog_far: bool,
146}
147impl ClipVertex {
148 #[inline]
149 fn lerp(self, other: Self, t: f32) -> Self {
150 Self {
151 clip: self.clip.lerp(other.clip, t),
152 world: self.world.lerp(other.world, t),
153 color: if self.color == other.color {
154 self.color
155 } else {
156 self.color.lerp(other.color, t)
157 },
158 screen_x: 0.0,
159 screen_y: 0.0,
160 inv_w: 0.0,
161 mask: 0,
162 fog_far: self.fog_far | other.fog_far,
163 }
164 }
165}
166
167#[derive(Clone, Copy)]
168enum TriShading {
169 FlatOpaque([u8; 4]),
170 FlatFog(u32),
171 Varying(u32),
172}
173
174#[derive(Clone, Copy)]
175struct FlatFogData {
176 rgba: [u8; 4],
177 fog_rgba: [u8; 4],
178 base_rgb255: [f32; 3],
179 delta_rgb255: [f32; 3],
180 q_base: f32,
181 dq_dx: f32,
182 dq_dy: f32,
183 wq_base: Vec3,
184 dwq_dx: Vec3,
185 dwq_dy: Vec3,
186}
187
188#[derive(Clone, Copy)]
189struct VaryingData {
190 fog: bool,
191 q_base: f32,
192 dq_dx: f32,
193 dq_dy: f32,
194 cq_base: Vec4,
195 dcq_dx: Vec4,
196 dcq_dy: Vec4,
197 wq_base: Vec3,
198 dwq_dx: Vec3,
199 dwq_dy: Vec3,
200}
201
202#[derive(Clone, Copy)]
203struct ScreenTri {
204 lx: [f64; 2],
205 ldx: [f64; 2],
206 rx: [f64; 2],
207 rdx: [f64; 2],
208 z_base: f64,
209 dz_dy: f64,
210 dz_dx: f32,
211 min_x: i32,
212 max_x: i32,
213 min_y: u16,
214 max_y: u16,
215 shading: TriShading,
216 z_in_unit: bool,
217}
218
219struct SceneBuffers {
220 order: Vec<u64>,
222 tris: Vec<ScreenTri>,
223 fog_tris: Vec<FlatFogData>,
224 var_tris: Vec<VaryingData>,
225 strip_bins: [Vec<u32>; MAX_STRIPS],
226}
227impl Default for SceneBuffers {
228 fn default() -> Self {
229 Self {
230 order: Vec::new(),
231 tris: Vec::new(),
232 fog_tris: Vec::new(),
233 var_tris: Vec::new(),
234 strip_bins: std::array::from_fn(|_| Vec::new()),
235 }
236 }
237}
238impl SceneBuffers {
239 fn clear(&mut self) {
240 self.order.clear();
241 self.tris.clear();
242 self.fog_tris.clear();
243 self.var_tris.clear();
244 }
245
246 fn sort_and_bin(&mut self, height: u32, num_strips: usize) -> u32 {
247 let strip_h = height.div_ceil(num_strips as u32).max(1);
248 for bin in &mut self.strip_bins[..num_strips] {
249 bin.clear();
250 }
251 if self.order.len() > 1 {
252 self.order.sort_unstable();
253 }
254 let last_strip = num_strips - 1;
255 for &key in &self.order {
256 let idx = key as u32;
257 let tri = &self.tris[idx as usize];
258 let s0 = (u32::from(tri.min_y) / strip_h) as usize;
259 let s1 = ((u32::from(tri.max_y) / strip_h) as usize).min(last_strip);
260 for bin in &mut self.strip_bins[s0..=s1] {
261 bin.push(idx);
262 }
263 }
264 strip_h
265 }
266}
267
268#[derive(Clone, Copy)]
269struct FogParams {
270 color: Vec4,
271 color_rgba: [u8; 4],
272 color_rgb255: [f32; 3],
273 start: f32,
274 start_sq: f32,
275 inv_range: f32,
276 camera_pos: Vec3,
277}
278
279#[cfg(not(target_arch = "wasm32"))]
280mod pool {
281 use super::{FogParams, MAX_STRIPS, SceneBuffers, raster_strip};
282 use std::sync::{
283 Arc, Condvar, Mutex, RwLock,
284 atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
285 };
286 use std::thread::{self, JoinHandle};
287
288 const MAX_WORKERS: usize = 8;
289
290 #[derive(Clone, Copy)]
291 struct FrameMeta {
292 width: usize,
293 height: u32,
294 strip_h: u32,
295 num_strips: usize,
296 clear_rgba: [u8; 4],
297 fog_params: Option<FogParams>,
298 }
299
300 struct StripBuf {
301 pixels: Vec<[u8; 4]>,
302 depths: Vec<f32>,
303 shaded: u64,
304 rendered_by_worker: bool,
305 }
306
307 struct Shared {
308 epoch: AtomicU64,
309 next_strip: AtomicUsize,
310 done: AtomicUsize,
311 sleeping: AtomicUsize,
312 shutdown: AtomicBool,
313 wake_lock: Mutex<()>,
314 wake_cv: Condvar,
315 meta: RwLock<FrameMeta>,
316 scene: RwLock<SceneBuffers>,
317 strips: [Mutex<StripBuf>; MAX_STRIPS],
318 }
319
320 pub(super) struct RasterPool {
321 total_workers: usize,
322 shared: Arc<Shared>,
323 handles: Vec<JoinHandle<()>>,
324 }
325
326 impl RasterPool {
327 pub(super) fn new(total_workers: usize) -> Self {
328 let total_workers = total_workers.clamp(1, MAX_WORKERS);
329 let workers = total_workers.saturating_sub(1);
330 let strips = std::array::from_fn(|_| {
331 Mutex::new(StripBuf {
332 pixels: Vec::new(),
333 depths: Vec::new(),
334 shaded: 0,
335 rendered_by_worker: false,
336 })
337 });
338 let shared = Arc::new(Shared {
339 epoch: AtomicU64::new(0),
340 next_strip: AtomicUsize::new(MAX_STRIPS),
341 done: AtomicUsize::new(0),
342 sleeping: AtomicUsize::new(0),
343 shutdown: AtomicBool::new(false),
344 wake_lock: Mutex::new(()),
345 wake_cv: Condvar::new(),
346 meta: RwLock::new(FrameMeta {
347 width: 0,
348 height: 0,
349 strip_h: 1,
350 num_strips: 0,
351 clear_rgba: [0; 4],
352 fog_params: None,
353 }),
354 scene: RwLock::new(SceneBuffers::default()),
355 strips,
356 });
357 let mut handles = Vec::with_capacity(workers);
358 for _ in 0..workers {
359 let s = Arc::clone(&shared);
360 handles.push(thread::spawn(move || worker_loop(s)));
361 }
362 Self {
363 total_workers,
364 shared,
365 handles,
366 }
367 }
368
369 #[allow(clippy::too_many_arguments)]
370 pub(super) fn render(
371 &self,
372 pixels: &mut [[u8; 4]],
373 depths: &mut [f32],
374 width: u32,
375 height: u32,
376 clear_rgba: [u8; 4],
377 fog_params: Option<FogParams>,
378 scene_buf: &mut SceneBuffers,
379 ) -> u64 {
380 let stride = width as usize;
381 let num_strips = (self.total_workers * 4)
382 .clamp(1, MAX_STRIPS)
383 .min(height as usize);
384 let strip_h = scene_buf.sort_and_bin(height, num_strips);
385 {
386 let mut meta = self.shared.meta.write().unwrap();
387 *meta = FrameMeta {
388 width: stride,
389 height,
390 strip_h,
391 num_strips,
392 clear_rgba,
393 fog_params,
394 };
395 }
396 {
397 let mut scene = self.shared.scene.write().unwrap();
398 std::mem::swap(&mut *scene, scene_buf);
399 }
400 let workers = self.total_workers - 1;
401 self.shared.next_strip.store(0, Ordering::Release);
402 self.shared.done.store(0, Ordering::Release);
403 self.shared.epoch.fetch_add(1, Ordering::Release);
404 if self.shared.sleeping.load(Ordering::Acquire) > 0 {
405 let _g = self.shared.wake_lock.lock().unwrap();
406 self.shared.wake_cv.notify_all();
407 }
408
409 let mut total_shaded = 0_u64;
412 let mut main_mask = 0_u32;
413 let mut empty_mask = 0_u32;
414 {
415 let scene = self.shared.scene.read().unwrap();
416 loop {
417 let s = self.shared.next_strip.fetch_add(1, Ordering::AcqRel);
418 if s >= num_strips {
419 break;
420 }
421 main_mask |= 1_u32 << s;
422 let y_start = (s as u32) * strip_h;
423 let y_end = (y_start + strip_h).min(height);
424 if y_start >= y_end {
425 continue;
426 }
427 let offset = (y_start as usize) * stride;
428 let count = ((y_end - y_start) as usize) * stride;
429 let p_slice = &mut pixels[offset..offset + count];
430 let d_slice = &mut depths[offset..offset + count];
431 p_slice.fill(clear_rgba);
432 d_slice.fill(f32::INFINITY);
433 if !scene.strip_bins[s].is_empty() {
434 total_shaded += raster_strip(
435 p_slice,
436 d_slice,
437 stride,
438 y_start,
439 y_end - 1,
440 &scene.strip_bins[s],
441 &scene,
442 fog_params,
443 );
444 }
445 }
446 for (s, bin) in scene.strip_bins[..num_strips].iter().enumerate() {
447 if bin.is_empty() {
448 empty_mask |= 1_u32 << s;
449 }
450 }
451 }
452
453 let worker_empty = empty_mask & !main_mask;
455 if worker_empty != 0 {
456 for s in 0..num_strips {
457 if (worker_empty & (1_u32 << s)) == 0 {
458 continue;
459 }
460 let y_start = (s as u32) * strip_h;
461 let y_end = (y_start + strip_h).min(height);
462 if y_start < y_end {
463 let offset = (y_start as usize) * stride;
464 let count = ((y_end - y_start) as usize) * stride;
465 pixels[offset..offset + count].fill(clear_rgba);
466 depths[offset..offset + count].fill(f32::INFINITY);
467 }
468 }
469 }
470
471 while self.shared.done.load(Ordering::Acquire) < workers {
472 std::hint::spin_loop();
473 }
474
475 let skip_mask = main_mask | empty_mask;
476 for s in 0..num_strips {
477 if (skip_mask & (1_u32 << s)) != 0 {
478 continue;
479 }
480 let y_start = (s as u32) * strip_h;
481 let y_end = (y_start + strip_h).min(height);
482 if y_start >= y_end {
483 continue;
484 }
485 let offset = (y_start as usize) * stride;
486 let count = ((y_end - y_start) as usize) * stride;
487 let mut buf = self.shared.strips[s].lock().unwrap();
488 if buf.rendered_by_worker {
489 pixels[offset..offset + count].copy_from_slice(&buf.pixels[..count]);
490 depths[offset..offset + count].copy_from_slice(&buf.depths[..count]);
491 total_shaded += buf.shaded;
492 buf.rendered_by_worker = false;
493 }
494 }
495
496 {
497 let mut scene = self.shared.scene.write().unwrap();
498 std::mem::swap(&mut *scene, scene_buf);
499 }
500 total_shaded
501 }
502 }
503
504 impl Drop for RasterPool {
505 fn drop(&mut self) {
506 self.shared.shutdown.store(true, Ordering::Release);
507 self.shared.epoch.fetch_add(1, Ordering::Release);
508 {
509 let _g = self.shared.wake_lock.lock().unwrap();
510 self.shared.wake_cv.notify_all();
511 }
512 for handle in self.handles.drain(..) {
513 let _ = handle.join();
514 }
515 }
516 }
517
518 fn worker_loop(shared: Arc<Shared>) {
519 let mut seen = 0_u64;
520 loop {
521 let mut next = shared.epoch.load(Ordering::Acquire);
522 if next == seen {
523 for _ in 0..40_000 {
524 std::hint::spin_loop();
525 next = shared.epoch.load(Ordering::Acquire);
526 if next != seen {
527 break;
528 }
529 }
530 }
531 if next == seen {
532 shared.sleeping.fetch_add(1, Ordering::AcqRel);
533 let mut g = shared.wake_lock.lock().unwrap();
534 loop {
535 next = shared.epoch.load(Ordering::Acquire);
536 if next != seen {
537 break;
538 }
539 g = shared.wake_cv.wait(g).unwrap();
540 }
541 drop(g);
542 shared.sleeping.fetch_sub(1, Ordering::AcqRel);
543 }
544 seen = next;
545 if shared.shutdown.load(Ordering::Acquire) {
546 return;
547 }
548 let meta = *shared.meta.read().unwrap();
549 let scene = shared.scene.read().unwrap();
550 loop {
551 let s = shared.next_strip.fetch_add(1, Ordering::AcqRel);
552 if s >= meta.num_strips {
553 break;
554 }
555 if scene.strip_bins[s].is_empty() {
557 continue;
558 }
559 let y_start = (s as u32) * meta.strip_h;
560 let y_end = (y_start + meta.strip_h).min(meta.height);
561 if y_start >= y_end {
562 continue;
563 }
564 let count = ((y_end - y_start) as usize) * meta.width;
565 let mut guard = shared.strips[s].lock().unwrap();
566 let buf = &mut *guard;
567 if buf.pixels.len() < count {
568 buf.pixels.resize(count, meta.clear_rgba);
569 buf.depths.resize(count, f32::INFINITY);
570 }
571 let p_slice = &mut buf.pixels[..count];
572 let d_slice = &mut buf.depths[..count];
573 p_slice.fill(meta.clear_rgba);
574 d_slice.fill(f32::INFINITY);
575 buf.shaded = raster_strip(
576 p_slice,
577 d_slice,
578 meta.width,
579 y_start,
580 y_end - 1,
581 &scene.strip_bins[s],
582 &scene,
583 meta.fog_params,
584 );
585 buf.rendered_by_worker = true;
586 }
587 drop(scene);
588 shared.done.fetch_add(1, Ordering::Release);
589 }
590 }
591}
592
593pub struct SoftwareRenderer {
594 pub framebuffer: Framebuffer,
595 pub settings: RenderSettings,
596 scratch: Vec<ClipVertex>,
597 scene: SceneBuffers,
598 #[cfg(not(target_arch = "wasm32"))]
599 pool: Option<pool::RasterPool>,
600}
601impl SoftwareRenderer {
602 pub fn new(width: u32, height: u32) -> Result<Self, RenderError> {
603 Ok(Self {
604 framebuffer: Framebuffer::new(width, height)?,
605 settings: RenderSettings::default(),
606 scratch: Vec::new(),
607 scene: SceneBuffers::default(),
608 #[cfg(not(target_arch = "wasm32"))]
609 pool: None,
610 })
611 }
612 pub fn render(
615 &mut self,
616 cache: &MeshCache,
617 items: &[RenderItem],
618 camera: Camera,
619 ) -> Result<RenderStats, RenderError> {
620 if !self.settings.valid() {
621 return Err(RenderError::InvalidSettings);
622 }
623 if !camera.position.is_finite() {
624 return Err(RenderError::InvalidCamera);
625 }
626 let frustum = camera.frustum().ok_or(RenderError::InvalidCamera)?;
627 let clear_color = self.settings.look.shade(self.settings.clear_color);
628 let mut stats = RenderStats::default();
629 let light = self.settings.light_direction.normalize_or_zero();
630 let fog_params = self.settings.fog.map(|fog| {
631 let color = self.settings.look.shade(fog.color).to_vec();
632 FogParams {
633 color,
634 color_rgba: [
635 (color.x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
636 (color.y.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
637 (color.z.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
638 255,
639 ],
640 color_rgb255: [
641 color.x.clamp(0.0, 1.0) * 255.0,
642 color.y.clamp(0.0, 1.0) * 255.0,
643 color.z.clamp(0.0, 1.0) * 255.0,
644 ],
645 start: fog.start,
646 start_sq: fog.start * fog.start,
647 inv_range: (fog.end - fog.start).recip(),
648 camera_pos: camera.position,
649 }
650 });
651 let look = self.settings.look;
652 let is_authored_look = look == crate::Look::Authored;
653 let ambient = self.settings.ambient;
654 let diffuse = self.settings.diffuse;
655 let cull_backfaces = self.settings.cull_backfaces;
656 let width = self.framebuffer.width;
657 let height = self.framebuffer.height;
658 let half_wf = 0.5 * (width as f32);
659 let half_hf = 0.5 * (height as f32);
660 let clip_depth = camera.clip_depth;
661 self.scene.clear();
662
663 for item in items {
664 stats.submitted_instances += 1;
665 let Some((mesh, bounds, unit_normals)) = cache.mesh_entry(item.mesh) else {
666 stats.invalid_instances += 1;
667 continue;
668 };
669 if !item.transform.is_finite() || !item.transform.row(3).abs_diff_eq(Vec4::W, 1.0e-5) {
670 stats.invalid_instances += 1;
671 continue;
672 }
673 let c0 = item.transform.x_axis.truncate();
674 let c1 = item.transform.y_axis.truncate();
675 let c2 = item.transform.z_axis.truncate();
676 let cof0 = c1.cross(c2);
677 let cof1 = c2.cross(c0);
678 let cof2 = c0.cross(c1);
679 let det = c0.dot(cof0);
680 if !det.is_finite() || det.abs() < 1.0e-12 {
681 stats.invalid_instances += 1;
682 continue;
683 }
684 if !frustum.intersects_bounds(bounds, item.transform) {
685 stats.culled_instances += 1;
686 continue;
687 }
688 stats.visible_instances += 1;
689
690 let inst_fog_params = fog_params.filter(|fog| {
691 let center = item.transform.transform_point3(bounds.center());
692 let half = bounds.half_extents();
693 let ext = Vec3::new(
694 c0.x.abs() * half.x + c1.x.abs() * half.y + c2.x.abs() * half.z,
695 c0.y.abs() * half.x + c1.y.abs() * half.y + c2.y.abs() * half.z,
696 c0.z.abs() * half.x + c1.z.abs() * half.y + c2.z.abs() * half.z,
697 );
698 let dx = center - fog.camera_pos;
699 dx.length_squared().sqrt() + ext.length_squared().sqrt() > fog.start
700 });
701
702 let inv_det = det.recip();
703 let n0 = cof0 * inv_det;
704 let n1 = cof1 * inv_det;
705 let n2 = cof2 * inv_det;
706 let local_light = Vec3::new(n0.dot(light), n1.dot(light), n2.dot(light));
707
708 let s0 = c0.length_squared();
709 let s1 = c1.length_squared();
710 let s2 = c2.length_squared();
711 let tol = 1.0e-4 * s0;
712 let uniform_ortho = unit_normals
713 && s0 > 1.0e-12
714 && (s0 - s1).abs() <= tol
715 && (s0 - s2).abs() <= tol
716 && c0.dot(c1).abs() <= tol
717 && c1.dot(c2).abs() <= tol
718 && c2.dot(c0).abs() <= tol;
719 let uniform_scale = if uniform_ortho { s0.sqrt() } else { 0.0 };
720
721 self.scratch.clear();
722 self.scratch.reserve(mesh.vertices.len());
723 transform_vertices(
724 &mesh.vertices,
725 item.transform,
726 camera.view_projection,
727 n0,
728 n1,
729 n2,
730 local_light,
731 light,
732 uniform_ortho,
733 uniform_scale,
734 ambient,
735 diffuse,
736 look,
737 is_authored_look,
738 clip_depth,
739 half_wf,
740 half_hf,
741 inst_fog_params,
742 &mut self.scratch,
743 );
744
745 let mirrored = det < 0.0;
746 let scratch = self.scratch.as_slice();
747 for indices in mesh.indices.as_chunks::<3>().0 {
748 stats.submitted_triangles += 1;
749 let v0 = &scratch[indices[0] as usize];
750 let v1 = &scratch[indices[1] as usize];
751 let v2 = &scratch[indices[2] as usize];
752 let union = v0.mask | v1.mask | v2.mask;
753 if (union & 0x80) != 0 || (v0.mask & v1.mask & v2.mask) != 0 {
754 continue;
755 }
756 if union == 0 {
757 stats.clipped_triangles += 1;
758 let (t0, t1, t2) = if mirrored { (v2, v1, v0) } else { (v0, v1, v2) };
759 prepare_screen_tri(
760 t0,
761 t1,
762 t2,
763 true,
764 width,
765 height,
766 half_wf,
767 half_hf,
768 cull_backfaces,
769 clip_depth,
770 inst_fog_params,
771 &mut stats,
772 &mut self.scene,
773 );
774 } else {
775 let (mut polygon, count) = clip_triangle([*v0, *v1, *v2], clip_depth, union);
776 if count < 3 {
777 continue;
778 }
779 if mirrored {
780 polygon[..count].reverse();
781 }
782 stats.clipped_triangles += (count - 2) as u64;
783 for i in 1..count - 1 {
784 prepare_screen_tri(
785 &polygon[0],
786 &polygon[i],
787 &polygon[i + 1],
788 false,
789 width,
790 height,
791 half_wf,
792 half_hf,
793 cull_backfaces,
794 clip_depth,
795 inst_fog_params,
796 &mut stats,
797 &mut self.scene,
798 );
799 }
800 }
801 }
802 }
803
804 #[cfg(not(target_arch = "wasm32"))]
805 {
806 let pixel_count = (width as usize) * (height as usize);
807 let req_threads = std::thread::available_parallelism()
808 .map(|n| n.get())
809 .unwrap_or(1)
810 .clamp(1, 8)
811 .min(height as usize);
812 if req_threads > 1 && pixel_count >= 65_536 && !self.scene.tris.is_empty() {
813 let pool = self
814 .pool
815 .get_or_insert_with(|| pool::RasterPool::new(req_threads));
816 stats.shaded_pixels += pool.render(
817 &mut self.framebuffer.pixels,
818 &mut self.framebuffer.depth,
819 width,
820 height,
821 clear_color.to_rgba(),
822 fog_params,
823 &mut self.scene,
824 );
825 return Ok(stats);
826 }
827 }
828
829 self.framebuffer.clear(clear_color);
830 if !self.scene.tris.is_empty() {
831 self.scene.sort_and_bin(height, 1);
832 stats.shaded_pixels += raster_strip(
833 &mut self.framebuffer.pixels,
834 &mut self.framebuffer.depth,
835 width as usize,
836 0,
837 height - 1,
838 &self.scene.strip_bins[0],
839 &self.scene,
840 fog_params,
841 );
842 }
843 Ok(stats)
844 }
845}
846
847#[allow(clippy::too_many_arguments)]
848fn transform_vertices(
849 vertices: &[crate::Vertex],
850 xform: crate::Mat4,
851 vp: crate::Mat4,
852 n0: Vec3,
853 n1: Vec3,
854 n2: Vec3,
855 local_light: Vec3,
856 light: Vec3,
857 uniform_ortho: bool,
858 uniform_scale: f32,
859 ambient: f32,
860 diffuse: f32,
861 look: crate::Look,
862 is_authored_look: bool,
863 clip_depth: ClipDepth,
864 half_wf: f32,
865 half_hf: f32,
866 inst_fog: Option<FogParams>,
867 out: &mut Vec<ClipVertex>,
868) {
869 let mut prev_normal = Vec3::NAN;
870 let mut prev_lighting = ambient;
871 let mut prev_color_in = Color::new(f32::NAN, f32::NAN, f32::NAN, f32::NAN);
872 let mut prev_color_out = Vec4::ZERO;
873 let mut prev_color_finite = true;
874
875 let mut shade_color = |vn: Vec3, vc: Color| -> (Vec4, bool) {
876 if vn == prev_normal && vc == prev_color_in {
877 return (prev_color_out, prev_color_finite);
878 }
879 let lighting = if vn == prev_normal {
880 prev_lighting
881 } else {
882 let d = vn.dot(local_light);
883 let n_dot_l = if d <= 0.0 {
884 0.0
885 } else if uniform_ortho {
886 d * uniform_scale
887 } else {
888 let n = n0 * vn.x + n1 * vn.y + n2 * vn.z;
889 let l2 = n.length_squared();
890 if l2 > 1.0e-20 && l2 < 1.0e20 {
891 d / l2.sqrt()
892 } else {
893 n.normalize_or_zero().dot(light).max(0.0)
894 }
895 };
896 let l = ambient + diffuse * n_dot_l;
897 prev_normal = vn;
898 prev_lighting = l;
899 l
900 };
901 let raw = Vec4::new(vc.r * lighting, vc.g * lighting, vc.b * lighting, vc.a);
902 let shaded = if is_authored_look {
903 raw
904 } else {
905 look.shade(Color::from(raw)).to_vec()
906 };
907 let fin = shaded.is_finite();
908 prev_color_in = vc;
909 prev_color_out = shaded;
910 prev_color_finite = fin;
911 (shaded, fin)
912 };
913
914 if let Some(fog) = inst_fog {
915 let cam = fog.camera_pos;
916 let start_sq = fog.start_sq;
917 let tx = xform.x_axis.truncate();
918 let ty = xform.y_axis.truncate();
919 let tz = xform.z_axis.truncate();
920 let tw = xform.w_axis.truncate();
921 for vertex in vertices {
922 let p = vertex.position;
923 let world = tx * p.x + ty * p.y + tz * p.z + tw;
924 let clip = vp.x_axis * world.x + vp.y_axis * world.y + vp.z_axis * world.z + vp.w_axis;
925 let (color, color_finite) = shade_color(vertex.normal, vertex.color);
926 let finite = color_finite && clip.is_finite() && world.is_finite();
927 let (mask, inv_w, screen_x, screen_y) = if !finite {
928 (0x80_u8, 0.0, 0.0, 0.0)
929 } else {
930 let m = clip_mask(clip, clip_depth);
931 if m == 0 {
932 let iw = clip.w.recip();
933 (
934 0,
935 iw,
936 (clip.x * iw + 1.0) * half_wf,
937 (1.0 - clip.y * iw) * half_hf,
938 )
939 } else {
940 (m, 0.0, 0.0, 0.0)
941 }
942 };
943 let fog_far = (world - cam).length_squared() > start_sq;
944 out.push(ClipVertex {
945 clip,
946 world,
947 color,
948 screen_x,
949 screen_y,
950 inv_w,
951 mask,
952 fog_far,
953 });
954 }
955 } else {
956 let mvp = vp * xform;
957 for vertex in vertices {
958 let p = vertex.position;
959 let clip = mvp.x_axis * p.x + mvp.y_axis * p.y + mvp.z_axis * p.z + mvp.w_axis;
960 let (color, color_finite) = shade_color(vertex.normal, vertex.color);
961 let finite = color_finite && clip.is_finite();
962 let (mask, inv_w, screen_x, screen_y) = if !finite {
963 (0x80_u8, 0.0, 0.0, 0.0)
964 } else {
965 let m = clip_mask(clip, clip_depth);
966 if m == 0 {
967 let iw = clip.w.recip();
968 (
969 0,
970 iw,
971 (clip.x * iw + 1.0) * half_wf,
972 (1.0 - clip.y * iw) * half_hf,
973 )
974 } else {
975 (m, 0.0, 0.0, 0.0)
976 }
977 };
978 out.push(ClipVertex {
979 clip,
980 world: Vec3::ZERO,
981 color,
982 screen_x,
983 screen_y,
984 inv_w,
985 mask,
986 fog_far: false,
987 });
988 }
989 }
990}
991
992#[inline]
993fn clip_mask(p: Vec4, depth: ClipDepth) -> u8 {
994 let near = if depth == ClipDepth::ZeroToOne {
995 p.z
996 } else {
997 p.w + p.z
998 };
999 u8::from(p.w + p.x < 0.0)
1000 | (u8::from(p.w - p.x < 0.0) << 1)
1001 | (u8::from(p.w + p.y < 0.0) << 2)
1002 | (u8::from(p.w - p.y < 0.0) << 3)
1003 | (u8::from(near < 0.0) << 4)
1004 | (u8::from(p.w - p.z < 0.0) << 5)
1005 | (u8::from(p.w - 1.0e-6 < 0.0) << 6)
1006}
1007
1008#[inline]
1009fn clip_distance(vertex: ClipVertex, plane: usize, depth: ClipDepth) -> f32 {
1010 let p = vertex.clip;
1011 match plane {
1012 0 => p.w + p.x,
1013 1 => p.w - p.x,
1014 2 => p.w + p.y,
1015 3 => p.w - p.y,
1016 4 => {
1017 if depth == ClipDepth::ZeroToOne {
1018 p.z
1019 } else {
1020 p.w + p.z
1021 }
1022 }
1023 5 => p.w - p.z,
1024 _ => p.w - 1.0e-6,
1025 }
1026}
1027
1028fn clip_triangle(
1030 triangle: [ClipVertex; 3],
1031 depth: ClipDepth,
1032 active_planes: u8,
1033) -> ([ClipVertex; CLIP_VERTEX_CAPACITY], usize) {
1034 let mut a = [ClipVertex::default(); CLIP_VERTEX_CAPACITY];
1035 let mut b = a;
1036 a[..3].copy_from_slice(&triangle);
1037 let mut count = 3;
1038 let mut planes_to_check = active_planes;
1039 for plane in 0..7 {
1040 if planes_to_check & (1 << plane) == 0 {
1041 continue;
1042 }
1043 let mut next = 0;
1044 let mut clipped_any = false;
1045 let mut previous = a[count - 1];
1046 let mut dp = clip_distance(previous, plane, depth);
1047 for i in 0..count {
1048 let current = a[i];
1049 let dc = clip_distance(current, plane, depth);
1050 if (dc >= 0.0) != (dp >= 0.0) {
1051 let ratio = (f64::from(dp) / (f64::from(dp) - f64::from(dc))) as f32;
1052 if next >= CLIP_VERTEX_CAPACITY {
1053 return (a, 0);
1054 }
1055 b[next] = previous.lerp(current, ratio.clamp(0.0, 1.0));
1056 next += 1;
1057 clipped_any = true;
1058 }
1059 if dc >= 0.0 {
1060 if next >= CLIP_VERTEX_CAPACITY {
1061 return (a, 0);
1062 }
1063 b[next] = current;
1064 next += 1;
1065 }
1066 previous = current;
1067 dp = dc;
1068 }
1069 if next < 3 {
1070 return (a, 0);
1071 }
1072 if clipped_any {
1073 planes_to_check = 0x7f;
1074 }
1075 std::mem::swap(&mut a, &mut b);
1076 count = next;
1077 }
1078 (a, count)
1079}
1080
1081#[inline]
1082#[allow(clippy::too_many_arguments)]
1083fn prepare_screen_tri(
1084 t0: &ClipVertex,
1085 t1: &ClipVertex,
1086 t2: &ClipVertex,
1087 preprojected: bool,
1088 width: u32,
1089 height: u32,
1090 half_wf: f32,
1091 half_hf: f32,
1092 cull_backfaces: bool,
1093 clip_depth: ClipDepth,
1094 fog_params: Option<FogParams>,
1095 stats: &mut RenderStats,
1096 scene: &mut SceneBuffers,
1097) {
1098 let (inv_w, screen) = if preprojected {
1099 (
1100 [t0.inv_w, t1.inv_w, t2.inv_w],
1101 [
1102 vec2(t0.screen_x, t0.screen_y),
1103 vec2(t1.screen_x, t1.screen_y),
1104 vec2(t2.screen_x, t2.screen_y),
1105 ],
1106 )
1107 } else {
1108 let iw = [t0.clip.w.recip(), t1.clip.w.recip(), t2.clip.w.recip()];
1109 (
1110 iw,
1111 [
1112 vec2(
1113 (t0.clip.x * iw[0] + 1.0) * half_wf,
1114 (1.0 - t0.clip.y * iw[0]) * half_hf,
1115 ),
1116 vec2(
1117 (t1.clip.x * iw[1] + 1.0) * half_wf,
1118 (1.0 - t1.clip.y * iw[1]) * half_hf,
1119 ),
1120 vec2(
1121 (t2.clip.x * iw[2] + 1.0) * half_wf,
1122 (1.0 - t2.clip.y * iw[2]) * half_hf,
1123 ),
1124 ],
1125 )
1126 };
1127
1128 let e1 = screen[1] - screen[0];
1129 let e2 = screen[2] - screen[0];
1130 let area = e1.perp_dot(e2);
1131 if !area.is_finite() || area.abs() < 1.0e-6 || (cull_backfaces && area >= 0.0) {
1132 return;
1133 }
1134 stats.rasterized_triangles += 1;
1135
1136 let min_xf = screen[0].x.min(screen[1].x).min(screen[2].x);
1137 let max_xf = screen[0].x.max(screen[1].x).max(screen[2].x);
1138 let min_yf = screen[0].y.min(screen[1].y).min(screen[2].y);
1139 let max_yf = screen[0].y.max(screen[1].y).max(screen[2].y);
1140 let (min_x, max_x, mut min_y, mut max_y) = if preprojected {
1141 (
1142 (min_xf as i32).clamp(0, width as i32 - 1),
1143 (max_xf as i32 + 1).clamp(0, width as i32 - 1),
1144 (min_yf as i32).clamp(0, height as i32 - 1) as u32,
1145 (max_yf as i32 + 1).clamp(0, height as i32 - 1) as u32,
1146 )
1147 } else {
1148 (
1149 (min_xf.floor() as i64).clamp(0, i64::from(width) - 1) as i32,
1150 (max_xf.ceil() as i64).clamp(0, i64::from(width) - 1) as i32,
1151 (min_yf.floor() as i64).clamp(0, i64::from(height) - 1) as u32,
1152 (max_yf.ceil() as i64).clamp(0, i64::from(height) - 1) as u32,
1153 )
1154 };
1155
1156 let sign = if area > 0.0 { 1.0_f64 } else { -1.0_f64 };
1157 let mut lx = [-1.0_f64; 2];
1158 let mut ldx = [0.0_f64; 2];
1159 let mut rx = [f64::from(width) + 1.0; 2];
1160 let mut rdx = [0.0_f64; 2];
1161 let mut n_left = 0_usize;
1162 let mut n_right = 0_usize;
1163 let edges = [
1164 (screen[1], screen[2]),
1165 (screen[2], screen[0]),
1166 (screen[0], screen[1]),
1167 ];
1168 for (pa, pb) in edges {
1169 let pax = f64::from(pa.x);
1170 let pay = f64::from(pa.y);
1171 let dx = f64::from(pb.x) - pax;
1172 let dy = f64::from(pb.y) - pay;
1173 let a = -dy * sign;
1174 if a > 1.0e-20 {
1175 let slope = dx / dy;
1176 let x0 = (pax - 0.5) + slope * (0.5 - pay);
1177 lx[n_left] = x0;
1178 ldx[n_left] = slope;
1179 n_left += 1;
1180 } else if a < -1.0e-20 {
1181 let slope = dx / dy;
1182 let x0 = (pax - 0.5) + slope * (0.5 - pay);
1183 rx[n_right] = x0;
1184 rdx[n_right] = slope;
1185 n_right += 1;
1186 } else {
1187 let b = dx * sign;
1188 let y_edge = pay - 0.5;
1189 if b > 1.0e-20 {
1190 if y_edge > f64::from(max_y) {
1191 return;
1192 }
1193 if y_edge > f64::from(min_y) {
1194 min_y = y_edge.ceil() as u32;
1195 }
1196 } else if b < -1.0e-20 {
1197 if y_edge < f64::from(min_y) {
1198 return;
1199 }
1200 if y_edge < f64::from(max_y) {
1201 max_y = y_edge.floor() as u32;
1202 }
1203 }
1204 }
1205 }
1206 if min_y > max_y {
1207 return;
1208 }
1209
1210 let z0_raw = f64::from(t0.clip.z * inv_w[0]);
1211 let z1_raw = f64::from(t1.clip.z * inv_w[1]);
1212 let z2_raw = f64::from(t2.clip.z * inv_w[2]);
1213 let (z0, z1, z2) = if clip_depth == ClipDepth::NegativeOneToOne {
1214 (z0_raw * 0.5 + 0.5, z1_raw * 0.5 + 0.5, z2_raw * 0.5 + 0.5)
1215 } else {
1216 (z0_raw, z1_raw, z2_raw)
1217 };
1218 let e1x = f64::from(screen[1].x) - f64::from(screen[0].x);
1219 let e1y = f64::from(screen[1].y) - f64::from(screen[0].y);
1220 let e2x = f64::from(screen[2].x) - f64::from(screen[0].x);
1221 let e2y = f64::from(screen[2].y) - f64::from(screen[0].y);
1222 let inv_area64 = 1.0_f64 / (e1x * e2y - e1y * e2x);
1223 let dz1 = z1 - z0;
1224 let dz2 = z2 - z0;
1225 let dz_dx64 = (dz1 * e2y - dz2 * e1y) * inv_area64;
1226 let dz_dy = (e1x * dz2 - e2x * dz1) * inv_area64;
1227 let ox0 = 0.5 - f64::from(screen[0].x);
1228 let oy0 = 0.5 - f64::from(screen[0].y);
1229 let z_base = z0 + dz_dx64 * ox0 + dz_dy * oy0;
1230 let dz_dx = dz_dx64 as f32;
1231
1232 let fog_active = fog_params.is_some() && (t0.fog_far || t1.fog_far || t2.fog_far);
1233 let same_color = t0.color == t1.color && t0.color == t2.color;
1234
1235 let shading = if same_color && !fog_active {
1236 let c = t0.color;
1237 if c.w <= 0.0 {
1238 return;
1239 }
1240 TriShading::FlatOpaque([
1241 (c.x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1242 (c.y.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1243 (c.z.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1244 255,
1245 ])
1246 } else if same_color {
1247 let c = t0.color;
1248 if c.w <= 0.0 {
1249 return;
1250 }
1251 let fog = fog_params.expect("fog_active requires fog");
1252 let base_rgb255 = [
1253 c.x.clamp(0.0, 1.0) * 255.0,
1254 c.y.clamp(0.0, 1.0) * 255.0,
1255 c.z.clamp(0.0, 1.0) * 255.0,
1256 ];
1257 let rgba = [
1258 (base_rgb255[0] + 0.5) as u8,
1259 (base_rgb255[1] + 0.5) as u8,
1260 (base_rgb255[2] + 0.5) as u8,
1261 255,
1262 ];
1263 let delta_rgb255 = [
1264 fog.color_rgb255[0] - base_rgb255[0],
1265 fog.color_rgb255[1] - base_rgb255[1],
1266 fog.color_rgb255[2] - base_rgb255[2],
1267 ];
1268 let inv_area = inv_area64 as f32;
1269 let ox = 0.5 - screen[0].x;
1270 let oy = 0.5 - screen[0].y;
1271 let dq1 = inv_w[1] - inv_w[0];
1272 let dq2 = inv_w[2] - inv_w[0];
1273 let dq_dx = (dq1 * e2.y - dq2 * e1.y) * inv_area;
1274 let dq_dy = (e1.x * dq2 - e2.x * dq1) * inv_area;
1275 let q_base = inv_w[0] + dq_dx * ox + dq_dy * oy;
1276 let wq0 = (t0.world - fog.camera_pos) * inv_w[0];
1277 let dwq1 = (t1.world - fog.camera_pos) * inv_w[1] - wq0;
1278 let dwq2 = (t2.world - fog.camera_pos) * inv_w[2] - wq0;
1279 let dwq_dx = (dwq1 * e2.y - dwq2 * e1.y) * inv_area;
1280 let dwq_dy = (dwq2 * e1.x - dwq1 * e2.x) * inv_area;
1281 let wq_base = wq0 + dwq_dx * ox + dwq_dy * oy;
1282 let idx = scene.fog_tris.len() as u32;
1283 scene.fog_tris.push(FlatFogData {
1284 rgba,
1285 fog_rgba: fog.color_rgba,
1286 base_rgb255,
1287 delta_rgb255,
1288 q_base,
1289 dq_dx,
1290 dq_dy,
1291 wq_base,
1292 dwq_dx,
1293 dwq_dy,
1294 });
1295 TriShading::FlatFog(idx)
1296 } else {
1297 let inv_area = inv_area64 as f32;
1298 let ox = 0.5 - screen[0].x;
1299 let oy = 0.5 - screen[0].y;
1300 let dq1 = inv_w[1] - inv_w[0];
1301 let dq2 = inv_w[2] - inv_w[0];
1302 let dq_dx = (dq1 * e2.y - dq2 * e1.y) * inv_area;
1303 let dq_dy = (e1.x * dq2 - e2.x * dq1) * inv_area;
1304 let q_base = inv_w[0] + dq_dx * ox + dq_dy * oy;
1305 let cq0 = t0.color * inv_w[0];
1306 let dcq1 = t1.color * inv_w[1] - cq0;
1307 let dcq2 = t2.color * inv_w[2] - cq0;
1308 let dcq_dx = (dcq1 * e2.y - dcq2 * e1.y) * inv_area;
1309 let dcq_dy = (dcq2 * e1.x - dcq1 * e2.x) * inv_area;
1310 let cq_base = cq0 + dcq_dx * ox + dcq_dy * oy;
1311 let (wq_base, dwq_dx, dwq_dy) = if fog_active {
1312 let wq0 = t0.world * inv_w[0];
1313 let dwq1 = t1.world * inv_w[1] - wq0;
1314 let dwq2 = t2.world * inv_w[2] - wq0;
1315 let dx = (dwq1 * e2.y - dwq2 * e1.y) * inv_area;
1316 let dy = (dwq2 * e1.x - dwq1 * e2.x) * inv_area;
1317 (wq0 + dx * ox + dy * oy, dx, dy)
1318 } else {
1319 (Vec3::ZERO, Vec3::ZERO, Vec3::ZERO)
1320 };
1321 let idx = scene.var_tris.len() as u32;
1322 scene.var_tris.push(VaryingData {
1323 fog: fog_active,
1324 q_base,
1325 dq_dx,
1326 dq_dy,
1327 cq_base,
1328 dcq_dx,
1329 dcq_dy,
1330 wq_base,
1331 dwq_dx,
1332 dwq_dy,
1333 });
1334 TriShading::Varying(idx)
1335 };
1336
1337 let min_z64 = z0.min(z1).min(z2);
1338 let max_z64 = z0.max(z1).max(z2);
1339 let z_in_unit = min_z64 >= 1.0e-6 && max_z64 <= 1.0 - 1.0e-6;
1340 let min_z = (min_z64 as f32).clamp(0.0, 1.0);
1341 let tri_idx = scene.tris.len() as u32;
1342 scene
1343 .order
1344 .push((u64::from(min_z.to_bits()) << 32) | u64::from(tri_idx));
1345 scene.tris.push(ScreenTri {
1346 lx,
1347 ldx,
1348 rx,
1349 rdx,
1350 z_base,
1351 dz_dy,
1352 dz_dx,
1353 min_x,
1354 max_x,
1355 min_y: min_y as u16,
1356 max_y: max_y as u16,
1357 shading,
1358 z_in_unit,
1359 });
1360}
1361
1362#[inline]
1363#[allow(clippy::too_many_arguments)]
1364fn span_bounds(
1365 lx0: f64,
1366 lx1: f64,
1367 rx0: f64,
1368 rx1: f64,
1369 min_x: i32,
1370 max_x: i32,
1371 min_xf: f64,
1372 max_xf: f64,
1373) -> Option<(usize, usize)> {
1374 let x0_f = lx0.max(lx1);
1375 let x1_f = rx0.min(rx1);
1376 if x0_f > max_xf || x1_f < min_xf || x0_f > x1_f {
1377 return None;
1378 }
1379 let x0 = if x0_f <= min_xf {
1380 min_x
1381 } else {
1382 x0_f.ceil() as i32
1383 };
1384 let x1 = if x1_f >= max_xf {
1385 max_x
1386 } else {
1387 x1_f.floor() as i32
1388 };
1389 if x0 <= x1 {
1390 Some((x0 as usize, x1 as usize))
1391 } else {
1392 None
1393 }
1394}
1395
1396#[inline]
1397fn fill_flat_span(
1398 d_span: &mut [f32],
1399 p_span: &mut [[u8; 4]],
1400 z0: f32,
1401 z1: f32,
1402 dz_dx: f32,
1403 rgba: [u8; 4],
1404 z_in_unit: bool,
1405) -> u64 {
1406 let mut shaded = 0_u64;
1407 if z_in_unit || ((0.0..=1.0).contains(&z0) && (0.0..=1.0).contains(&z1)) {
1408 let step8 = dz_dx * 8.0;
1409 let mut zv = [
1410 z0,
1411 z0 + dz_dx,
1412 z0 + dz_dx * 2.0,
1413 z0 + dz_dx * 3.0,
1414 z0 + dz_dx * 4.0,
1415 z0 + dz_dx * 5.0,
1416 z0 + dz_dx * 6.0,
1417 z0 + dz_dx * 7.0,
1418 ];
1419 let mut d_chunks = d_span.chunks_exact_mut(8);
1420 let mut p_chunks = p_span.chunks_exact_mut(8);
1421 for (dc, pc) in d_chunks.by_ref().zip(p_chunks.by_ref()) {
1422 let pass = [
1423 zv[0] < dc[0],
1424 zv[1] < dc[1],
1425 zv[2] < dc[2],
1426 zv[3] < dc[3],
1427 zv[4] < dc[4],
1428 zv[5] < dc[5],
1429 zv[6] < dc[6],
1430 zv[7] < dc[7],
1431 ];
1432 let all = pass[0] & pass[1] & pass[2] & pass[3] & pass[4] & pass[5] & pass[6] & pass[7];
1433 if all {
1434 dc.copy_from_slice(&zv);
1435 pc.fill(rgba);
1436 shaded += 8;
1437 } else if pass[0] | pass[1] | pass[2] | pass[3] | pass[4] | pass[5] | pass[6] | pass[7]
1438 {
1439 let mut hits = 0_u32;
1440 for i in 0..8 {
1441 if pass[i] {
1442 dc[i] = zv[i];
1443 pc[i] = rgba;
1444 hits += 1;
1445 }
1446 }
1447 shaded += u64::from(hits);
1448 }
1449 for z in &mut zv {
1450 *z += step8;
1451 }
1452 }
1453 let mut z = zv[0];
1454 for (d, p) in d_chunks
1455 .into_remainder()
1456 .iter_mut()
1457 .zip(p_chunks.into_remainder().iter_mut())
1458 {
1459 if z < *d {
1460 *d = z;
1461 *p = rgba;
1462 shaded += 1;
1463 }
1464 z += dz_dx;
1465 }
1466 } else {
1467 let mut z = z0;
1468 for (d, p) in d_span.iter_mut().zip(p_span.iter_mut()) {
1469 if z.is_finite() && (0.0..=1.00001).contains(&z) && z < *d {
1470 *d = z.clamp(0.0, 1.0);
1471 *p = rgba;
1472 shaded += 1;
1473 }
1474 z += dz_dx;
1475 }
1476 }
1477 shaded
1478}
1479
1480#[inline(always)]
1481fn fog_pixel(fd: &FlatFogData, a: f32) -> [u8; 4] {
1482 [
1483 (fd.base_rgb255[0] + fd.delta_rgb255[0] * a + 0.5) as u8,
1484 (fd.base_rgb255[1] + fd.delta_rgb255[1] * a + 0.5) as u8,
1485 (fd.base_rgb255[2] + fd.delta_rgb255[2] * a + 0.5) as u8,
1486 255,
1487 ]
1488}
1489
1490#[inline(always)]
1491fn write_const_chunk(
1492 dc: &mut [f32],
1493 pc: &mut [[u8; 4]],
1494 zv: &[f32; 8],
1495 pass: &[bool; 8],
1496 all: bool,
1497 rgba: [u8; 4],
1498) -> u64 {
1499 if all {
1500 dc.copy_from_slice(zv);
1501 pc.fill(rgba);
1502 8
1503 } else {
1504 let mut hits = 0_u32;
1505 for i in 0..8 {
1506 if pass[i] {
1507 dc[i] = zv[i];
1508 pc[i] = rgba;
1509 hits += 1;
1510 }
1511 }
1512 u64::from(hits)
1513 }
1514}
1515
1516#[allow(clippy::too_many_arguments)]
1517fn raster_strip(
1518 pixels: &mut [[u8; 4]],
1519 depths: &mut [f32],
1520 stride: usize,
1521 y_start: u32,
1522 y_end: u32,
1523 bin: &[u32],
1524 scene: &SceneBuffers,
1525 fog_params: Option<FogParams>,
1526) -> u64 {
1527 let mut shaded = 0_u64;
1528 for &idx in bin {
1529 let tri = &scene.tris[idx as usize];
1530 let ys = u32::from(tri.min_y).max(y_start);
1531 let ye = u32::from(tri.max_y).min(y_end);
1532 let ys_f = ys as f32;
1533 let ys_64 = f64::from(ys);
1534 let mut lx0 = tri.lx[0] + tri.ldx[0] * ys_64;
1535 let mut lx1 = tri.lx[1] + tri.ldx[1] * ys_64;
1536 let mut rx0 = tri.rx[0] + tri.rdx[0] * ys_64;
1537 let mut rx1 = tri.rx[1] + tri.rdx[1] * ys_64;
1538 let min_x = tri.min_x;
1539 let max_x = tri.max_x;
1540 let min_xf = f64::from(min_x);
1541 let max_xf = f64::from(max_x);
1542 let mut z_row = tri.z_base + tri.dz_dy * ys_64;
1543 let dz_dx = tri.dz_dx;
1544 let z_in_unit = tri.z_in_unit;
1545
1546 match tri.shading {
1547 TriShading::FlatOpaque(rgba) => {
1548 for y in ys..=ye {
1549 if let Some((x0, x1)) =
1550 span_bounds(lx0, lx1, rx0, rx1, min_x, max_x, min_xf, max_xf)
1551 {
1552 let base = (y - y_start) as usize * stride;
1553 let z_row_f = z_row as f32;
1554 let z0 = z_row_f + dz_dx * (x0 as f32);
1555 let z1 = z_row_f + dz_dx * (x1 as f32);
1556 shaded += fill_flat_span(
1557 &mut depths[base + x0..=base + x1],
1558 &mut pixels[base + x0..=base + x1],
1559 z0,
1560 z1,
1561 dz_dx,
1562 rgba,
1563 z_in_unit,
1564 );
1565 }
1566 lx0 += tri.ldx[0];
1567 lx1 += tri.ldx[1];
1568 rx0 += tri.rdx[0];
1569 rx1 += tri.rdx[1];
1570 z_row += tri.dz_dy;
1571 }
1572 }
1573 TriShading::FlatFog(fog_idx) => {
1574 let fd = scene.fog_tris[fog_idx as usize];
1575 let fog = fog_params.expect("FlatFog requires fog");
1576 let mut q_row = fd.q_base + fd.dq_dy * ys_f;
1577 let mut wq_row = fd.wq_base + fd.dwq_dy * ys_f;
1578 for y in ys..=ye {
1579 if let Some((x0, x1)) =
1580 span_bounds(lx0, lx1, rx0, rx1, min_x, max_x, min_xf, max_xf)
1581 {
1582 let base = (y - y_start) as usize * stride;
1583 let d_span = &mut depths[base + x0..=base + x1];
1584 let p_span = &mut pixels[base + x0..=base + x1];
1585 let x0_f = x0 as f32;
1586 let x1_f = x1 as f32;
1587 let z_row_f = z_row as f32;
1588 let z0 = z_row_f + dz_dx * x0_f;
1589 let z1 = z_row_f + dz_dx * x1_f;
1590 let qa = q_row + fd.dq_dx * x0_f;
1591 let qb = q_row + fd.dq_dx * x1_f;
1592 let rqa = wq_row + fd.dwq_dx * x0_f;
1593 let rqb = wq_row + fd.dwq_dx * x1_f;
1594 if qa > 0.0
1595 && qb > 0.0
1596 && rqa.length_squared() <= fog.start_sq * qa * qa
1597 && rqb.length_squared() <= fog.start_sq * qb * qb
1598 {
1599 shaded +=
1600 fill_flat_span(d_span, p_span, z0, z1, dz_dx, fd.rgba, z_in_unit);
1601 lx0 += tri.ldx[0];
1602 lx1 += tri.ldx[1];
1603 rx0 += tri.rdx[0];
1604 rx1 += tri.rdx[1];
1605 z_row += tri.dz_dy;
1606 q_row += fd.dq_dy;
1607 wq_row += fd.dwq_dy;
1608 continue;
1609 }
1610 let z_ok =
1611 z_in_unit || ((0.0..=1.0).contains(&z0) && (0.0..=1.0).contains(&z1));
1612 if z_ok && qa > 0.0 && qb > 0.0 {
1613 let step8_z = dz_dx * 8.0;
1614 let step8_q = fd.dq_dx * 8.0;
1615 let step8_r = fd.dwq_dx * 8.0;
1616 let mut zv = [
1617 z0,
1618 z0 + dz_dx,
1619 z0 + dz_dx * 2.0,
1620 z0 + dz_dx * 3.0,
1621 z0 + dz_dx * 4.0,
1622 z0 + dz_dx * 5.0,
1623 z0 + dz_dx * 6.0,
1624 z0 + dz_dx * 7.0,
1625 ];
1626 let mut q_c = qa;
1627 let mut r_c = rqa;
1628 let mut prev_end_valid = false;
1629 let mut prev_end_amt = 0.0_f32;
1630 let mut d_chunks = d_span.chunks_exact_mut(8);
1631 let mut p_chunks = p_span.chunks_exact_mut(8);
1632 for (dc, pc) in d_chunks.by_ref().zip(p_chunks.by_ref()) {
1633 let pass = [
1634 zv[0] < dc[0],
1635 zv[1] < dc[1],
1636 zv[2] < dc[2],
1637 zv[3] < dc[3],
1638 zv[4] < dc[4],
1639 zv[5] < dc[5],
1640 zv[6] < dc[6],
1641 zv[7] < dc[7],
1642 ];
1643 let all = pass[0]
1644 & pass[1]
1645 & pass[2]
1646 & pass[3]
1647 & pass[4]
1648 & pass[5]
1649 & pass[6]
1650 & pass[7];
1651 let any = all
1652 | (pass[0]
1653 | pass[1]
1654 | pass[2]
1655 | pass[3]
1656 | pass[4]
1657 | pass[5]
1658 | pass[6]
1659 | pass[7]);
1660 if any {
1661 let q_next = q_c + step8_q;
1662 let r_next = r_c + step8_r;
1663 if (q_next - q_c).abs() <= 0.05 * q_c.min(q_next) {
1664 let a0 = if prev_end_valid {
1665 prev_end_amt
1666 } else {
1667 ((r_c.length_squared().sqrt() / q_c - fog.start)
1668 * fog.inv_range)
1669 .clamp(0.0, 1.0)
1670 };
1671 let a8 = ((r_next.length_squared().sqrt() / q_next
1672 - fog.start)
1673 * fog.inv_range)
1674 .clamp(0.0, 1.0);
1675 prev_end_valid = true;
1676 prev_end_amt = a8;
1677 if a0 == 0.0 && a8 == 0.0 {
1678 shaded +=
1679 write_const_chunk(dc, pc, &zv, &pass, all, fd.rgba);
1680 } else if a0 == 1.0 && a8 == 1.0 {
1681 shaded += write_const_chunk(
1682 dc,
1683 pc,
1684 &zv,
1685 &pass,
1686 all,
1687 fd.fog_rgba,
1688 );
1689 } else {
1690 let da = (a8 - a0) * 0.125;
1691 let mut a = a0;
1692 if all {
1693 dc.copy_from_slice(&zv);
1694 for p in pc.iter_mut() {
1695 *p = fog_pixel(&fd, a);
1696 a += da;
1697 }
1698 shaded += 8;
1699 } else {
1700 let mut hits = 0_u32;
1701 for i in 0..8 {
1702 if pass[i] {
1703 pc[i] = fog_pixel(&fd, a);
1704 dc[i] = zv[i];
1705 hits += 1;
1706 }
1707 a += da;
1708 }
1709 shaded += u64::from(hits);
1710 }
1711 }
1712 } else {
1713 prev_end_valid = false;
1714 let mut q = q_c;
1715 let mut r = r_c;
1716 let mut hits = 0_u32;
1717 for i in 0..8 {
1718 if pass[i] {
1719 let a = ((r.length_squared().sqrt() / q
1720 - fog.start)
1721 * fog.inv_range)
1722 .clamp(0.0, 1.0);
1723 pc[i] = fog_pixel(&fd, a);
1724 dc[i] = zv[i];
1725 hits += 1;
1726 }
1727 q += fd.dq_dx;
1728 r += fd.dwq_dx;
1729 }
1730 shaded += u64::from(hits);
1731 }
1732 } else {
1733 prev_end_valid = false;
1734 }
1735 for z in &mut zv {
1736 *z += step8_z;
1737 }
1738 q_c += step8_q;
1739 r_c += step8_r;
1740 }
1741 let mut z = zv[0];
1742 let mut q = q_c;
1743 let mut r = r_c;
1744 for (d, p) in d_chunks
1745 .into_remainder()
1746 .iter_mut()
1747 .zip(p_chunks.into_remainder().iter_mut())
1748 {
1749 if z < *d {
1750 let a = ((r.length_squared().sqrt() / q - fog.start)
1751 * fog.inv_range)
1752 .clamp(0.0, 1.0);
1753 *p = fog_pixel(&fd, a);
1754 *d = z;
1755 shaded += 1;
1756 }
1757 z += dz_dx;
1758 q += fd.dq_dx;
1759 r += fd.dwq_dx;
1760 }
1761 } else {
1762 let mut z = z0;
1763 for (offset, (d, p)) in
1764 d_span.iter_mut().zip(p_span.iter_mut()).enumerate()
1765 {
1766 if z.is_finite() && (0.0..=1.00001).contains(&z) && z < *d {
1767 let xf = (x0 + offset) as f32;
1768 let q = q_row + fd.dq_dx * xf;
1769 if q.is_finite() && q > 0.0 {
1770 let rq = wq_row + fd.dwq_dx * xf;
1771 let a = ((rq.length_squared().sqrt() / q - fog.start)
1772 * fog.inv_range)
1773 .clamp(0.0, 1.0);
1774 *p = fog_pixel(&fd, a);
1775 *d = z.clamp(0.0, 1.0);
1776 shaded += 1;
1777 }
1778 }
1779 z += dz_dx;
1780 }
1781 }
1782 }
1783 lx0 += tri.ldx[0];
1784 lx1 += tri.ldx[1];
1785 rx0 += tri.rdx[0];
1786 rx1 += tri.rdx[1];
1787 z_row += tri.dz_dy;
1788 q_row += fd.dq_dy;
1789 wq_row += fd.dwq_dy;
1790 }
1791 }
1792 TriShading::Varying(var_idx) => {
1793 let vd = scene.var_tris[var_idx as usize];
1794 let mut q_row = vd.q_base + vd.dq_dy * ys_f;
1795 let mut cq_row = vd.cq_base + vd.dcq_dy * ys_f;
1796 let mut wq_row = vd.wq_base + vd.dwq_dy * ys_f;
1797 for y in ys..=ye {
1798 if let Some((x0, x1)) =
1799 span_bounds(lx0, lx1, rx0, rx1, min_x, max_x, min_xf, max_xf)
1800 {
1801 let base = (y - y_start) as usize * stride;
1802 let d_span = &mut depths[base + x0..=base + x1];
1803 let p_span = &mut pixels[base + x0..=base + x1];
1804 let x0_f = x0 as f32;
1805 let mut z = z_row as f32 + dz_dx * x0_f;
1806 for (offset, (d, p)) in d_span.iter_mut().zip(p_span.iter_mut()).enumerate()
1807 {
1808 if z.is_finite() && (0.0..=1.00001).contains(&z) && z < *d {
1809 let xf = (x0 + offset) as f32;
1810 let q = q_row + vd.dq_dx * xf;
1811 if q.is_finite() && q > 0.0 {
1812 let inv_q = q.recip();
1813 let mut color = (cq_row + vd.dcq_dx * xf) * inv_q;
1814 if color.w > 0.0 {
1815 if vd.fog
1816 && let Some(fog) = fog_params
1817 {
1818 let pos = (wq_row + vd.dwq_dx * xf) * inv_q;
1819 let amount = ((pos.distance(fog.camera_pos)
1820 - fog.start)
1821 * fog.inv_range)
1822 .clamp(0.0, 1.0);
1823 color = color.lerp(fog.color, amount);
1824 }
1825 color.w = 1.0;
1826 *p = Color::from(color).to_rgba();
1827 *d = z.clamp(0.0, 1.0);
1828 shaded += 1;
1829 }
1830 }
1831 }
1832 z += dz_dx;
1833 }
1834 }
1835 lx0 += tri.ldx[0];
1836 lx1 += tri.ldx[1];
1837 rx0 += tri.rdx[0];
1838 rx1 += tri.rdx[1];
1839 z_row += tri.dz_dy;
1840 q_row += vd.dq_dy;
1841 cq_row += vd.dcq_dy;
1842 wq_row += vd.dwq_dy;
1843 }
1844 }
1845 }
1846 }
1847 shaded
1848}