three-rs 0.3.0

A port of three.js core and its WebGPURenderer to Rust on wgpu, graded against three.js's own end-to-end pixel comparison.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Port of `three.js/src/objects/BatchedMesh.js` — the subset
//! `webgpu_mesh_batch` exercises: geometry ranges packed into one
//! `BufferGeometry`, per-instance matrices and colours in `DataTexture`s, the
//! per-instance frustum cull and the sorted draw list `onBeforeRender()` builds.
//!
//! Under `WebGPURenderer` there is no multi-draw and no indirect draw: the
//! backend walks `_multiDrawStarts` / `_multiDrawCounts` and issues one
//! ordinary `drawIndexed( count, 1, start / bytesPerElement, 0, i )` per
//! range, with `firstInstance = i` — the *draw ordinal*, which is what
//! `@builtin(instance_index)` reads and what `_indirectTexture` maps back to an
//! instance id. See `docs/rung11-progress.md`.

use std::rc::Rc;

use crate::core::{
    ArrayKind, BufferAttribute, BufferGeometry, Index, Object3D, ObjectRef, TypedArray,
};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Box3, CoordinateSystem, Frustum, Matrix4, Sphere, Vector3};
use crate::nodes::batch::BatchEntry;
use crate::objects::{Mesh, Payload};
use crate::textures::DataTexture;

/// One entry of `_geometryInfo`.
#[derive(Clone, Debug)]
pub struct GeometryInfo {
    /// The first vertex of this geometry's range in the packed buffer.
    pub vertex_start: usize,
    /// How many vertices of the geometry were actually written.
    pub vertex_count: usize,
    /// How many vertices the range reserves, which may exceed `vertex_count`.
    pub reserved_vertex_count: usize,
    /// `-1` when the batch geometry is not indexed.
    pub index_start: isize,
    /// How many indices of the geometry were actually written.
    pub index_count: usize,
    /// How many indices the range reserves, which may exceed `index_count`.
    pub reserved_index_count: usize,
    /// The draw range: `indexStart` / `indexCount` for an indexed batch.
    pub start: usize,
    /// The draw range's count.
    pub count: usize,
    pub(crate) bounding_box: Option<Box3>,
    pub(crate) bounding_sphere: Option<Sphere>,
    pub(crate) active: bool,
}

/// One entry of `_instanceInfo`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct InstanceInfo {
    pub visible: bool,
    pub active: bool,
    pub geometry_index: usize,
}

/// One entry of `MultiDrawRenderList.list`.
#[derive(Clone, Copy, Debug)]
pub struct MultiDrawItem {
    /// The draw range's start.
    pub start: usize,
    /// The draw range's count.
    pub count: usize,
    /// The sort depth, camera-space.
    pub z: f64,
    /// The instance id this draw item belongs to.
    pub index: usize,
}

/// What the page's `sortFunction` reads off `this` and `camera`. three.js calls
/// the custom sort with `this` bound to the mesh and the camera as the second
/// argument; the port hands it only the two values any sort on the ladder uses.
#[derive(Clone, Copy, Debug)]
pub struct SortContext {
    /// `camera.far`.
    pub camera_far: f64,
    /// `this.material.transparent`, which the page uses as `options.reversed`.
    pub transparent: bool,
    /// `this.maxInstanceCount`, the page's `options.aux` length.
    pub max_instance_count: usize,
}

/// `BatchedMesh.customSort`.
pub type CustomSort = Rc<dyn Fn(&mut Vec<MultiDrawItem>, &SortContext)>;

/// One `drawIndexed()` the backend issues for this batch.
#[derive(Clone, Copy, Debug)]
#[doc(hidden)]
pub struct SubDraw {
    pub first_index: u32,
    pub index_count: u32,
    /// `firstInstance` — the draw ordinal, not the instance id.
    pub first_instance: u32,
}

