1use std::cell::{Cell, RefCell};
6use std::collections::HashMap;
7use std::rc::Rc;
8
9use super::buffer_attribute::{AttributeDesc, BufferAttribute, InterleavedBuffer};
10use crate::math::{Matrix3, Matrix4, Quaternion, Vector3};
11
12#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub struct GeometryId(usize);
29
30impl GeometryId {
31 fn next() -> Self {
32 thread_local! {
33 static GEOMETRY_ID: Cell<usize> = const { Cell::new(0) };
34 }
35 GEOMETRY_ID.with(|id| {
36 let next = id.get();
37 id.set(next + 1);
38 GeometryId(next)
39 })
40 }
41
42 pub fn get(&self) -> usize {
44 self.0
45 }
46}
47
48impl Clone for GeometryId {
50 fn clone(&self) -> Self {
51 Self::next()
52 }
53}
54
55impl Default for GeometryId {
56 fn default() -> Self {
57 Self::next()
58 }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct BoundingBox {
64 pub min: Vector3,
66 pub max: Vector3,
68}
69
70impl BoundingBox {
71 pub fn empty() -> Self {
73 Self {
74 min: Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
75 max: Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
76 }
77 }
78
79 pub fn from_buffer_attribute(attribute: &BufferAttribute) -> Self {
81 let mut box3 = Self::empty();
82
83 for i in 0..attribute.count() {
84 box3.expand_by_point(&attribute.get_vector3(i));
85 }
86
87 box3
88 }
89
90 pub fn expand_by_point(&mut self, point: &Vector3) -> &mut Self {
92 self.min.min(point);
93 self.max.max(point);
94 self
95 }
96
97 pub fn center(&self) -> Vector3 {
99 Vector3::new(
100 (self.min.x + self.max.x) * 0.5,
101 (self.min.y + self.max.y) * 0.5,
102 (self.min.z + self.max.z) * 0.5,
103 )
104 }
105}
106
107#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct BoundingSphere {
110 pub center: Vector3,
112 pub radius: f64,
114}
115
116#[derive(Clone, Debug)]
120pub enum Index {
121 U16(Vec<u16>),
123 U32(Vec<u32>),
125}
126
127impl Index {
128 pub fn count(&self) -> usize {
130 match self {
131 Index::U16(v) => v.len(),
132 Index::U32(v) => v.len(),
133 }
134 }
135
136 pub fn get_x(&self, i: usize) -> usize {
138 match self {
139 Index::U16(v) => v[i] as usize,
140 Index::U32(v) => v[i] as usize,
141 }
142 }
143
144 pub fn set_x(&mut self, i: usize, x: usize) -> &mut Self {
147 match self {
148 Index::U16(v) => v[i] = x as u16,
149 Index::U32(v) => v[i] = x as u32,
150 }
151 self
152 }
153}
154
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub struct Group {
158 pub start: usize,
160 pub count: usize,
162 pub material_index: usize,
164}
165
166#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
169pub struct DrawRange {
170 pub start: usize,
172 pub count: Option<usize>,
174}
175
176#[derive(Clone, Debug, PartialEq)]
182struct BoundsKey {
183 position: (usize, u32),
184 morph_positions: Vec<(usize, u32)>,
185 morph_targets_relative: bool,
186}
187
188impl BoundsKey {
189 fn matches(&self, geometry: &BufferGeometry, position: &BufferAttribute) -> bool {
192 if self.position != (position.id.get(), position.version())
193 || self.morph_targets_relative != geometry.morph_targets_relative
194 {
195 return false;
196 }
197 let morph = geometry.get_morph_attribute("position").unwrap_or(&[]);
198 morph.len() == self.morph_positions.len()
199 && morph
200 .iter()
201 .zip(&self.morph_positions)
202 .all(|(attribute, &key)| (attribute.id.get(), attribute.version()) == key)
203 }
204
205 fn of(geometry: &BufferGeometry, position: &BufferAttribute) -> Self {
206 Self {
207 position: (position.id.get(), position.version()),
208 morph_positions: geometry
209 .get_morph_attribute("position")
210 .unwrap_or(&[])
211 .iter()
212 .map(|attribute| (attribute.id.get(), attribute.version()))
213 .collect(),
214 morph_targets_relative: geometry.morph_targets_relative,
215 }
216 }
217}
218
219#[derive(Clone, Debug)]
221struct CachedBounds {
222 key: BoundsKey,
223 bounding_box: BoundingBox,
224 bounding_sphere: BoundingSphere,
225}
226
227#[derive(Debug, Default)]
234pub struct BufferGeometry {
235 pub id: GeometryId,
238 attributes: Vec<(String, BufferAttribute)>,
239 pub index: Option<Index>,
241 morph_attributes: Vec<(String, Vec<BufferAttribute>)>,
244 pub morph_targets_relative: bool,
246 pub groups: Vec<Group>,
248 pub draw_range: DrawRange,
250 pub bounding_sphere: Option<BoundingSphere>,
262 pub instance_count: Option<usize>,
268 indirect: Option<super::IndirectStorageBufferAttribute>,
271 bounds: RefCell<Option<CachedBounds>>,
276}
277
278impl Clone for BufferGeometry {
284 fn clone(&self) -> Self {
285 let mut buffers: HashMap<usize, Rc<InterleavedBuffer>> = HashMap::new();
286 let attributes = self
287 .attributes
288 .iter()
289 .map(|(name, attribute)| (name.clone(), attribute.clone_with(&mut buffers)))
290 .collect();
291 let morph_attributes = self
292 .morph_attributes
293 .iter()
294 .map(|(name, list)| {
295 let list = list.iter().map(|a| a.clone_with(&mut buffers)).collect();
296 (name.clone(), list)
297 })
298 .collect();
299 Self {
300 id: self.id.clone(),
301 attributes,
302 index: self.index.clone(),
303 morph_attributes,
304 morph_targets_relative: self.morph_targets_relative,
305 groups: self.groups.clone(),
306 draw_range: self.draw_range,
307 bounding_sphere: self.bounding_sphere,
308 instance_count: self.instance_count,
309 indirect: self.indirect.clone(),
310 bounds: self.bounds.clone(),
311 }
312 }
313}
314
315impl BufferGeometry {
316 pub fn dispose(self: std::rc::Rc<Self>) {}
323
324 pub fn new() -> Self {
326 Self::default()
327 }
328
329 pub fn set_indirect(&mut self, indirect: super::IndirectStorageBufferAttribute) -> &mut Self {
334 self.indirect = Some(indirect);
335 self
336 }
337
338 pub fn indirect(&self) -> Option<&super::IndirectStorageBufferAttribute> {
340 self.indirect.as_ref()
341 }
342
343 pub fn id(&self) -> usize {
346 self.id.get()
347 }
348
349 pub fn get_attribute(&self, name: &str) -> Option<&BufferAttribute> {
351 self.attributes
352 .iter()
353 .find(|(key, _)| key == name)
354 .map(|(_, attribute)| attribute)
355 }
356
357 pub fn get_attribute_mut(&mut self, name: &str) -> Option<&mut BufferAttribute> {
362 self.invalidate_bounds();
363 self.attributes
364 .iter_mut()
365 .find(|(key, _)| key == name)
366 .map(|(_, attribute)| attribute)
367 }
368
369 pub fn set_attribute(&mut self, name: &str, attribute: BufferAttribute) -> &mut Self {
371 self.invalidate_bounds();
372 match self.attributes.iter_mut().find(|(key, _)| key == name) {
373 Some(slot) => slot.1 = attribute,
375 None => self.attributes.push((name.to_string(), attribute)),
376 }
377
378 self
379 }
380
381 pub fn delete_attribute(&mut self, name: &str) -> &mut Self {
383 self.invalidate_bounds();
384 self.attributes.retain(|(key, _)| key != name);
385 self
386 }
387
388 pub fn has_attribute(&self, name: &str) -> bool {
390 self.get_attribute(name).is_some()
391 }
392
393 pub fn attributes(&self) -> impl Iterator<Item = (&str, &BufferAttribute)> {
395 self.attributes
396 .iter()
397 .map(|(name, attribute)| (name.as_str(), attribute))
398 }
399
400 #[doc(hidden)]
412 pub fn attribute_descs(&self) -> Vec<AttributeDesc> {
413 let mut groups: Vec<(usize, usize)> = Vec::new();
414 self.attributes
415 .iter()
416 .enumerate()
417 .map(|(i, (name, attribute))| {
418 let group = match attribute.data_buffer() {
419 Some(data) => match groups.iter().find(|(id, _)| *id == data.id()) {
420 Some((_, group)) => *group,
421 None => {
422 groups.push((data.id(), i));
423 i
424 }
425 },
426 None => i,
427 };
428 attribute.desc(name, group)
429 })
430 .collect()
431 }
432
433 pub fn position(&self) -> Option<&BufferAttribute> {
435 self.get_attribute("position")
436 }
437
438 pub fn normal(&self) -> Option<&BufferAttribute> {
440 self.get_attribute("normal")
441 }
442
443 pub fn uv(&self) -> Option<&BufferAttribute> {
445 self.get_attribute("uv")
446 }
447
448 pub fn get_morph_attribute(&self, name: &str) -> Option<&[BufferAttribute]> {
450 self.morph_attributes
451 .iter()
452 .find(|(key, _)| key == name)
453 .map(|(_, attributes)| attributes.as_slice())
454 }
455
456 pub fn set_morph_attribute(
458 &mut self,
459 name: &str,
460 attributes: Vec<BufferAttribute>,
461 ) -> &mut Self {
462 self.invalidate_bounds();
463 match self
464 .morph_attributes
465 .iter_mut()
466 .find(|(key, _)| key == name)
467 {
468 Some(slot) => slot.1 = attributes,
469 None => self.morph_attributes.push((name.to_string(), attributes)),
470 }
471
472 self
473 }
474
475 pub fn morph_attributes(&self) -> impl Iterator<Item = (&str, &[BufferAttribute])> {
477 self.morph_attributes
478 .iter()
479 .map(|(name, attributes)| (name.as_str(), attributes.as_slice()))
480 }
481
482 pub fn add_group(&mut self, start: usize, count: usize, material_index: usize) {
484 self.groups.push(Group {
485 start,
486 count,
487 material_index,
488 });
489 }
490
491 pub fn clear_groups(&mut self) {
493 self.groups = Vec::new();
494 }
495
496 pub fn set_draw_range(&mut self, start: usize, count: usize) {
498 self.draw_range.start = start;
499 self.draw_range.count = Some(count);
500 }
501
502 pub fn set_from_points(&mut self, points: &[Vector3]) -> &mut Self {
509 match self.get_attribute_mut("position") {
510 Some(position) => {
511 let count = position.count().min(points.len());
512 for (i, point) in points.iter().take(count).enumerate() {
513 position.set_xyz(i, point.x, point.y, point.z);
514 }
515 }
516 None => {
517 let mut array = Vec::with_capacity(points.len() * 3);
518 for point in points {
519 array.push(point.x as f32);
520 array.push(point.y as f32);
521 array.push(point.z as f32);
522 }
523 self.set_attribute("position", BufferAttribute::new(array, 3));
524 }
525 }
526
527 self
528 }
529
530 pub fn set_index(&mut self, indices: &[u32]) {
533 let max = indices.iter().copied().max().unwrap_or(0);
534 self.index = Some(if max > 65535 {
535 Index::U32(indices.to_vec())
536 } else {
537 Index::U16(indices.iter().map(|&i| i as u16).collect())
538 });
539 }
540
541 pub fn set_index_attribute(&mut self, index: Index) {
544 self.index = Some(index);
545 }
546
547 fn invalidate_bounds(&mut self) {
551 *self.bounds.get_mut() = None;
552 }
553
554 pub(crate) fn bounding_sphere_center(&self) -> Vector3 {
559 match self.compute_bounding_box() {
560 Some(box3) => box3.center(),
561 None => Vector3::ZERO,
562 }
563 }
564
565 pub fn compute_bounding_box(&self) -> Option<BoundingBox> {
573 self.cached_bounds().map(|(bounding_box, _)| bounding_box)
574 }
575
576 pub fn compute_bounding_sphere(&self) -> Option<BoundingSphere> {
598 if let Some(sphere) = self.bounding_sphere {
599 return Some(sphere);
600 }
601 self.cached_bounds()
602 .map(|(_, bounding_sphere)| bounding_sphere)
603 }
604
605 fn cached_bounds(&self) -> Option<(BoundingBox, BoundingSphere)> {
607 let position = self.position()?;
608
609 if let Some(cached) = self.bounds.borrow().as_ref() {
610 if cached.key.matches(self, position) {
611 return Some((cached.bounding_box, cached.bounding_sphere));
612 }
613 }
614
615 let bounding_box = self.bounding_box_from_positions(position);
616 let bounding_sphere = self.bounding_sphere_from_positions(position, &bounding_box);
617
618 *self.bounds.borrow_mut() = Some(CachedBounds {
619 key: BoundsKey::of(self, position),
620 bounding_box,
621 bounding_sphere,
622 });
623
624 Some((bounding_box, bounding_sphere))
625 }
626
627 fn bounding_box_from_positions(&self, position: &BufferAttribute) -> BoundingBox {
629 let mut bounding_box = BoundingBox::from_buffer_attribute(position);
630
631 if let Some(morph_positions) = self.get_morph_attribute("position") {
633 for morph_attribute in morph_positions {
634 let box3 = BoundingBox::from_buffer_attribute(morph_attribute);
635
636 if self.morph_targets_relative {
637 let mut vector = Vector3::ZERO;
638 vector.add_vectors(&bounding_box.min, &box3.min);
639 bounding_box.expand_by_point(&vector);
640
641 vector.add_vectors(&bounding_box.max, &box3.max);
642 bounding_box.expand_by_point(&vector);
643 } else {
644 bounding_box.expand_by_point(&box3.min);
645 bounding_box.expand_by_point(&box3.max);
646 }
647 }
648 }
649
650 bounding_box
651 }
652
653 fn bounding_sphere_from_positions(
656 &self,
657 position: &BufferAttribute,
658 bounding_box: &BoundingBox,
659 ) -> BoundingSphere {
660 let center = bounding_box.center();
662
663 let mut max_radius_sq: f64 = 0.0;
664
665 for i in 0..position.count() {
666 let v = position.get_vector3(i);
667 max_radius_sq = max_radius_sq.max(center.distance_to_squared(&v));
668 }
669
670 if let Some(morph_positions) = self.get_morph_attribute("position") {
672 for morph_attribute in morph_positions {
673 for j in 0..morph_attribute.count() {
674 let mut vector = morph_attribute.get_vector3(j);
675
676 if self.morph_targets_relative {
677 let offset = position.get_vector3(j);
678 vector.add(&offset);
679 }
680
681 max_radius_sq = max_radius_sq.max(center.distance_to_squared(&vector));
682 }
683 }
684 }
685
686 BoundingSphere {
687 center,
688 radius: max_radius_sq.sqrt(),
689 }
690 }
691
692 pub fn compute_vertex_normals(&mut self) {
701 let Some(count) = self.position().map(BufferAttribute::count) else {
702 return;
703 };
704
705 let needs_new = match self.normal() {
706 Some(normal) => normal.count() != count,
707 None => true,
708 };
709 if needs_new {
710 self.set_attribute("normal", BufferAttribute::new(vec![0.0; count * 3], 3));
711 }
712
713 let position = self.position().expect("three-rs: checked above");
714 let normal = self.normal().expect("three-rs: set above if missing");
715 let set_xyz = |i: usize, v: &Vector3| {
716 normal.store(i, 0, v.x);
717 normal.store(i, 1, v.y);
718 normal.store(i, 2, v.z);
719 };
720 if !needs_new {
721 for i in 0..normal.count() {
722 set_xyz(i, &Vector3::ZERO);
723 }
724 }
725
726 let mut cb = Vector3::ZERO;
727 let mut ab = Vector3::ZERO;
728
729 if let Some(index) = &self.index {
731 let get = |i: usize| -> usize {
732 match index {
733 Index::U16(v) => v[i] as usize,
734 Index::U32(v) => v[i] as usize,
735 }
736 };
737
738 let mut i = 0;
742 while i + 2 < index.count() {
743 let (v_a, v_b, v_c) = (get(i), get(i + 1), get(i + 2));
744
745 let p_a = position.get_vector3(v_a);
746 let p_b = position.get_vector3(v_b);
747 let p_c = position.get_vector3(v_c);
748
749 cb.sub_vectors(&p_c, &p_b);
750 ab.sub_vectors(&p_a, &p_b);
751 cb.cross(&ab);
752
753 let mut n_a = normal.get_vector3(v_a);
754 let mut n_b = normal.get_vector3(v_b);
755 let mut n_c = normal.get_vector3(v_c);
756
757 n_a.add(&cb);
758 n_b.add(&cb);
759 n_c.add(&cb);
760
761 set_xyz(v_a, &n_a);
762 set_xyz(v_b, &n_b);
763 set_xyz(v_c, &n_c);
764
765 i += 3;
766 }
767 } else {
768 let mut i = 0;
771 while i + 2 < position.count() {
772 let p_a = position.get_vector3(i);
773 let p_b = position.get_vector3(i + 1);
774 let p_c = position.get_vector3(i + 2);
775
776 cb.sub_vectors(&p_c, &p_b);
777 ab.sub_vectors(&p_a, &p_b);
778 cb.cross(&ab);
779
780 set_xyz(i, &cb);
781 set_xyz(i + 1, &cb);
782 set_xyz(i + 2, &cb);
783
784 i += 3;
785 }
786 }
787
788 self.normalize_normals();
789 if let Some(normal) = self.normal() {
790 normal.set_needs_update();
791 }
792 }
793
794 pub fn normalize_normals(&mut self) {
796 let Some(normal) = self.get_attribute_mut("normal") else {
797 return;
798 };
799
800 for i in 0..normal.count() {
801 let mut v = normal.get_vector3(i);
802 v.normalize();
803 normal.set_xyz(i, v.x, v.y, v.z);
804 }
805 }
806
807 pub fn apply_matrix4(&mut self, matrix: &Matrix4) -> &mut Self {
809 if let Some(position) = self.get_attribute_mut("position") {
810 position.apply_matrix4(matrix);
811 }
812
813 if let Some(normal) = self.get_attribute_mut("normal") {
814 let mut normal_matrix = Matrix3::identity();
815 normal_matrix.get_normal_matrix(matrix);
816 normal.apply_normal_matrix(&normal_matrix);
817 }
818
819 self
820 }
821
822 pub fn scale(&mut self, x: f64, y: f64, z: f64) -> &mut Self {
824 let mut m1 = Matrix4::identity();
825 m1.make_scale(x, y, z);
826 self.apply_matrix4(&m1)
827 }
828
829 pub fn apply_quaternion(&mut self, q: &Quaternion) -> &mut Self {
831 let mut m1 = Matrix4::identity();
832 m1.make_rotation_from_quaternion(q);
833 self.apply_matrix4(&m1)
834 }
835
836 pub fn rotate_x(&mut self, angle: f64) -> &mut Self {
838 let mut m1 = Matrix4::identity();
839 m1.make_rotation_x(angle);
840 self.apply_matrix4(&m1)
841 }
842
843 pub fn rotate_y(&mut self, angle: f64) -> &mut Self {
845 let mut m1 = Matrix4::identity();
846 m1.make_rotation_y(angle);
847 self.apply_matrix4(&m1)
848 }
849
850 pub fn rotate_z(&mut self, angle: f64) -> &mut Self {
852 let mut m1 = Matrix4::identity();
853 m1.make_rotation_z(angle);
854 self.apply_matrix4(&m1)
855 }
856
857 pub fn translate(&mut self, x: f64, y: f64, z: f64) -> &mut Self {
859 let mut m1 = Matrix4::identity();
860 m1.make_translation(x, y, z);
861 self.apply_matrix4(&m1)
862 }
863
864 pub fn look_at(&mut self, vector: &Vector3) -> &mut Self {
867 let mut object = crate::core::Object3D::default();
868 object.look_at(vector);
869 object.update_matrix();
870
871 let matrix = object.matrix;
872 self.apply_matrix4(&matrix)
873 }
874
875 pub fn center(&mut self) -> &mut Self {
877 let Some(bounding_box) = self.compute_bounding_box() else {
878 return self;
879 };
880
881 let mut offset = bounding_box.center();
882 offset.negate();
883
884 self.translate(offset.x, offset.y, offset.z)
885 }
886
887 pub fn to_non_indexed(&self) -> Self {
889 let Some(index) = self.index.as_ref() else {
890 return self.clone();
893 };
894
895 let indices: Vec<usize> = match index {
896 Index::U16(v) => v.iter().map(|&i| i as usize).collect(),
897 Index::U32(v) => v.iter().map(|&i| i as usize).collect(),
898 };
899
900 let convert = |attribute: &BufferAttribute| attribute.gather(&indices);
903
904 let mut geometry2 = Self::new();
905
906 for (name, attribute) in self.attributes() {
908 geometry2.set_attribute(name, convert(attribute));
909 }
910
911 let morph: Vec<(String, Vec<BufferAttribute>)> = self
913 .morph_attributes()
914 .map(|(name, attributes)| {
915 (
916 name.to_string(),
917 attributes.iter().map(convert).collect::<Vec<_>>(),
918 )
919 })
920 .collect();
921 for (name, attributes) in morph {
922 geometry2.set_morph_attribute(&name, attributes);
923 }
924
925 geometry2.morph_targets_relative = self.morph_targets_relative;
926
927 for group in &self.groups {
929 geometry2.add_group(group.start, group.count, group.material_index);
930 }
931
932 geometry2
933 }
934}
935
936#[cfg(test)]
937mod tests {
938 use super::*;
939
940 fn triangle() -> BufferGeometry {
941 let mut geometry = BufferGeometry::new();
942 geometry.set_attribute(
943 "position",
944 BufferAttribute::new(vec![-1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0], 3),
945 );
946 geometry
947 }
948
949 #[test]
950 fn bounds_are_the_same_on_a_second_call() {
951 let geometry = triangle();
952 let box1 = geometry.compute_bounding_box().unwrap();
953 let sphere1 = geometry.compute_bounding_sphere().unwrap();
954 assert_eq!(geometry.compute_bounding_box().unwrap(), box1);
955 assert_eq!(geometry.compute_bounding_sphere().unwrap(), sphere1);
956 assert_eq!(geometry.bounding_sphere_center(), box1.center());
957 assert_eq!(sphere1.center, Vector3::new(0.0, 1.0, 0.0));
958 }
959
960 #[test]
961 fn an_in_place_edit_shows_after_set_needs_update() {
962 let geometry = triangle();
963 let before = geometry.compute_bounding_sphere().unwrap();
964
965 let position = geometry.position().unwrap();
966 position.array_mut()[0] = -11.0;
967 assert_eq!(geometry.compute_bounding_sphere().unwrap(), before);
969
970 position.set_needs_update();
971 let after = geometry.compute_bounding_sphere().unwrap();
972 assert_eq!(after.center, Vector3::new(-5.0, 1.0, 0.0));
973 assert_eq!(geometry.bounding_sphere_center(), after.center);
974 assert_eq!(
975 geometry.compute_bounding_box().unwrap().min,
976 Vector3::new(-11.0, 0.0, 0.0)
977 );
978 }
979
980 #[test]
981 fn set_attribute_recomputes() {
982 let mut geometry = triangle();
983 geometry.compute_bounding_sphere().unwrap();
984 geometry.set_attribute(
985 "position",
986 BufferAttribute::new(vec![10.0, 0.0, 0.0, 12.0, 0.0, 0.0], 3),
987 );
988 let sphere = geometry.compute_bounding_sphere().unwrap();
989 assert_eq!(sphere.center, Vector3::new(11.0, 0.0, 0.0));
990 assert_eq!(sphere.radius, 1.0);
991 }
992
993 #[test]
994 fn a_mutating_transform_recomputes() {
995 let mut geometry = triangle();
996 geometry.compute_bounding_sphere().unwrap();
997 geometry.translate(0.0, 0.0, 5.0);
998 assert_eq!(
999 geometry.compute_bounding_sphere().unwrap().center,
1000 Vector3::new(0.0, 1.0, 5.0)
1001 );
1002 geometry.center();
1003 assert_eq!(geometry.bounding_sphere_center(), Vector3::ZERO);
1004 }
1005
1006 #[test]
1007 fn a_clone_keeps_its_own_bounds() {
1008 let original = triangle();
1009 let original_sphere = original.compute_bounding_sphere().unwrap();
1010
1011 let clone = original.clone();
1013 assert_eq!(clone.compute_bounding_sphere().unwrap(), original_sphere);
1014
1015 clone.position().unwrap().array_mut()[0] = -11.0;
1016 clone.position().unwrap().set_needs_update();
1017 assert_eq!(
1018 clone.compute_bounding_sphere().unwrap().center,
1019 Vector3::new(-5.0, 1.0, 0.0)
1020 );
1021 assert_eq!(original.compute_bounding_sphere().unwrap(), original_sphere);
1022
1023 original.position().unwrap().array_mut()[3] = 21.0;
1024 original.position().unwrap().set_needs_update();
1025 assert_eq!(
1026 original.compute_bounding_sphere().unwrap().center,
1027 Vector3::new(10.0, 1.0, 0.0)
1028 );
1029 assert_eq!(
1030 clone.compute_bounding_sphere().unwrap().center,
1031 Vector3::new(-5.0, 1.0, 0.0)
1032 );
1033 }
1034
1035 #[test]
1036 fn a_morph_position_edit_recomputes() {
1037 let mut geometry = triangle();
1038 geometry.set_morph_attribute(
1039 "position",
1040 vec![BufferAttribute::new(
1041 vec![-1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0],
1042 3,
1043 )],
1044 );
1045 let before = geometry.compute_bounding_box().unwrap();
1046 assert_eq!(before.max, Vector3::new(1.0, 2.0, 0.0));
1047
1048 let morph = &geometry.get_morph_attribute("position").unwrap()[0];
1049 morph.array_mut()[3] = 9.0;
1050 morph.set_needs_update();
1051 assert_eq!(
1052 geometry.compute_bounding_box().unwrap().max,
1053 Vector3::new(9.0, 2.0, 0.0)
1054 );
1055
1056 geometry.morph_targets_relative = true;
1058 assert_eq!(
1059 geometry.compute_bounding_box().unwrap().max,
1060 Vector3::new(10.0, 4.0, 0.0)
1061 );
1062 }
1063
1064 #[test]
1065 fn the_override_field_still_wins() {
1066 let mut geometry = triangle();
1067 geometry.compute_bounding_sphere().unwrap();
1068 let sphere = BoundingSphere {
1069 center: Vector3::new(7.0, 7.0, 7.0),
1070 radius: 3.0,
1071 };
1072 geometry.bounding_sphere = Some(sphere);
1073 assert_eq!(geometry.compute_bounding_sphere(), Some(sphere));
1074 }
1075}