1use super::*;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub struct Object3dId {
8 pub(super) scene_id: u64,
9 pub(super) object_id: u64,
10 slot: usize,
11}
12
13impl Object3dId {
14 pub const fn get(self) -> u64 {
19 self.object_id
20 }
21}
22
23#[derive(Clone)]
25pub struct Mesh3dInstance {
26 pub(super) id: Object3dId,
27 pub(super) mesh: RetainedMesh3d,
28 pub(super) transform: Transform3d,
29 pub(super) style: MeshStyle3d,
30 pub(super) visible: bool,
31}
32
33impl Mesh3dInstance {
34 fn new(
35 id: Object3dId,
36 mesh: &RetainedMesh3d,
37 transform: Transform3d,
38 style: MeshStyle3d,
39 ) -> Self {
40 Self {
41 id,
42 mesh: mesh.clone(),
43 transform,
44 style,
45 visible: true,
46 }
47 }
48
49 pub const fn id(&self) -> Object3dId {
51 self.id
52 }
53
54 pub const fn mesh(&self) -> &RetainedMesh3d {
56 &self.mesh
57 }
58
59 pub const fn transform(&self) -> Transform3d {
61 self.transform
62 }
63
64 pub const fn style(&self) -> MeshStyle3d {
66 self.style
67 }
68
69 pub const fn is_visible(&self) -> bool {
71 self.visible
72 }
73
74 pub const fn wireframe(&self) -> Option<WireframeStyle3d> {
76 self.style.wireframe_style()
77 }
78}
79
80pub struct Scene3d {
82 pub(super) scene_id: u64,
83 pub(super) background: Color,
84 pub(super) lighting: Lighting3d,
85 pub(super) fog: Option<Fog3d>,
86 pub(super) instances: Vec<Mesh3dInstance>,
87 pub(super) next_object_id: u64,
88 pub(super) renderer_identity: Option<Arc<()>>,
89 slots: Vec<ObjectSlot>,
90 free_slot: Option<usize>,
91 resources: Vec<ResourceUsage>,
92 budget: Scene3dBudget,
93}
94
95#[derive(Clone)]
96struct ObjectSlot {
97 dense_index: Option<usize>,
98 next_free: Option<usize>,
99}
100
101#[derive(Clone, Copy)]
102struct ResourceUsage {
103 key: (u8, usize),
104 references: usize,
105 bytes: usize,
106}
107
108pub(super) struct DynamicSceneMeshChange {
109 index: usize,
110 outgoing: [ResourceUsage; 4],
111 resources: Option<Vec<ResourceUsage>>,
112}
113
114impl DynamicSceneMeshChange {
115 pub(super) fn object_index(&self) -> usize {
116 self.index
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct Scene3dBudget {
127 max_objects: usize,
128 max_storage_bytes: usize,
129 max_mesh_cpu_bytes: usize,
130 max_mesh_gpu_bytes: usize,
131 max_texture_cpu_bytes: usize,
132 max_texture_gpu_bytes: usize,
133}
134
135impl Scene3dBudget {
136 pub fn new(
138 max_objects: usize,
139 max_storage_bytes: usize,
140 max_mesh_cpu_bytes: usize,
141 max_mesh_gpu_bytes: usize,
142 ) -> Result<Self, Scene3dError> {
143 if [
144 max_objects,
145 max_storage_bytes,
146 max_mesh_cpu_bytes,
147 max_mesh_gpu_bytes,
148 ]
149 .contains(&0)
150 {
151 return Err(Scene3dError::InvalidBudget);
152 }
153 Ok(Self {
154 max_objects,
155 max_storage_bytes,
156 max_mesh_cpu_bytes,
157 max_mesh_gpu_bytes,
158 max_texture_cpu_bytes: 64 * 1024 * 1024,
159 max_texture_gpu_bytes: 64 * 1024 * 1024,
160 })
161 }
162 pub const fn max_objects(self) -> usize {
164 self.max_objects
165 }
166 pub const fn max_storage_bytes(self) -> usize {
168 self.max_storage_bytes
169 }
170 pub const fn max_mesh_cpu_bytes(self) -> usize {
172 self.max_mesh_cpu_bytes
173 }
174 pub const fn max_mesh_gpu_bytes(self) -> usize {
176 self.max_mesh_gpu_bytes
177 }
178 pub const fn with_texture_limits(mut self, cpu_bytes: usize, gpu_bytes: usize) -> Self {
181 self.max_texture_cpu_bytes = cpu_bytes;
182 self.max_texture_gpu_bytes = gpu_bytes;
183 self
184 }
185 pub const fn max_texture_cpu_bytes(self) -> usize {
187 self.max_texture_cpu_bytes
188 }
189 pub const fn max_texture_gpu_bytes(self) -> usize {
191 self.max_texture_gpu_bytes
192 }
193}
194
195impl Default for Scene3dBudget {
196 fn default() -> Self {
197 Self {
198 max_objects: 65_536,
199 max_storage_bytes: 64 * 1024 * 1024,
200 max_mesh_cpu_bytes: 256 * 1024 * 1024,
201 max_mesh_gpu_bytes: 256 * 1024 * 1024,
202 max_texture_cpu_bytes: 64 * 1024 * 1024,
203 max_texture_gpu_bytes: 64 * 1024 * 1024,
204 }
205 }
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Scene3dBudgetResource {
211 TextureCpuBytes,
213 TextureGpuBytes,
215 Objects,
217 StorageBytes,
219 MeshCpuBytes,
221 MeshGpuBytes,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct Scene3dStatistics {
228 object_count: usize,
229 slot_capacity: usize,
230 storage_bytes: usize,
231 mesh_count: usize,
232 mesh_cpu_bytes: usize,
233 mesh_gpu_bytes: usize,
234 texture_count: usize,
235 texture_cpu_bytes: usize,
236 texture_gpu_bytes: usize,
237}
238
239impl Scene3dStatistics {
240 pub const fn texture_count(self) -> usize {
242 self.texture_count
243 }
244 pub const fn texture_cpu_bytes(self) -> usize {
246 self.texture_cpu_bytes
247 }
248 pub const fn texture_gpu_bytes(self) -> usize {
250 self.texture_gpu_bytes
251 }
252 pub const fn object_count(self) -> usize {
254 self.object_count
255 }
256 pub const fn slot_capacity(self) -> usize {
258 self.slot_capacity
259 }
260 pub const fn storage_bytes(self) -> usize {
262 self.storage_bytes
263 }
264 pub const fn mesh_count(self) -> usize {
266 self.mesh_count
267 }
268 pub const fn mesh_cpu_bytes(self) -> usize {
270 self.mesh_cpu_bytes
271 }
272 pub const fn mesh_gpu_bytes(self) -> usize {
274 self.mesh_gpu_bytes
275 }
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub struct Scene3dMeshUpdateReport {
281 statistics: Scene3dStatistics,
282 peak_mesh_cpu_bytes: usize,
283 peak_mesh_gpu_bytes: usize,
284 peak_texture_cpu_bytes: usize,
285 peak_texture_gpu_bytes: usize,
286}
287
288impl Scene3dMeshUpdateReport {
289 pub const fn peak_texture_cpu_bytes(self) -> usize {
291 self.peak_texture_cpu_bytes
292 }
293 pub const fn peak_texture_gpu_bytes(self) -> usize {
295 self.peak_texture_gpu_bytes
296 }
297 pub const fn statistics(self) -> Scene3dStatistics {
299 self.statistics
300 }
301 pub const fn peak_mesh_cpu_bytes(self) -> usize {
303 self.peak_mesh_cpu_bytes
304 }
305 pub const fn peak_mesh_gpu_bytes(self) -> usize {
307 self.peak_mesh_gpu_bytes
308 }
309}
310
311impl Scene3d {
312 pub fn new(background: Color) -> Result<Self, Scene3dError> {
314 Self::with_budget(background, Scene3dBudget::default())
315 }
316
317 pub fn with_budget(background: Color, budget: Scene3dBudget) -> Result<Self, Scene3dError> {
319 if !background.is_normalized() || background.alpha() != 1.0 {
320 return Err(Scene3dError::InvalidBackground);
321 }
322 Self::with_alpha_background_and_budget(background, budget)
323 }
324
325 pub fn with_alpha_background(background: Color) -> Result<Self, Scene3dError> {
329 Self::with_alpha_background_and_budget(background, Scene3dBudget::default())
330 }
331
332 pub fn with_alpha_background_and_budget(
334 background: Color,
335 budget: Scene3dBudget,
336 ) -> Result<Self, Scene3dError> {
337 if !background.is_normalized() {
338 return Err(Scene3dError::InvalidBackground);
339 }
340 let scene_id = NEXT_SCENE3D_ID
341 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
342 current.checked_add(1)
343 })
344 .map_err(|_| Scene3dError::SceneIdExhausted)?;
345 Ok(Self {
346 scene_id,
347 background,
348 lighting: Lighting3d::default(),
349 fog: None,
350 instances: Vec::new(),
351 next_object_id: 0,
352 renderer_identity: None,
353 slots: Vec::new(),
354 free_slot: None,
355 resources: Vec::new(),
356 budget,
357 })
358 }
359
360 pub fn set_lighting(&mut self, lighting: Lighting3d) {
362 self.lighting = lighting;
363 }
364 pub const fn lighting(&self) -> Lighting3d {
366 self.lighting
367 }
368 pub fn set_fog(&mut self, fog: Option<Fog3d>) {
370 self.fog = fog;
371 }
372 pub const fn fog(&self) -> Option<Fog3d> {
374 self.fog
375 }
376
377 pub fn try_push(
379 &mut self,
380 mesh: &RetainedMesh3d,
381 transform: Transform3d,
382 style: MeshStyle3d,
383 ) -> Result<Object3dId, Scene3dError> {
384 validate_mesh_style(mesh, style)?;
385 validate_scene3d_transform(transform)?;
386 self.validate_mesh_owner(mesh)?;
387 check_scene_limit(
388 Scene3dBudgetResource::Objects,
389 self.budget.max_objects,
390 self.instances.len().saturating_add(1),
391 )?;
392 let next_object_id = self
393 .next_object_id
394 .checked_add(1)
395 .ok_or(Scene3dError::ObjectIdExhausted)?;
396 let keys = mesh_resources(mesh);
397 self.validate_resource_change(&keys, None)?;
398 self.reserve_storage(
399 1,
400 usize::from(self.free_slot.is_none()),
401 self.missing_resources(&keys),
402 )?;
403 let slot = self.free_slot.unwrap_or(self.slots.len());
404 let id = Object3dId {
405 scene_id: self.scene_id,
406 object_id: self.next_object_id,
407 slot,
408 };
409 if let Some(free) = self.free_slot {
410 self.free_slot = self.slots[free].next_free;
411 self.slots[free] = ObjectSlot {
412 dense_index: Some(self.instances.len()),
413 next_free: None,
414 };
415 } else {
416 self.slots.push(ObjectSlot {
417 dense_index: Some(self.instances.len()),
418 next_free: None,
419 });
420 }
421 for resource in keys {
422 self.add_resource(resource);
423 }
424 self.renderer_identity = Some(Arc::clone(&mesh.renderer_identity));
425 self.instances
426 .push(Mesh3dInstance::new(id, mesh, transform, style));
427 self.next_object_id = next_object_id;
428 Ok(id)
429 }
430
431 pub const fn background(&self) -> Color {
433 self.background
434 }
435
436 pub fn set_background(&mut self, background: Color) -> Result<(), Scene3dError> {
444 if !background.is_normalized() {
445 return Err(Scene3dError::InvalidBackground);
446 }
447 self.background = background;
448 Ok(())
449 }
450
451 pub fn instances(&self) -> &[Mesh3dInstance] {
453 &self.instances
454 }
455
456 pub fn object_count(&self) -> usize {
458 self.instances.len()
459 }
460
461 pub const fn budget(&self) -> Scene3dBudget {
463 self.budget
464 }
465
466 pub fn statistics(&self) -> Scene3dStatistics {
468 Scene3dStatistics {
469 texture_count: self.resources.iter().filter(|r| r.key.0 == 3).count(),
470 texture_cpu_bytes: self
471 .resources
472 .iter()
473 .filter(|r| r.key.0 == 2)
474 .map(|r| r.bytes)
475 .sum(),
476 texture_gpu_bytes: self
477 .resources
478 .iter()
479 .filter(|r| r.key.0 == 3)
480 .map(|r| r.bytes)
481 .sum(),
482 object_count: self.instances.len(),
483 slot_capacity: self.slots.capacity(),
484 storage_bytes: storage_bytes(
485 self.instances.capacity(),
486 self.slots.capacity(),
487 self.resources.capacity(),
488 ),
489 mesh_count: self.resources.iter().filter(|r| r.key.0 == 1).count(),
490 mesh_cpu_bytes: self
491 .resources
492 .iter()
493 .filter(|r| r.key.0 == 0)
494 .map(|r| r.bytes)
495 .sum(),
496 mesh_gpu_bytes: self
497 .resources
498 .iter()
499 .filter(|r| r.key.0 == 1)
500 .map(|r| r.bytes)
501 .sum(),
502 }
503 }
504
505 pub fn instance(&self, object_id: Object3dId) -> Result<&Mesh3dInstance, Scene3dError> {
507 let index = self.instance_index(object_id)?;
508 Ok(&self.instances[index])
509 }
510
511 pub fn remove(&mut self, object_id: Object3dId) -> Result<Mesh3dInstance, Scene3dError> {
518 let index = self.instance_index(object_id)?;
519 let removed = self.instances.remove(index);
520 for instance in &self.instances[index..] {
521 if let Some(dense) = &mut self.slots[instance.id.slot].dense_index {
522 *dense -= 1;
523 }
524 }
525 self.slots[object_id.slot] = ObjectSlot {
526 dense_index: None,
527 next_free: self.free_slot,
528 };
529 self.free_slot = Some(object_id.slot);
530 for resource in mesh_resources(&removed.mesh) {
531 self.remove_resource(resource.key);
532 }
533 Ok(removed)
534 }
535
536 pub fn set_texture_material(
549 &mut self,
550 object_id: Object3dId,
551 material: Option<&TextureMaterial3d>,
552 ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
553 let mesh = self.instance(object_id)?.mesh();
554 let replacement = match material {
555 Some(material) => texture::attach_material(&mesh.renderer_identity, mesh, material)
556 .map_err(Scene3dError::Texture)?,
557 None => mesh.without_material(),
558 };
559 self.set_mesh(object_id, &replacement)
560 }
561
562 pub fn set_mesh(
570 &mut self,
571 object_id: Object3dId,
572 mesh: &RetainedMesh3d,
573 ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
574 let index = self.instance_index(object_id)?;
575 self.validate_mesh_owner(mesh)?;
576 validate_mesh_style(mesh, self.instances[index].style)?;
577 let incoming = mesh_resources(mesh);
578 let outgoing = mesh_resources(&self.instances[index].mesh);
579 let [
580 peak_mesh_cpu_bytes,
581 peak_mesh_gpu_bytes,
582 peak_texture_cpu_bytes,
583 peak_texture_gpu_bytes,
584 ] = self.validate_resource_change(&incoming, Some(&outgoing))?;
585 let removed_keys = outgoing
586 .iter()
587 .filter(|resource| {
588 !incoming.iter().any(|r| r.key == resource.key)
589 && self
590 .resources
591 .binary_search_by_key(&resource.key, |r| r.key)
592 .ok()
593 .is_some_and(|i| self.resources[i].references == 1)
594 })
595 .count();
596 self.reserve_storage(
597 0,
598 0,
599 self.missing_resources(&incoming)
600 .saturating_sub(removed_keys),
601 )?;
602 for resource in outgoing {
603 self.remove_resource(resource.key);
604 }
605 for resource in incoming {
606 self.add_resource(resource);
607 }
608 self.instances[index].mesh = mesh.clone();
609 Ok(Scene3dMeshUpdateReport {
610 statistics: self.statistics(),
611 peak_mesh_cpu_bytes,
612 peak_mesh_gpu_bytes,
613 peak_texture_cpu_bytes,
614 peak_texture_gpu_bytes,
615 })
616 }
617
618 pub(super) fn prepare_dynamic_mesh_change(
619 &self,
620 object_id: Object3dId,
621 source: &Mesh3d,
622 gpu_bytes: usize,
623 replace_buffers: bool,
624 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
625 let index = self.instance_index(object_id)?;
626 validate_mesh_source_style(source, self.instances[index].style)?;
627 let outgoing = mesh_resources(&self.instances[index].mesh);
628 let mut incoming = outgoing;
629 incoming[0].key.1 = source.vertices().as_ptr() as usize;
630 incoming[0].bytes = source.recovery_memory_bytes();
631 if replace_buffers {
632 incoming[1].key.1 = 0;
635 }
636 incoming[1].bytes = gpu_bytes;
637 self.prepare_resource_change(index, incoming, outgoing)
638 }
639
640 pub(super) fn prepare_dynamic_texture_change(
641 &self,
642 object_id: Object3dId,
643 cpu_bytes: usize,
644 gpu_bytes: usize,
645 detached: bool,
646 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
647 let index = self.instance_index(object_id)?;
648 let outgoing = mesh_resources(&self.instances[index].mesh);
649 let mut incoming = outgoing;
650 incoming[2].key.1 = 0;
653 incoming[2].bytes = cpu_bytes;
654 incoming[3].bytes = gpu_bytes;
655 if detached {
656 incoming[3].key.1 = 0;
657 }
658 self.prepare_resource_change(index, incoming, outgoing)
659 }
660
661 fn prepare_resource_change(
662 &self,
663 index: usize,
664 incoming: [ResourceUsage; 4],
665 outgoing: [ResourceUsage; 4],
666 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
667 self.validate_resource_change(&incoming, Some(&outgoing))?;
668 let retired = outgoing
669 .iter()
670 .filter(|resource| {
671 !incoming
672 .iter()
673 .any(|candidate| candidate.key == resource.key)
674 && self
675 .resources
676 .binary_search_by_key(&resource.key, |entry| entry.key)
677 .ok()
678 .is_some_and(|index| self.resources[index].references == 1)
679 })
680 .count();
681 let additional = self.missing_resources(&incoming).saturating_sub(retired);
682 let mut capacity = planned_capacity(
683 &self.resources,
684 additional,
685 self.budget.max_objects.saturating_mul(4),
686 );
687 if storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity)
688 > self.budget.max_storage_bytes
689 {
690 capacity = self
691 .resources
692 .capacity()
693 .max(self.resources.len().saturating_add(additional));
694 }
695 check_scene_limit(
696 Scene3dBudgetResource::StorageBytes,
697 self.budget.max_storage_bytes,
698 storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity),
699 )?;
700 let resources = replacement_capacity(&self.resources, capacity)?;
701 check_scene_limit(
702 Scene3dBudgetResource::StorageBytes,
703 self.budget.max_storage_bytes,
704 storage_bytes(
705 self.instances.capacity(),
706 self.slots.capacity(),
707 resources
708 .as_ref()
709 .map_or(self.resources.capacity(), Vec::capacity),
710 ),
711 )?;
712 Ok(DynamicSceneMeshChange {
713 index,
714 outgoing,
715 resources,
716 })
717 }
718
719 pub(super) fn commit_dynamic_mesh_change(
720 &mut self,
721 change: DynamicSceneMeshChange,
722 mesh: RetainedMesh3d,
723 ) -> Scene3dStatistics {
724 if let Some(resources) = change.resources {
725 self.resources = resources;
726 }
727 for resource in change.outgoing {
728 self.remove_resource(resource.key);
729 }
730 for resource in mesh_resources(&mesh) {
731 self.add_resource(resource);
732 }
733 self.instances[change.index].mesh = mesh;
734 self.statistics()
735 }
736
737 pub(super) fn commit_dynamic_texture_change(&mut self, change: DynamicSceneMeshChange) {
738 if let Some(resources) = change.resources {
739 self.resources = resources;
740 }
741 for resource in change.outgoing {
742 self.remove_resource(resource.key);
743 }
744 for resource in mesh_resources(&self.instances[change.index].mesh) {
745 self.add_resource(resource);
746 }
747 }
748
749 pub fn visible_object_count(&self) -> usize {
751 self.instances
752 .iter()
753 .filter(|instance| instance.visible)
754 .count()
755 }
756
757 pub fn set_transform(
759 &mut self,
760 object_id: Object3dId,
761 transform: Transform3d,
762 ) -> Result<(), Scene3dError> {
763 validate_scene3d_transform(transform)?;
764 let instance = self.instance_mut(object_id)?;
765 instance.transform = transform;
766 Ok(())
767 }
768
769 pub fn set_style(
771 &mut self,
772 object_id: Object3dId,
773 style: MeshStyle3d,
774 ) -> Result<(), Scene3dError> {
775 let instance = self.instance_mut(object_id)?;
776 validate_mesh_style(&instance.mesh, style)?;
777 instance.style = style;
778 Ok(())
779 }
780
781 pub fn set_visible(
783 &mut self,
784 object_id: Object3dId,
785 visible: bool,
786 ) -> Result<(), Scene3dError> {
787 let instance = self.instance_mut(object_id)?;
788 instance.visible = visible;
789 Ok(())
790 }
791
792 pub fn set_wireframe(
794 &mut self,
795 object_id: Object3dId,
796 wireframe: Option<WireframeStyle3d>,
797 ) -> Result<(), Scene3dError> {
798 let instance = self.instance_mut(object_id)?;
799 let surface = instance.style.surface_style();
800 let style = match (surface, wireframe) {
801 (Some(surface), Some(wireframe)) => {
802 MeshStyle3d::surface(surface).with_wireframe(wireframe)
803 }
804 (Some(surface), None) => MeshStyle3d::surface(surface),
805 (None, Some(wireframe)) => MeshStyle3d::wireframe(wireframe),
806 (None, None) => return Err(Scene3dError::EmptyStyle),
807 };
808 validate_mesh_style(&instance.mesh, style)?;
809 instance.style = style;
810 Ok(())
811 }
812
813 fn instance_mut(&mut self, object_id: Object3dId) -> Result<&mut Mesh3dInstance, Scene3dError> {
814 let index = self.instance_index(object_id)?;
815 Ok(&mut self.instances[index])
816 }
817
818 fn instance_index(&self, object_id: Object3dId) -> Result<usize, Scene3dError> {
819 let index = (object_id.scene_id == self.scene_id)
820 .then_some(())
821 .and_then(|()| self.slots.get(object_id.slot))
822 .and_then(|slot| slot.dense_index)
823 .filter(|&index| {
824 self.instances
825 .get(index)
826 .is_some_and(|instance| instance.id == object_id)
827 });
828 index.ok_or(Scene3dError::ObjectNotFound { object_id })
829 }
830
831 fn validate_mesh_owner(&self, mesh: &RetainedMesh3d) -> Result<(), Scene3dError> {
832 if mesh
833 .material()
834 .is_some_and(|material| !material.texture().belongs_to(&mesh.renderer_identity))
835 {
836 return Err(Scene3dError::RendererMismatch);
837 }
838 if self
839 .renderer_identity
840 .as_ref()
841 .is_some_and(|identity| !Arc::ptr_eq(identity, &mesh.renderer_identity))
842 {
843 Err(Scene3dError::RendererMismatch)
844 } else {
845 Ok(())
846 }
847 }
848
849 fn missing_resources(&self, incoming: &[ResourceUsage]) -> usize {
850 incoming
851 .iter()
852 .filter(|r| {
853 r.bytes > 0
854 && self
855 .resources
856 .binary_search_by_key(&r.key, |r| r.key)
857 .is_err()
858 })
859 .count()
860 }
861
862 fn add_resource(&mut self, resource: ResourceUsage) {
863 if resource.bytes == 0 {
864 return;
865 }
866 match self
867 .resources
868 .binary_search_by_key(&resource.key, |r| r.key)
869 {
870 Ok(index) => self.resources[index].references += 1,
871 Err(index) => self.resources.insert(index, resource),
872 }
873 }
874
875 fn remove_resource(&mut self, key: (u8, usize)) {
876 if let Ok(index) = self.resources.binary_search_by_key(&key, |r| r.key) {
877 self.resources[index].references -= 1;
878 if self.resources[index].references == 0 {
879 self.resources.remove(index);
880 }
881 }
882 }
883
884 fn validate_resource_change(
885 &self,
886 incoming: &[ResourceUsage],
887 outgoing: Option<&[ResourceUsage]>,
888 ) -> Result<[usize; 4], Scene3dError> {
889 let stats = self.statistics();
890 let mut bytes = [
891 stats.mesh_cpu_bytes,
892 stats.mesh_gpu_bytes,
893 stats.texture_cpu_bytes,
894 stats.texture_gpu_bytes,
895 ];
896 for resource in incoming {
897 if self
898 .resources
899 .binary_search_by_key(&resource.key, |r| r.key)
900 .is_err()
901 {
902 bytes[resource.key.0 as usize] =
903 bytes[resource.key.0 as usize].saturating_add(resource.bytes);
904 }
905 }
906 let peak = bytes;
907 for resource in outgoing.into_iter().flatten() {
908 if !incoming.iter().any(|r| r.key == resource.key)
909 && self
910 .resources
911 .binary_search_by_key(&resource.key, |r| r.key)
912 .ok()
913 .is_some_and(|i| self.resources[i].references == 1)
914 {
915 bytes[resource.key.0 as usize] -= resource.bytes;
916 }
917 }
918 check_scene_limit(
919 Scene3dBudgetResource::MeshCpuBytes,
920 self.budget.max_mesh_cpu_bytes,
921 bytes[0],
922 )?;
923 check_scene_limit(
924 Scene3dBudgetResource::MeshGpuBytes,
925 self.budget.max_mesh_gpu_bytes,
926 bytes[1],
927 )?;
928 check_scene_limit(
929 Scene3dBudgetResource::TextureCpuBytes,
930 self.budget.max_texture_cpu_bytes,
931 bytes[2],
932 )?;
933 check_scene_limit(
934 Scene3dBudgetResource::TextureGpuBytes,
935 self.budget.max_texture_gpu_bytes,
936 bytes[3],
937 )?;
938 Ok(peak)
939 }
940
941 fn reserve_storage(
942 &mut self,
943 instances: usize,
944 slots: usize,
945 resources: usize,
946 ) -> Result<(), Scene3dError> {
947 let mut capacities = [
948 planned_capacity(&self.instances, instances, self.budget.max_objects),
949 planned_capacity(&self.slots, slots, self.budget.max_objects),
950 planned_capacity(
951 &self.resources,
952 resources,
953 self.budget.max_objects.saturating_mul(4),
954 ),
955 ];
956 if storage_bytes(capacities[0], capacities[1], capacities[2])
957 > self.budget.max_storage_bytes
958 {
959 capacities = [
960 self.instances
961 .capacity()
962 .max(self.instances.len().saturating_add(instances)),
963 self.slots
964 .capacity()
965 .max(self.slots.len().saturating_add(slots)),
966 self.resources
967 .capacity()
968 .max(self.resources.len().saturating_add(resources)),
969 ];
970 }
971 let planned_bytes = storage_bytes(capacities[0], capacities[1], capacities[2]);
972 check_scene_limit(
973 Scene3dBudgetResource::StorageBytes,
974 self.budget.max_storage_bytes,
975 planned_bytes,
976 )?;
977 let new_instances = replacement_capacity(&self.instances, capacities[0])?;
978 let new_slots = replacement_capacity(&self.slots, capacities[1])?;
979 let new_resources = replacement_capacity(&self.resources, capacities[2])?;
980 let bytes = storage_bytes(
981 new_instances
982 .as_ref()
983 .map_or(self.instances.capacity(), Vec::capacity),
984 new_slots
985 .as_ref()
986 .map_or(self.slots.capacity(), Vec::capacity),
987 new_resources
988 .as_ref()
989 .map_or(self.resources.capacity(), Vec::capacity),
990 );
991 check_scene_limit(
992 Scene3dBudgetResource::StorageBytes,
993 self.budget.max_storage_bytes,
994 bytes,
995 )?;
996 if let Some(values) = new_instances {
997 self.instances = values;
998 }
999 if let Some(values) = new_slots {
1000 self.slots = values;
1001 }
1002 if let Some(values) = new_resources {
1003 self.resources = values;
1004 }
1005 Ok(())
1006 }
1007
1008 pub(super) fn rebuild_resource_keys(&mut self) {
1009 self.resources.clear();
1013 for index in 0..self.instances.len() {
1014 for resource in mesh_resources(&self.instances[index].mesh) {
1015 self.add_resource(resource);
1016 }
1017 }
1018 }
1019}
1020
1021fn mesh_resources(mesh: &RetainedMesh3d) -> [ResourceUsage; 4] {
1022 [
1023 ResourceUsage {
1024 key: (0, mesh.source.vertices().as_ptr() as usize),
1025 references: 1,
1026 bytes: mesh.recovery_memory_bytes(),
1027 },
1028 ResourceUsage {
1029 key: (1, Arc::as_ptr(&mesh.vertex_buffer) as usize),
1030 references: 1,
1031 bytes: mesh.gpu_allocation_bytes(),
1032 },
1033 ResourceUsage {
1034 key: (
1035 2,
1036 mesh.material()
1037 .map_or(0, |material| material.texture().identity_key()),
1038 ),
1039 references: 1,
1040 bytes: mesh
1041 .material()
1042 .map_or(0, |material| material.texture().recovery_memory_bytes()),
1043 },
1044 ResourceUsage {
1045 key: (
1046 3,
1047 mesh.material()
1048 .map_or(0, |material| material.texture().identity_key()),
1049 ),
1050 references: 1,
1051 bytes: mesh
1052 .material()
1053 .map_or(0, |material| material.texture().gpu_allocation_bytes()),
1054 },
1055 ]
1056}
1057
1058fn check_scene_limit(
1059 resource: Scene3dBudgetResource,
1060 limit: usize,
1061 actual: usize,
1062) -> Result<(), Scene3dError> {
1063 if actual > limit {
1064 Err(Scene3dError::BudgetExceeded {
1065 resource,
1066 limit,
1067 actual,
1068 })
1069 } else {
1070 Ok(())
1071 }
1072}
1073
1074fn storage_bytes(instances: usize, slots: usize, resources: usize) -> usize {
1075 instances
1076 .saturating_mul(std::mem::size_of::<Mesh3dInstance>())
1077 .saturating_add(slots.saturating_mul(std::mem::size_of::<ObjectSlot>()))
1078 .saturating_add(resources.saturating_mul(std::mem::size_of::<ResourceUsage>()))
1079}
1080
1081fn replacement_capacity<T: Clone>(
1082 current: &Vec<T>,
1083 capacity: usize,
1084) -> Result<Option<Vec<T>>, Scene3dError> {
1085 if capacity <= current.capacity() {
1086 return Ok(None);
1087 }
1088 let mut values = Vec::new();
1089 values
1090 .try_reserve_exact(capacity)
1091 .map_err(|_| Scene3dError::AllocationFailed {
1092 requested_bytes: capacity.saturating_mul(std::mem::size_of::<T>()),
1093 })?;
1094 values.extend_from_slice(current);
1095 Ok(Some(values))
1096}
1097
1098fn planned_capacity<T>(current: &Vec<T>, additional: usize, maximum: usize) -> usize {
1099 let needed = current.len().saturating_add(additional);
1100 if needed <= current.capacity() {
1101 current.capacity()
1102 } else {
1103 needed
1104 .max(current.capacity().saturating_mul(2))
1105 .min(maximum)
1106 }
1107}
1108
1109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1111pub enum Scene3dError {
1112 Texture(Texture3dError),
1114 MissingNormals,
1116 InvalidBudget,
1118 RendererMismatch,
1120 BudgetExceeded {
1122 resource: Scene3dBudgetResource,
1124 limit: usize,
1126 actual: usize,
1128 },
1129 InvalidBackground,
1131 EmptyStyle,
1133 StyleHasNoMatchingGeometry,
1135 InvalidTransform,
1137 SceneIdExhausted,
1139 ObjectIdExhausted,
1141 AllocationFailed {
1143 requested_bytes: usize,
1145 },
1146 ObjectNotFound {
1148 object_id: Object3dId,
1150 },
1151}
1152
1153impl fmt::Display for Scene3dError {
1154 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1155 match self {
1156 Self::Texture(error) => write!(formatter, "3D scene material: {error}"),
1157 Self::MissingNormals => write!(
1158 formatter,
1159 "Lambert surface requires application-supplied model normals"
1160 ),
1161 Self::InvalidBudget => write!(formatter, "3D scene budget limits must be nonzero"),
1162 Self::RendererMismatch => {
1163 write!(formatter, "3D mesh belongs to another renderer generation")
1164 }
1165 Self::BudgetExceeded {
1166 resource,
1167 limit,
1168 actual,
1169 } => write!(
1170 formatter,
1171 "3D scene {resource:?} budget exceeded: {actual} > {limit}"
1172 ),
1173 Self::InvalidBackground => write!(
1174 formatter,
1175 "3D scene background must be normalized; legacy constructors also require opaque alpha"
1176 ),
1177 Self::EmptyStyle => write!(formatter, "3D object requires a surface or wireframe"),
1178 Self::StyleHasNoMatchingGeometry => write!(
1179 formatter,
1180 "3D object style has no matching triangles or display edges"
1181 ),
1182 Self::InvalidTransform => {
1183 write!(
1184 formatter,
1185 "3D model transform is outside the portable shader envelope"
1186 )
1187 }
1188 Self::SceneIdExhausted => write!(formatter, "3D scene identifiers exhausted"),
1189 Self::ObjectIdExhausted => write!(formatter, "3D scene object identifiers exhausted"),
1190 Self::AllocationFailed { requested_bytes } => write!(
1191 formatter,
1192 "could not reserve {requested_bytes} bytes for another 3D scene object"
1193 ),
1194 Self::ObjectNotFound { object_id } => write!(
1195 formatter,
1196 "3D scene object {} does not exist in this scene",
1197 object_id.get()
1198 ),
1199 }
1200 }
1201}
1202
1203impl Error for Scene3dError {
1204 fn source(&self) -> Option<&(dyn Error + 'static)> {
1205 match self {
1206 Self::Texture(error) => Some(error),
1207 _ => None,
1208 }
1209 }
1210}
1211
1212#[cfg(test)]
1213mod presentation_tests {
1214 use super::*;
1215
1216 #[test]
1217 fn background_changes_are_normalized_atomic_and_allocation_free() {
1218 let mut scene = Scene3d::new(Color::BLACK).unwrap();
1219 let identity = scene.scene_id;
1220 let statistics = scene.statistics();
1221 let lighting = scene.lighting();
1222 let fog = scene.fog();
1223 let background = Color::rgba(0.125, 0.25, 0.5, 0.5);
1224 let (_, allocations) = crate::test_allocations::count(|| {
1225 scene.set_background(background).unwrap();
1226 for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1.1] {
1227 for channel in 0..4 {
1228 let mut channels = [0.5; 4];
1229 channels[channel] = bad;
1230 assert_eq!(
1231 scene.set_background(Color::rgba(
1232 channels[0],
1233 channels[1],
1234 channels[2],
1235 channels[3],
1236 )),
1237 Err(Scene3dError::InvalidBackground)
1238 );
1239 assert_eq!(scene.background(), background);
1240 }
1241 }
1242 });
1243 assert_eq!(allocations, 0);
1244 assert_eq!(scene.scene_id, identity);
1245 assert_eq!(scene.statistics(), statistics);
1246 assert_eq!(scene.lighting(), lighting);
1247 assert_eq!(scene.fog(), fog);
1248 for alpha in [0.0, f32::from_bits(1), 1.0] {
1249 scene
1250 .set_background(Color::rgba(0.5, 0.0, 1.0, alpha))
1251 .unwrap();
1252 assert_eq!(scene.background().alpha(), alpha);
1253 }
1254 }
1255
1256 #[test]
1257 fn background_setter_does_not_change_legacy_constructor_validation() {
1258 let translucent = Color::rgba(0.5, 0.0, 1.0, 0.5);
1259 assert!(matches!(
1260 Scene3d::new(translucent),
1261 Err(Scene3dError::InvalidBackground)
1262 ));
1263 assert_eq!(
1264 Scene3d::with_alpha_background(translucent)
1265 .unwrap()
1266 .background(),
1267 translucent
1268 );
1269 let cause = Texture3dError::MissingTextureCoordinates;
1270 let error = Scene3dError::Texture(cause);
1271 assert_eq!(error.source().unwrap().to_string(), cause.to_string());
1272 assert!(Scene3dError::InvalidBackground.source().is_none());
1273 }
1274}