/// The camera state `onBeforeRender()` needs.
#[derive(Clone, Copy, Debug)]
pub struct BatchCamera {
    /// `camera.projectionMatrix`.
    pub projection_matrix: Matrix4,
    /// `camera.matrixWorldInverse`.
    pub matrix_world_inverse: Matrix4,
    /// `camera.matrixWorld`.
    pub matrix_world: Matrix4,
    /// `camera.coordinateSystem`.
    pub coordinate_system: CoordinateSystem,
    /// `camera.far`.
    pub far: f64,
}

/// `BatchedMesh extends Mesh`.
#[derive(Clone)]
pub struct BatchedMesh {
    /// The `Mesh` half: geometry, material and morph state.
    pub mesh: Mesh,
    /// `_perObjectFrustumCulled` — whether each instance is culled by its own
    /// bounding sphere.
    pub per_object_frustum_culled: bool,
    /// `_sortObjects` — whether instances are depth-sorted before drawing.
    pub sort_objects: bool,
    /// `customSort`, set by [`set_custom_sort`](Self::set_custom_sort).
    pub custom_sort: Option<CustomSort>,

    instance_info: Vec<InstanceInfo>,
    geometry_info: Vec<GeometryInfo>,

    next_index_start: usize,
    next_vertex_start: usize,
    geometry_count: usize,

    visibility_changed: bool,
    geometry_initialized: bool,

    max_instance_count: usize,
    max_vertex_count: usize,
    max_index_count: usize,

    /// `_multiDrawStarts` — in *bytes*, as three.js keeps them.
    multi_draw_starts: Vec<i32>,
    multi_draw_counts: Vec<i32>,
    multi_draw_count: usize,
    multi_draw_bytes_per_element: usize,

    /// three.js' module-level `_vector`, reproduced as state because
    /// `getBoundingBoxAt()` / `getBoundingSphereAt()` overwrite it while they
    /// lazily compute a geometry's bounds, and `onBeforeRender()`'s sort reads
    /// it afterwards as if it still held the camera position. See
    /// `docs/rung11-progress.md`.
    shared_vector: Vector3,

    matrices_texture: DataTexture,
    indirect_texture: DataTexture,
    colors_texture: Option<DataTexture>,
}

impl BatchedMesh {
    /// `new BatchedMesh( maxInstanceCount, maxVertexCount, maxIndexCount, material )`,
    /// as a scene-graph [`ObjectRef`].
    #[allow(clippy::new_ret_no_self)] // mirrors three.js' constructor, which returns the object the scene holds
    pub fn new(
        max_instance_count: usize,
        max_vertex_count: usize,
        max_index_count: usize,
        material: MeshBasicNodeMaterial,
    ) -> ObjectRef {
        let mut object = Object3D {
            object_type: "BatchedMesh",
            ..Default::default()
        };
        object.payload = Payload::BatchedMesh(Box::new(Self {
            mesh: Mesh {
                geometry: Rc::new(BufferGeometry::new()),
                material: Some(material),
                materials: Vec::new(),
                morph_target_influences: Vec::new(),
                line_segments: None,
                count: None,
            },
            per_object_frustum_culled: true,
            sort_objects: true,
            custom_sort: None,
            instance_info: Vec::new(),
            geometry_info: Vec::new(),
            next_index_start: 0,
            next_vertex_start: 0,
            geometry_count: 0,
            visibility_changed: true,
            geometry_initialized: false,
            max_instance_count,
            max_vertex_count,
            max_index_count,
            multi_draw_starts: vec![0; max_instance_count],
            multi_draw_counts: vec![0; max_instance_count],
            multi_draw_count: 0,
            multi_draw_bytes_per_element: 1,
            shared_vector: Vector3::ZERO,
            matrices_texture: init_matrices_texture(max_instance_count),
            indirect_texture: init_indirect_texture(max_instance_count),
            colors_texture: None,
        }));
        object.into_node()
    }

    /// `maxInstanceCount`.
    pub fn max_instance_count(&self) -> usize {
        self.max_instance_count
    }

    /// `instanceCount` — the number of active instances.
    pub fn instance_count(&self) -> usize {
        self.instance_info.iter().filter(|i| i.active).count()
    }

    /// The packed geometry every instance draws a range of.
    pub fn geometry(&self) -> &Rc<BufferGeometry> {
        &self.mesh.geometry
    }

    /// `getGeometryRangeAt( geometryId )` — the packed range this geometry
    /// owns inside the shared `BufferGeometry`.
    pub fn geometry_range_at(&self, geometry_id: usize) -> Option<&GeometryInfo> {
        self.geometry_info
            .get(geometry_id)
            .filter(|info| info.active)
    }

    /// The three textures the node system binds.
    #[doc(hidden)]
    pub fn batch_entry(&self) -> BatchEntry {
        BatchEntry {
            indirect: self.indirect_texture.clone(),
            matrices: self.matrices_texture.clone(),
            colors: self.colors_texture.clone(),
        }
    }

    /// `_multiDrawCount` sub-ranges as `(firstIndex, indexCount, firstInstance)`
    /// — `WebGPUBackend.draw()`'s `object.isBatchedMesh` arm, which divides the
    /// byte start back out by `bytesPerElement`.
    #[doc(hidden)]
    pub fn sub_draws(&self) -> Vec<SubDraw> {
        let bpe = self.multi_draw_bytes_per_element.max(1) as i32;
        (0..self.multi_draw_count)
            .map(|i| SubDraw {
                first_index: (self.multi_draw_starts[i] / bpe) as u32,
                index_count: self.multi_draw_counts[i] as u32,
                first_instance: i as u32,
            })
            .collect()
    }

    /// `setCustomSort( func )`.
    pub fn set_custom_sort(&mut self, func: Option<CustomSort>) -> &mut Self {
        self.custom_sort = func;
        self
    }

    fn init_colors_texture(&mut self) {
        let size = (self.max_instance_count as f64).sqrt().ceil().max(1.0) as u32;
        // "4 floats per RGBA pixel initialized to white" — the alpha a
        // `Color.toArray()` never writes therefore stays 1.
        self.colors_texture = Some(DataTexture::new_f32(
            vec![1.0; (size * size * 4) as usize],
            size,
            size,
        ));
    }

    /// `_initializeGeometry( reference )`.
    fn initialize_geometry(&mut self, reference: &BufferGeometry) {
        if self.geometry_initialized {
            return;
        }
        let max_vertex_count = self.max_vertex_count;
        let max_index_count = self.max_index_count;
        let geometry = Rc::get_mut(&mut self.mesh.geometry)
            .expect("three-rs: the batch geometry is shared; add geometries before rendering");

        // "create new attribute buffers to hold the geometry data", each of
        // the reference's typed-array kind and `normalized`.
        let names: Vec<(String, usize, ArrayKind, bool)> = reference
            .attributes()
            .map(|(name, attr)| {
                (
                    name.to_string(),
                    attr.item_size,
                    attr.kind(),
                    attr.normalized,
                )
            })
            .collect();
        for (name, item_size, kind, normalized) in names {
            geometry.set_attribute(
                &name,
                BufferAttribute::from_typed(
                    TypedArray::zeros(kind, max_vertex_count * item_size),
                    item_size,
                    normalized,
                ),
            );
        }

        if reference.index.is_some() {
            // "Reserve last u16 index for primitive restart."
            geometry.set_index_attribute(if max_vertex_count > 65535 {
                Index::U32(vec![0; max_index_count])
            } else {
                Index::U16(vec![0; max_index_count])
            });
        }

        self.geometry_initialized = true;
    }

    /// `_validateGeometry( geometry )`.
    fn validate_geometry(&self, geometry: &BufferGeometry) {
        let batch = &self.mesh.geometry;
        assert_eq!(
            geometry.index.is_some(),
            batch.index.is_some(),
            "THREE.BatchedMesh: All geometries must consistently have \"index\"."
        );
        for (name, dst) in batch.attributes() {
            let src = geometry.get_attribute(name).unwrap_or_else(|| {
                panic!(
                    "THREE.BatchedMesh: Added geometry missing \"{name}\". \
                     All geometries must have consistent attributes."
                )
            });
            assert_eq!(
                src.item_size, dst.item_size,
                "THREE.BatchedMesh: All attributes must have a consistent itemSize."
            );
        }
    }

    /// `addGeometry( geometry )` with the default reserved counts.
    pub fn add_geometry(&mut self, geometry: &BufferGeometry) -> usize {
        self.initialize_geometry(geometry);
        self.validate_geometry(geometry);

        let reserved_vertex_count = geometry
            .position()
            .expect("three-rs: an added geometry needs a position attribute")
            .count();
        let reserved_index_count = geometry.index.as_ref().map(|i| i.count()).unwrap_or(0);

        let info = GeometryInfo {
            vertex_start: self.next_vertex_start,
            vertex_count: 0,
            reserved_vertex_count,
            index_start: if geometry.index.is_some() {
                self.next_index_start as isize
            } else {
                -1
            },
            index_count: 0,
            reserved_index_count,
            start: 0,
            count: 0,
            bounding_box: None,
            bounding_sphere: None,
            active: true,
        };

        assert!(
            !(info.index_start != -1
                && info.index_start as usize + info.reserved_index_count > self.max_index_count
                || info.vertex_start + info.reserved_vertex_count > self.max_vertex_count),
            "THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."
        );

        let geometry_id = self.geometry_count;
        self.geometry_count += 1;
        self.geometry_info.push(info);

        self.set_geometry_at(geometry_id, geometry);

        let info = &self.geometry_info[geometry_id];
        self.next_index_start = (info.index_start.max(0) as usize) + info.reserved_index_count;
        self.next_vertex_start = info.vertex_start + info.reserved_vertex_count;

        geometry_id
    }

    /// `setGeometryAt( geometryId, geometry )`.
    pub fn set_geometry_at(&mut self, geometry_id: usize, geometry: &BufferGeometry) -> usize {
        assert!(
            geometry_id < self.geometry_count,
            "THREE.BatchedMesh: Maximum geometry count reached."
        );
        self.validate_geometry(geometry);

        let info = self.geometry_info[geometry_id].clone();
        let has_index = self.mesh.geometry.index.is_some();
        let src_index_count = geometry.index.as_ref().map(|i| i.count()).unwrap_or(0);
        assert!(
            !(has_index && src_index_count > info.reserved_index_count
                || geometry.position().map(|p| p.count()).unwrap_or(0)
                    > info.reserved_vertex_count),
            "THREE.BatchedMesh: Reserved space not large enough for provided geometry."
        );

        let vertex_start = info.vertex_start;
        let reserved_vertex_count = info.reserved_vertex_count;
        let vertex_count = geometry
            .position()
            .expect("three-rs: an added geometry needs a position attribute")
            .count();

        {
            let batch = Rc::get_mut(&mut self.mesh.geometry)
                .expect("three-rs: the batch geometry is shared; add geometries before rendering");

            let names: Vec<String> = batch.attributes().map(|(n, _)| n.to_string()).collect();
            for name in names {
                let src = geometry
                    .get_attribute(&name)
                    .expect("three-rs: validate_geometry checked this attribute exists");
                let item_size = src.item_size;
                let src_count = src.count();
                let dst = batch
                    .get_attribute_mut(&name)
                    .expect("three-rs: the batch geometry has this attribute");
                copy_attribute_data(src, dst, vertex_start);
                // "fill the rest in with zeroes"
                for i in src_count..reserved_vertex_count {
                    for c in 0..item_size {
                        dst.set_component(vertex_start + i, c, 0.0);
                    }
                }
                dst.set_needs_update();
            }
        }

        let (start, count) = if has_index {
            let index_start = info.index_start.max(0) as usize;
            let reserved_index_count = info.reserved_index_count;
            let src: Vec<u32> = match geometry.index.as_ref() {
                Some(Index::U16(v)) => v.iter().map(|&x| x as u32).collect(),
                Some(Index::U32(v)) => v.clone(),
                None => Vec::new(),
            };
            let batch = Rc::get_mut(&mut self.mesh.geometry)
                .expect("three-rs: the batch geometry is shared; add geometries before rendering");
            let write = |dst: &mut dyn FnMut(usize, u32)| {
                for (i, value) in src.iter().enumerate() {
                    dst(index_start + i, vertex_start as u32 + value);
                }
                for i in src.len()..reserved_index_count {
                    dst(index_start + i, vertex_start as u32);
                }
            };
            match batch.index.as_mut() {
                Some(Index::U16(v)) => write(&mut |i, x| v[i] = x as u16),
                Some(Index::U32(v)) => write(&mut |i, x| v[i] = x),
                None => {}
            }
            (index_start, src.len())
        } else {
            (vertex_start, vertex_count)
        };

        let info = &mut self.geometry_info[geometry_id];
        info.vertex_count = vertex_count;
        if has_index {
            info.index_count = count;
        }
        info.start = start;
        info.count = count;
        info.bounding_box = None;
        info.bounding_sphere = None;

        self.visibility_changed = true;
        geometry_id
    }

    /// `addInstance( geometryId )`.
    pub fn add_instance(&mut self, geometry_id: usize) -> usize {
        assert!(
            self.instance_info.len() < self.max_instance_count,
            "THREE.BatchedMesh: Maximum item count reached."
        );
        let draw_id = self.instance_info.len();
        self.instance_info.push(InstanceInfo {
            visible: true,
            active: true,
            geometry_index: geometry_id,
        });

        let identity = Matrix4::identity().to_array();
        self.matrices_texture.with_f32_mut(|data| {
            for (i, v) in identity.iter().enumerate() {
                data[draw_id * 16 + i] = *v as f32;
            }
        });

        if let Some(colors) = &self.colors_texture {
            colors.with_f32_mut(|data| {
                data[draw_id * 4] = 1.0;
                data[draw_id * 4 + 1] = 1.0;
                data[draw_id * 4 + 2] = 1.0;
            });
        }

        self.visibility_changed = true;
        draw_id
    }

    /// `setMatrixAt( instanceId, matrix )`.
    pub fn set_matrix_at(&mut self, instance_id: usize, matrix: &Matrix4) -> &mut Self {
        let values = matrix.to_array();
        self.matrices_texture.with_f32_mut(|data| {
            for (i, v) in values.iter().enumerate() {
                data[instance_id * 16 + i] = *v as f32;
            }
        });
        self
    }

    /// `getMatrixAt( instanceId, matrix )`.
    pub fn matrix_at(&self, instance_id: usize) -> Matrix4 {
        let values: Vec<f64> = self.matrices_texture.with_f32(|data| {
            data[instance_id * 16..instance_id * 16 + 16]
                .iter()
                .map(|v| *v as f64)
                .collect()
        });
        let mut matrix = Matrix4::identity();
        matrix.from_array(&values, 0);
        matrix
    }

    /// `setColorAt( instanceId, color )`. `Color.toArray()` writes `rgb` only,
    /// so the alpha stays at the texture's initial 1.
    pub fn set_color_at(&mut self, instance_id: usize, color: &crate::math::Color) -> &mut Self {
        if self.colors_texture.is_none() {
            self.init_colors_texture();
        }
        let colors = self
            .colors_texture
            .as_ref()
            .expect("three-rs: the colours texture was just initialised");
        colors.with_f32_mut(|data| {
            data[instance_id * 4] = color.r as f32;
            data[instance_id * 4 + 1] = color.g as f32;
            data[instance_id * 4 + 2] = color.b as f32;
        });
        self
    }

    /// `getBoundingBoxAt( geometryId, target )` — computed from the packed
    /// geometry's own index range, so it costs nothing until the first cull.
    pub fn bounding_box_at(&mut self, geometry_id: usize) -> Option<Box3> {
        if geometry_id >= self.geometry_count {
            return None;
        }
        if self.geometry_info[geometry_id].bounding_box.is_none() {
            let info = self.geometry_info[geometry_id].clone();
            let geometry = &self.mesh.geometry;
            let position = geometry.position()?;
            let mut box3 = Box3::default();
            let mut scratch = Vector3::ZERO;
            for i in info.start..info.start + info.count {
                let iv = index_at(geometry, i);
                // `box.expandByPoint( _vector.fromBufferAttribute( position, iv ) )`
                scratch = position.get_vector3(iv);
                box3.expand_by_point(&scratch);
            }
            self.shared_vector = scratch;
            self.geometry_info[geometry_id].bounding_box = Some(box3);
        }
        self.geometry_info[geometry_id].bounding_box
    }

    /// `getBoundingSphereAt( geometryId, target )`.
    pub fn bounding_sphere_at(&mut self, geometry_id: usize) -> Option<Sphere> {
        if geometry_id >= self.geometry_count {
            return None;
        }
        if self.geometry_info[geometry_id].bounding_sphere.is_none() {
            let box3 = self.bounding_box_at(geometry_id)?;
            let info = self.geometry_info[geometry_id].clone();
            let center = box3.get_center();
            let geometry = &self.mesh.geometry;
            let position = geometry.position()?;
            let mut max_radius_sq: f64 = 0.0;
            let mut scratch = Vector3::ZERO;
            for i in info.start..info.start + info.count {
                let iv = index_at(geometry, i);
                // `_vector.fromBufferAttribute( position, iv )`
                scratch = position.get_vector3(iv);
                max_radius_sq = max_radius_sq.max(center.distance_to_squared(&scratch));
            }
            self.shared_vector = scratch;
            self.geometry_info[geometry_id].bounding_sphere =
                Some(Sphere::new(center, max_radius_sq.sqrt()));
        }
        self.geometry_info[geometry_id].bounding_sphere
    }

    /// `BatchedMesh.raycast( raycaster, intersects )` — `Mesh.raycast()` once
    /// per active, visible instance, over that instance's geometry range with
    /// its per-geometry bounds and `matrixWorld × instanceMatrix`, each hit
    /// tagged with its `batchId`.
    ///
    /// three.js points a scratch `Mesh` (no morph targets) at the batch
    /// geometry's attributes for this; the port passes the same pieces to the
    /// shared mesh raycast directly.
    pub fn raycast(
        &mut self,
        matrix_world: &Matrix4,
        object: &ObjectRef,
        raycaster: &crate::core::Raycaster,
        intersects: &mut Vec<crate::core::Intersection>,
    ) {
        let side = self
            .mesh
            .material
            .as_ref()
            .map_or(crate::materials::Side::Front, |m| m.side);
        let mut batch_intersects = Vec::new();

        for i in 0..self.instance_info.len() {
            let info = self.instance_info[i];
            if !info.visible || !info.active {
                continue;
            }

            let geometry_id = info.geometry_index;
            let (Some(bounding_box), Some(bounding_sphere)) = (
                self.bounding_box_at(geometry_id),
                self.bounding_sphere_at(geometry_id),
            ) else {
                continue;
            };
            let geometry_info = &self.geometry_info[geometry_id];

            // Get the intersects.
            let mut instance_world_matrix = self.matrix_at(i);
            instance_world_matrix.premultiply(matrix_world);

            let geometry = &self.mesh.geometry;
            let target = crate::objects::mesh::MeshRaycast {
                geometry,
                side,
                matrix_world: instance_world_matrix,
                draw_start: geometry_info.start,
                draw_count: Some(geometry_info.count),
                vertex_position: &|index| {
                    crate::objects::mesh::vertex_position(geometry, &[], index)
                },
            };
            target.raycast(
                &bounding_sphere,
                Some(&bounding_box),
                object,
                raycaster,
                &mut batch_intersects,
            );

            // Add the batch id to the intersects.
            for mut intersect in batch_intersects.drain(..) {
                intersect.batch_id = Some(i);
                intersects.push(intersect);
            }
        }
    }

    /// `_multiDrawCount` after the last `onBeforeRender()`.
    #[doc(hidden)]
    pub fn multi_draw_count(&self) -> usize {
        self.multi_draw_count
    }

    /// The first `n` entries of `_indirectTexture` — the draw ordinal → instance
    /// id table, for tests.
    #[doc(hidden)]
    pub fn indirect_prefix(&self, n: usize) -> Vec<u32> {
        self.indirect_texture.with_u32(|data| data[..n].to_vec())
    }

    /// `onBeforeRender( renderer, scene, camera, geometry, material )`.
    pub fn on_before_render(&mut self, matrix_world: &Matrix4, camera: &BatchCamera) {
        if !self.visibility_changed && !self.per_object_frustum_culled && !self.sort_objects {
            return;
        }

        // The indexed multi-draw start offset is in bytes.
        let bytes_per_element = match &self.mesh.geometry.index {
            Some(Index::U16(_)) => 2,
            Some(Index::U32(_)) => 4,
            None => 1,
        };

        let mut frustum = Frustum::default();
        if self.per_object_frustum_culled {
            let mut m = Matrix4::identity();
            m.multiply_matrices(&camera.projection_matrix, &camera.matrix_world_inverse);
            m.multiply(matrix_world);
            frustum.set_from_projection_matrix(&m, camera.coordinate_system, false);
        }

        let mut multi_draw_count = 0usize;

        if self.sort_objects {
            // The camera position and forward axis in the batch's local frame.
            let mut inverse = *matrix_world;
            inverse.invert();
            let mut camera_pos = Vector3::ZERO;
            camera_pos.set_from_matrix_position(&camera.matrix_world);
            camera_pos.apply_matrix4(&inverse);
            self.shared_vector = camera_pos;
            let mut forward = Vector3::new(0.0, 0.0, -1.0);
            forward.transform_direction(&camera.matrix_world);
            forward.transform_direction(&inverse);

            let mut list: Vec<MultiDrawItem> = Vec::new();
            for i in 0..self.instance_info.len() {
                let info = self.instance_info[i];
                if !(info.visible && info.active) {
                    continue;
                }
                let geometry_id = info.geometry_index;
                let matrix = self.matrix_at(i);
                let mut sphere = match self.bounding_sphere_at(geometry_id) {
                    Some(sphere) => sphere,
                    None => continue,
                };
                sphere.apply_matrix4(&matrix);

                let culled = self.per_object_frustum_culled && !frustum.intersects_sphere(&sphere);
                if culled {
                    continue;
                }
                let range = &self.geometry_info[geometry_id];
                // `_temp.subVectors( _sphere.center, _vector ).dot( _forward )`
                // — deliberately `_vector`, not the camera position: the
                // `getBoundingSphereAt()` above overwrites it the first time a
                // geometry's bounds are computed, so on the frame that fills
                // the cache the depths are measured from the last vertex of the
                // last geometry visited. Three does this; the graded frame is
                // that first frame, so the port does it too.
                let mut temp = Vector3::ZERO;
                temp.sub_vectors(&sphere.center, &self.shared_vector);
                let z = temp.dot(&forward);
                list.push(MultiDrawItem {
                    start: range.start,
                    count: range.count,
                    z,
                    index: i,
                });
            }

            let transparent = self
                .mesh
                .material
                .as_ref()
                .map(|m| m.transparent)
                .unwrap_or(false);
            match &self.custom_sort {
                None => {
                    // `list.sort( material.transparent ? sortTransparent : sortOpaque )`.
                    if transparent {
                        list.sort_by(|a, b| b.z.total_cmp(&a.z));
                    } else {
                        list.sort_by(|a, b| a.z.total_cmp(&b.z));
                    }
                }
                Some(sort) => {
                    let sort = sort.clone();
                    sort(
                        &mut list,
                        &SortContext {
                            camera_far: camera.far,
                            transparent,
                            max_instance_count: self.max_instance_count,
                        },
                    );
                }
            }

            let mut indirect = Vec::with_capacity(list.len());
            for item in &list {
                self.multi_draw_starts[multi_draw_count] = (item.start * bytes_per_element) as i32;
                self.multi_draw_counts[multi_draw_count] = item.count as i32;
                indirect.push(item.index as u32);
                multi_draw_count += 1;
            }
            self.indirect_texture.with_u32_mut(|data| {
                for (i, value) in indirect.iter().enumerate() {
                    data[i] = *value;
                }
            });
        } else {
            let mut indirect = Vec::new();
            for i in 0..self.instance_info.len() {
                let info = self.instance_info[i];
                if !(info.visible && info.active) {
                    continue;
                }
                let geometry_id = info.geometry_index;
                let culled = if self.per_object_frustum_culled {
                    let matrix = self.matrix_at(i);
                    match self.bounding_sphere_at(geometry_id) {
                        Some(mut sphere) => {
                            sphere.apply_matrix4(&matrix);
                            !frustum.intersects_sphere(&sphere)
                        }
                        None => false,
                    }
                } else {
                    false
                };
                if culled {
                    continue;
                }
                let range = &self.geometry_info[geometry_id];
                self.multi_draw_starts[multi_draw_count] = (range.start * bytes_per_element) as i32;
                self.multi_draw_counts[multi_draw_count] = range.count as i32;
                indirect.push(i as u32);
                multi_draw_count += 1;
            }
            self.indirect_texture.with_u32_mut(|data| {
                for (i, value) in indirect.iter().enumerate() {
                    data[i] = *value;
                }
            });
        }

        self.multi_draw_count = multi_draw_count;
        self.multi_draw_bytes_per_element = bytes_per_element;
        self.visibility_changed = false;
    }
}

/// `index ? index.getX( i ) : i`.
fn index_at(geometry: &BufferGeometry, i: usize) -> usize {
    match &geometry.index {
        Some(Index::U16(v)) => v[i] as usize,
        Some(Index::U32(v)) => v[i] as usize,
        None => i,
    }
}

/// `_initMatricesTexture()`: one matrix is four RGBA texels, and the side is
/// rounded up to a multiple of four so a matrix never straddles two rows.
fn init_matrices_texture(max_instance_count: usize) -> DataTexture {
    let mut size = ((max_instance_count * 4) as f64).sqrt();
    size = (size / 4.0).ceil() * 4.0;
    let size = (size.max(4.0)) as u32;
    DataTexture::new_f32(vec![0.0; (size * size * 4) as usize], size, size)
}

/// `_initIndirectTexture()`.
fn init_indirect_texture(max_instance_count: usize) -> DataTexture {
    let size = (max_instance_count as f64).sqrt().ceil().max(1.0) as u32;
    DataTexture::new_u32(vec![0; (size * size) as usize], size, size)
}

/// `copyAttributeData( src, target, targetOffset )` from
/// `BatchedMesh.js`'s utils: a straight typed-array copy when both arrays are
/// the same kind and `src` is not interleaved, otherwise through the
/// component getters and setters (which denormalize and renormalize).
///
/// "Same kind" is stricter than three's `src.array.constructor !==
/// target.array.constructor` in one pair: a `Float16BufferAttribute` keeps its
/// binary16 bits in a `Uint16Array`, so three block-copies an `F16` source
/// into a `U16` target (and back) bit for bit, where the port's [`ArrayKind`]
/// tells them apart and copies the decoded values through the getters.
///
/// [`ArrayKind`]: crate::core::ArrayKind
fn copy_attribute_data(src: &BufferAttribute, target: &mut BufferAttribute, target_offset: usize) {
    let item_size = target.item_size;
    if src.is_interleaved() || src.kind() != target.kind() {
        for i in 0..src.count() {
            for c in 0..item_size {
                target.set_component(i + target_offset, c, src.get_component(i, c));
            }
        }
    } else {
        let src = src.data();
        let mut dst = target.data_mut();
        for i in 0..src.len() {
            dst.set(target_offset * item_size + i, src.get(i));
        }
    }
    target.set_needs_update();
}