1#![allow(unused_variables)]
4
5use crate::overlay3d::Overlay3D;
6use std::collections::BTreeMap;
7use strata_style::Color;
8
9pub use crate::texture3d::{
10 SamplerDesc, TextureData, TextureDesc, TextureId, TextureStore, UvTransform,
11};
12
13#[derive(Debug, Clone, PartialEq)]
15pub struct Transform3D {
16 pub position: [f32; 3],
17 pub rotation: [f32; 3],
18 pub scale: [f32; 3],
19}
20
21impl Default for Transform3D {
22 fn default() -> Self {
23 Self {
24 position: [0.0, 0.0, 0.0],
25 rotation: [0.0, 0.0, 0.0],
26 scale: [1.0, 1.0, 1.0],
27 }
28 }
29}
30
31impl Transform3D {
32 pub const fn from_position(position: [f32; 3]) -> Self {
33 Self {
34 position,
35 rotation: [0.0, 0.0, 0.0],
36 scale: [1.0, 1.0, 1.0],
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq)]
43pub enum Camera3D {
44 Perspective {
45 fov_horizontal_deg: f32,
48 near: f32,
49 far: f32,
50 position: [f32; 3],
51 target: [f32; 3],
52 },
53 Orthographic {
54 left: f32,
55 right: f32,
56 top: f32,
57 bottom: f32,
58 near: f32,
59 far: f32,
60 position: [f32; 3],
61 target: [f32; 3],
62 },
63}
64
65impl Default for Camera3D {
66 fn default() -> Self {
67 Self::Perspective {
68 fov_horizontal_deg: 60.0,
69 near: 0.1,
70 far: 1000.0,
71 position: [0.0, 2.0, 5.0],
72 target: [0.0, 0.0, 0.0],
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq)]
79pub enum Light3D {
80 Ambient {
81 color: Color,
82 intensity: f32,
83 },
84 Directional {
85 position: [f32; 3],
86 color: Color,
87 intensity: f32,
88 cast_shadow: bool,
89 },
90 Point {
91 position: [f32; 3],
92 color: Color,
93 intensity: f32,
94 distance: f32,
95 },
96}
97
98#[derive(Debug, Clone, PartialEq)]
100pub enum Geometry3D {
101 Box {
102 width: f32,
103 height: f32,
104 depth: f32,
105 },
106 Sphere {
107 radius: f32,
108 width_segments: u32,
109 height_segments: u32,
110 },
111 Plane {
112 width: f32,
113 height: f32,
114 },
115 Cylinder {
116 radius_top: f32,
117 radius_bottom: f32,
118 height: f32,
119 radial_segments: u32,
120 },
121 Custom {
122 vertices: Vec<f32>,
123 indices: Vec<u32>,
124 },
125 CustomTextured {
131 vertices: Vec<f32>,
132 indices: Vec<u32>,
133 },
134}
135
136#[derive(Debug, Clone, PartialEq)]
138pub struct TexturedMaterial3D {
139 pub texture: TextureId,
141 pub tint: Color,
143 pub uv_transform: UvTransform,
145 pub lit: bool,
148 pub opacity: f32,
150}
151
152#[derive(Debug, Clone, PartialEq)]
154pub struct TexturedDraw3D {
155 pub material: TexturedMaterial3D,
156 pub index_start: u32,
158 pub index_count: u32,
160}
161
162impl TexturedDraw3D {
163 pub fn new(material: TexturedMaterial3D, index_start: u32, index_count: u32) -> Self {
164 Self {
165 material,
166 index_start,
167 index_count,
168 }
169 }
170}
171
172#[derive(Debug, Clone, PartialEq, Default)]
179pub struct TexturedBatchMaterial3D {
180 pub draws: Vec<TexturedDraw3D>,
181}
182
183impl TexturedBatchMaterial3D {
184 pub fn new() -> Self {
185 Self::default()
186 }
187
188 pub fn push(&mut self, draw: TexturedDraw3D) -> &mut Self {
189 self.draws.push(draw);
190 self
191 }
192
193 pub fn is_empty(&self) -> bool {
194 self.draws.is_empty()
195 }
196}
197
198impl TexturedMaterial3D {
199 pub fn new(texture: TextureId) -> Self {
200 Self {
201 texture,
202 tint: Color::rgba(255, 255, 255, 255),
203 uv_transform: UvTransform::IDENTITY,
204 lit: false,
205 opacity: 1.0,
206 }
207 }
208
209 pub fn with_uv_transform(mut self, transform: UvTransform) -> Self {
210 self.uv_transform = transform;
211 self
212 }
213
214 pub fn with_tint(mut self, tint: Color) -> Self {
215 self.tint = tint;
216 self
217 }
218}
219
220#[derive(Debug, Clone, PartialEq)]
222pub enum ShaderSource {
223 SpirV(Vec<u32>),
224 Glsl(String),
225 Wgsl(String),
226 Msl(String),
227}
228
229#[derive(Debug, Clone, PartialEq)]
231pub enum Material3D {
232 Standard {
234 color: Color,
235 roughness: f32,
236 metalness: f32,
237 emissive: Option<Color>,
238 },
239 Physical {
241 color: Color,
242 roughness: f32,
243 metalness: f32,
244 clearcoat: f32,
245 transmission: f32,
246 },
247 Basic { color: Color },
249 Shader {
251 vertex_shader: Option<ShaderSource>,
252 fragment_shader: Option<ShaderSource>,
253 glsl_fragment: Option<String>,
254 uniforms: BTreeMap<String, f32>,
255 },
256 Textured(TexturedMaterial3D),
258 TexturedBatch(TexturedBatchMaterial3D),
260}
261
262impl Default for Material3D {
263 fn default() -> Self {
264 Self::Standard {
265 color: Color::rgba(255, 255, 255, 255),
266 roughness: 0.5,
267 metalness: 0.0,
268 emissive: None,
269 }
270 }
271}
272
273#[derive(Debug, Clone, PartialEq)]
275pub struct Mesh3D {
276 pub geometry: Geometry3D,
277 pub material: Material3D,
278 pub transform: Transform3D,
279}
280
281impl Mesh3D {
282 pub fn new(geometry: Geometry3D, material: Material3D) -> Self {
283 Self {
284 geometry,
285 material,
286 transform: Transform3D::default(),
287 }
288 }
289
290 pub fn with_transform(mut self, transform: Transform3D) -> Self {
291 self.transform = transform;
292 self
293 }
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, Default)]
298pub enum Background3D {
299 #[default]
301 Transparent,
302 Solid(Color),
304 VerticalGradient { top: Color, bottom: Color },
306}
307
308impl Background3D {
309 pub fn color_at(self, t: f32) -> Option<Color> {
311 let t = t.clamp(0.0, 1.0);
312 match self {
313 Self::Transparent => None,
314 Self::Solid(color) => Some(color),
315 Self::VerticalGradient { top, bottom } => {
316 let mix = |a: f32, b: f32| -> u8 {
317 ((a * (1.0 - t) + b * t) * 255.0).round().clamp(0.0, 255.0) as u8
318 };
319 Some(Color::rgba(
320 mix(top.r(), bottom.r()),
321 mix(top.g(), bottom.g()),
322 mix(top.b(), bottom.b()),
323 mix(top.a(), bottom.a()),
324 ))
325 }
326 }
327 }
328}
329
330#[derive(Debug, Clone, Copy, PartialEq)]
333pub struct CelestialBody3D {
334 pub position: [f64; 3],
336 pub radius: f64,
338 pub color: Color,
339 pub glow: f32,
341 pub depth_test: bool,
344}
345
346#[derive(Debug, Clone, Copy, PartialEq)]
349pub struct CloudShell3D {
350 pub centre: [f64; 3],
352 pub radius: f64,
354 pub color: Color,
355 pub coverage: f32,
357 pub opacity: f32,
359}
360
361impl CloudShell3D {
362 pub fn effective_opacity(&self) -> f32 {
367 (self.coverage.clamp(0.0, 1.0) * self.opacity.clamp(0.0, 1.0)).clamp(0.0, 1.0)
368 }
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
373pub struct TileKeyId {
374 pub level: u8,
375 pub col: u32,
376 pub row: u32,
377 pub face: u8,
378}
379
380impl TileKeyId {
381 #[inline]
382 pub const fn new(level: u8, col: u32, row: u32, face: u8) -> Self {
383 Self {
384 level,
385 col,
386 row,
387 face,
388 }
389 }
390
391 #[inline]
392 pub const fn quadtree(level: u8, col: u32, row: u32) -> Self {
393 Self::new(level, col, row, 0)
394 }
395}
396
397#[repr(C)]
402#[derive(Debug, Clone, Copy, PartialEq)]
403#[cfg_attr(feature = "wgpu-backend", derive(bytemuck::Pod, bytemuck::Zeroable))]
404pub struct RteTileVertex {
405 pub pos_u: [f32; 4],
406 pub norm_v: [f32; 4],
407}
408
409impl RteTileVertex {
410 #[inline]
411 pub const fn new(pos: [f32; 3], normal: [f32; 3], uv: [f32; 2]) -> Self {
412 Self {
413 pos_u: [pos[0], pos[1], pos[2], uv[0]],
414 norm_v: [normal[0], normal[1], normal[2], uv[1]],
415 }
416 }
417
418 #[inline]
419 pub const fn position(self) -> [f32; 3] {
420 [self.pos_u[0], self.pos_u[1], self.pos_u[2]]
421 }
422
423 #[inline]
424 pub const fn normal(self) -> [f32; 3] {
425 [self.norm_v[0], self.norm_v[1], self.norm_v[2]]
426 }
427
428 #[inline]
429 pub const fn uv(self) -> [f32; 2] {
430 [self.pos_u[3], self.norm_v[3]]
431 }
432}
433
434#[derive(Debug, Clone, PartialEq)]
436pub struct RetainedTileMesh {
437 pub key: TileKeyId,
438 pub revision: u64,
439 pub center_ecef: [f64; 3],
440 pub grid_res: u32,
441 pub has_skirts: bool,
442 pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
443 pub bounding_radius: f32,
444}
445
446#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct RetainedTileTexture {
449 pub id: u64,
450 pub revision: u64,
451 pub width: u32,
452 pub height: u32,
453 pub rgba8: std::sync::Arc<Vec<u8>>,
454}
455
456#[derive(Debug, Clone, PartialEq)]
458pub struct RetainedTileInstance {
459 pub key: TileKeyId,
460 pub mesh_revision: u64,
461 pub center_ecef: [f64; 3],
462 pub texture_id: Option<u64>,
463 pub texture_revision: u64,
464 pub uv_rect: [f32; 4],
465 pub tint: [f32; 4],
466 pub unlit: bool,
467 pub night_texture_id: Option<u64>,
468 pub night_texture_revision: u64,
469 pub night_uv_rect: [f32; 4],
470}
471
472impl Default for RetainedTileInstance {
473 fn default() -> Self {
474 Self {
475 key: TileKeyId::quadtree(0, 0, 0),
476 mesh_revision: 0,
477 center_ecef: [0.0; 3],
478 texture_id: None,
479 texture_revision: 0,
480 uv_rect: [0.0, 0.0, 1.0, 1.0],
481 tint: [1.0, 1.0, 1.0, 1.0],
482 unlit: false,
483 night_texture_id: None,
484 night_texture_revision: 0,
485 night_uv_rect: [0.0, 0.0, 1.0, 1.0],
486 }
487 }
488}
489
490#[derive(Debug, Clone, PartialEq)]
492pub struct RetainedDynamicMesh {
493 pub id: u64,
494 pub revision: u64,
495 pub anchor_ecef: [f64; 3],
496 pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
497 pub indices: std::sync::Arc<Vec<u32>>,
498 pub color: [f32; 4],
499 pub unlit: bool,
500}
501
502#[derive(Debug, Clone, PartialEq)]
507pub struct RetainedMeshAsset {
508 pub id: u64,
509 pub revision: u64,
510 pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
511 pub indices: std::sync::Arc<Vec<u32>>,
512 pub vertex_colors: Option<std::sync::Arc<Vec<[f32; 4]>>>,
514 pub albedo_texture: Option<std::sync::Arc<RetainedTileTexture>>,
516}
517
518#[derive(Debug, Clone, PartialEq)]
524pub struct RetainedGeoInstance {
525 pub mesh_id: u64,
526 pub anchor_ecef: [f64; 3],
527 pub model_cols: [[f32; 3]; 3],
528 pub base_color: [f32; 4],
529 pub emissive_rgb: [f32; 3],
530 pub roughness: f32,
531 pub metalness: f32,
532 pub unlit: bool,
533 pub accent_mix: f32,
535 pub albedo_texture: Option<std::sync::Arc<RetainedTileTexture>>,
537}
538
539impl Default for RetainedGeoInstance {
540 fn default() -> Self {
541 Self {
542 mesh_id: 0,
543 anchor_ecef: [0.0; 3],
544 model_cols: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
545 base_color: [1.0, 1.0, 1.0, 1.0],
546 emissive_rgb: [0.0, 0.0, 0.0],
547 roughness: 0.45,
548 metalness: 0.1,
549 unlit: false,
550 accent_mix: 0.0,
551 albedo_texture: None,
552 }
553 }
554}
555
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
558pub enum RetainedParticleSprite {
559 Textured(u64),
562 #[default]
564 ProceduralStreak,
565 ProceduralSnowflake,
567 ProceduralPellet,
569 ProceduralCurtain,
571}
572
573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
575pub enum RetainedParticleBillboard {
576 #[default]
579 VelocityAligned,
580 CameraFacing,
582}
583
584#[derive(Debug, Clone, PartialEq)]
591pub struct RetainedParticleLayer {
592 pub id: u64,
593 pub particle_count: u32,
594 pub sprite: RetainedParticleSprite,
595 pub billboard: RetainedParticleBillboard,
596 pub basis_east: [f32; 3],
598 pub basis_north: [f32; 3],
600 pub basis_up: [f32; 3],
602 pub forward_bias_world: [f32; 3],
604 pub wrapped_phase: [f32; 3],
607 pub altitude_bounds: [f32; 4],
609 pub volume_params: [f32; 4],
611 pub motion_params: [f32; 4],
613 pub size_params: [f32; 4],
615 pub flutter_clamp: [f32; 4],
617 pub color: [f32; 4],
619 pub seed: u32,
621}
622
623impl Default for RetainedParticleLayer {
624 fn default() -> Self {
625 Self {
626 id: 0,
627 particle_count: 0,
628 sprite: RetainedParticleSprite::ProceduralStreak,
629 billboard: RetainedParticleBillboard::VelocityAligned,
630 basis_east: [1.0, 0.0, 0.0],
631 basis_north: [0.0, 1.0, 0.0],
632 basis_up: [0.0, 0.0, 1.0],
633 forward_bias_world: [0.0, 0.0, 0.0],
634 wrapped_phase: [0.0, 0.0, 0.0],
635 altitude_bounds: [100.0, 0.0, 5_500.0, 900.0],
636 volume_params: [48.0, 36.0, 0.22, 1.4],
637 motion_params: [26.0, 3.0, 1.0, 0.0],
638 size_params: [0.045, 0.95, 0.032, 0.0],
639 flutter_clamp: [0.0, 0.0, 1.4, 52.0],
640 color: [0.80, 0.89, 1.0, 0.72],
641 seed: 1,
642 }
643 }
644}
645
646#[derive(Debug, Clone, Copy, PartialEq)]
648pub struct RetainedOceanWaveTrain {
649 pub dir_en: [f32; 2],
651 pub wind_speed_mps: f32,
653 pub phase_time_s: f32,
655 pub weight: f32,
657}
658
659impl Default for RetainedOceanWaveTrain {
660 fn default() -> Self {
661 Self {
662 dir_en: [0.866, 0.5],
663 wind_speed_mps: 8.0,
664 phase_time_s: 0.0,
665 weight: 1.0,
666 }
667 }
668}
669
670#[derive(Debug, Clone, PartialEq)]
675pub struct RetainedOceanSurface {
676 pub enabled: bool,
677 pub origin_ecef: [f64; 3],
679 pub basis_east: [f32; 3],
681 pub basis_north: [f32; 3],
683 pub basis_up: [f32; 3],
685 pub train_a: RetainedOceanWaveTrain,
687 pub train_b: RetainedOceanWaveTrain,
689 pub wave_strength: f32,
691 pub wave_scale: f32,
693 pub glint_intensity: f32,
695 pub opacity: f32,
697 pub alt_fade: f32,
699 pub coastal_shoaling: bool,
701 pub shoaling_range_m: f32,
703 pub sdf_half_span_m: f32,
705 pub sdf_center_en_m: [f32; 2],
707 pub coastal_sdf: Option<std::sync::Arc<RetainedTileTexture>>,
709}
710
711impl Default for RetainedOceanSurface {
712 fn default() -> Self {
713 Self {
714 enabled: false,
715 origin_ecef: [0.0; 3],
716 basis_east: [1.0, 0.0, 0.0],
717 basis_north: [0.0, 1.0, 0.0],
718 basis_up: [0.0, 0.0, 1.0],
719 train_a: RetainedOceanWaveTrain::default(),
720 train_b: RetainedOceanWaveTrain {
721 weight: 0.0,
722 ..RetainedOceanWaveTrain::default()
723 },
724 wave_strength: 1.0,
725 wave_scale: 1.0,
726 glint_intensity: 1.0,
727 opacity: 0.82,
728 alt_fade: 1.0,
729 coastal_shoaling: false,
730 shoaling_range_m: 360.0,
731 sdf_half_span_m: 1_500.0,
732 sdf_center_en_m: [0.0, 0.0],
733 coastal_sdf: None,
734 }
735 }
736}
737
738#[derive(Debug, Clone, Copy, PartialEq)]
740pub struct RetainedStar {
741 pub icrf_dir: [f32; 3],
743 pub vmag: f32,
745 pub color: [f32; 4],
747}
748
749#[derive(Debug, Clone, PartialEq)]
751pub struct RetainedCubemapTexture {
752 pub id: u64,
753 pub revision: u64,
754 pub face_size: u32,
756 pub faces_rgba8: [std::sync::Arc<Vec<u8>>; 6],
758}
759
760#[derive(Debug, Clone, Default, PartialEq)]
762pub struct RetainedEnvironmentAssets {
763 pub revision: u64,
764 pub land_mask: Option<std::sync::Arc<RetainedTileTexture>>,
766 pub cloud_map: Option<std::sync::Arc<RetainedTileTexture>>,
768 pub moon_texture: Option<std::sync::Arc<RetainedTileTexture>>,
770 pub stars: Option<std::sync::Arc<Vec<RetainedStar>>>,
772 pub skybox_cubemap: Option<std::sync::Arc<RetainedCubemapTexture>>,
774}
775
776#[derive(Debug, Clone, Copy, PartialEq)]
778pub struct RetainedCameraUniforms {
779 pub proj: [[f32; 4]; 4],
781 pub view_rot: [[f32; 4]; 4],
783 pub view_proj_rte: [[f32; 4]; 4],
785 pub eye_ecef: [f64; 3],
787 pub sun_dir: [f32; 3],
789 pub sun_color: [f32; 3],
790 pub ambient_color: [f32; 3],
791 pub background: Background3D,
792 pub near: f32,
793 pub far: f32,
794 pub ecef_from_icrf: [[f32; 4]; 4],
796 pub moon_dir: [f32; 3],
798 pub day_night_strength: f32,
800 pub city_lights_intensity: f32,
802 pub local_25d_blend: f32,
804 pub sun_visible: bool,
806 pub sun_angular_radius_rad: f32,
808 pub moon_visible: bool,
810 pub moon_angular_radius_rad: f32,
812 pub stars_visible: bool,
814 pub stars_intensity: f32,
816 pub skybox_intensity: f32,
818 pub cloud_layer_opacity: f32,
820 pub local_cloud_opacity: f32,
822 pub cloud_lon_offset_rad: f32,
824 pub time_s: f32,
826 pub realistic_25d_sky: f32,
828 pub night_stars_25d: f32,
830 pub terrain_25d_lighting: f32,
832 pub terrain_25d_shadows: f32,
834 pub shadow_map_size: u32,
836 pub weather_darkness: f32,
838 pub weather_cloud_cover: f32,
840 pub weather_haze: f32,
842 pub cloud_tint_rgb: [f32; 3],
844 pub cloud_25d_cover_boost: f32,
846}
847
848impl Default for RetainedCameraUniforms {
849 fn default() -> Self {
850 let ident = [
851 [1.0, 0.0, 0.0, 0.0],
852 [0.0, 1.0, 0.0, 0.0],
853 [0.0, 0.0, 1.0, 0.0],
854 [0.0, 0.0, 0.0, 1.0],
855 ];
856 Self {
857 proj: ident,
858 view_rot: ident,
859 view_proj_rte: ident,
860 eye_ecef: [0.0, 0.0, 5.0],
861 sun_dir: [0.577_350_26, 0.577_350_26, 0.577_350_26],
862 sun_color: [1.0, 0.98, 0.95],
863 ambient_color: [0.22, 0.24, 0.28],
864 background: Background3D::Transparent,
865 near: 0.1,
866 far: 100_000_000.0,
867 ecef_from_icrf: ident,
868 moon_dir: [-0.577_350_26, 0.577_350_26, 0.577_350_26],
869 day_night_strength: 1.0,
870 city_lights_intensity: 0.0,
871 local_25d_blend: 0.0,
872 sun_visible: false,
873 sun_angular_radius_rad: 0.018,
874 moon_visible: false,
875 moon_angular_radius_rad: 0.022,
876 stars_visible: false,
877 stars_intensity: 1.0,
878 skybox_intensity: 1.0,
879 cloud_layer_opacity: 0.0,
880 local_cloud_opacity: 0.0,
881 cloud_lon_offset_rad: 0.0,
882 time_s: 0.0,
883 realistic_25d_sky: 0.0,
884 night_stars_25d: 0.0,
885 terrain_25d_lighting: 0.0,
886 terrain_25d_shadows: 0.0,
887 shadow_map_size: 2048,
888 weather_darkness: 0.0,
889 weather_cloud_cover: 0.0,
890 weather_haze: 0.0,
891 cloud_tint_rgb: [1.0, 1.0, 1.0],
892 cloud_25d_cover_boost: 0.0,
893 }
894 }
895}
896
897#[derive(Debug, Clone, Default, PartialEq)]
900pub struct RetainedTerrainFrame {
901 pub camera: RetainedCameraUniforms,
902 pub geometry_revision: u64,
903 pub geo_revision: u64,
906 pub meshes: Vec<std::sync::Arc<RetainedTileMesh>>,
907 pub instances: Vec<RetainedTileInstance>,
908 pub textures: Vec<std::sync::Arc<RetainedTileTexture>>,
909 pub dynamic_meshes: Vec<RetainedDynamicMesh>,
910 pub geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
911 pub geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
912 pub particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
913 pub particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
914 pub ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
915 pub environment: Option<std::sync::Arc<RetainedEnvironmentAssets>>,
916}
917
918#[derive(Debug)]
919struct RetainedSceneState {
920 camera: RetainedCameraUniforms,
921 terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
922 fallback_scene: Option<std::sync::Arc<Scene3D>>,
923}
924
925#[derive(Debug)]
926struct RetainedScene3DInner {
927 camera_generation: std::sync::atomic::AtomicU64,
928 geometry_generation: std::sync::atomic::AtomicU64,
929 overlay_generation: std::sync::atomic::AtomicU64,
930 geo_revision: std::sync::atomic::AtomicU64,
931 state: std::sync::RwLock<RetainedSceneState>,
932}
933
934#[derive(Clone)]
940pub struct RetainedScene3D {
941 inner: std::sync::Arc<RetainedScene3DInner>,
942}
943
944impl std::fmt::Debug for RetainedScene3D {
945 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946 let (cam, geom, overlay) = self.generations();
947 f.debug_struct("RetainedScene3D")
948 .field("camera_generation", &cam)
949 .field("geometry_generation", &geom)
950 .field("overlay_generation", &overlay)
951 .finish()
952 }
953}
954
955impl PartialEq for RetainedScene3D {
956 fn eq(&self, other: &Self) -> bool {
957 if std::sync::Arc::ptr_eq(&self.inner, &other.inner) {
958 return true;
959 }
960 let Ok(a) = self.inner.state.read() else {
961 return false;
962 };
963 let Ok(b) = other.inner.state.read() else {
964 return false;
965 };
966 a.camera == b.camera && a.terrain == b.terrain && a.fallback_scene == b.fallback_scene
967 }
968}
969
970impl RetainedScene3D {
971 pub fn new(camera: RetainedCameraUniforms) -> Self {
972 Self {
973 inner: std::sync::Arc::new(RetainedScene3DInner {
974 camera_generation: std::sync::atomic::AtomicU64::new(1),
975 geometry_generation: std::sync::atomic::AtomicU64::new(0),
976 overlay_generation: std::sync::atomic::AtomicU64::new(0),
977 geo_revision: std::sync::atomic::AtomicU64::new(0),
978 state: std::sync::RwLock::new(RetainedSceneState {
979 camera,
980 terrain: None,
981 fallback_scene: None,
982 }),
983 }),
984 }
985 }
986
987 #[inline]
989 pub fn geo_revision(&self) -> u64 {
990 self.inner
991 .geo_revision
992 .load(std::sync::atomic::Ordering::Acquire)
993 }
994
995 pub fn update_camera(&self, camera: RetainedCameraUniforms) {
996 if let Ok(mut guard) = self.inner.state.write() {
997 guard.camera = camera;
998 }
999 self.inner
1000 .camera_generation
1001 .fetch_add(1, std::sync::atomic::Ordering::Release);
1002 }
1003
1004 pub fn update_terrain(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1005 if let Ok(mut guard) = self.inner.state.write() {
1006 guard.camera = terrain.camera;
1007 let rev = terrain.geo_revision;
1008 guard.terrain = Some(terrain);
1009 self.inner
1010 .geo_revision
1011 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1012 }
1013 self.inner
1014 .geometry_generation
1015 .fetch_add(1, std::sync::atomic::Ordering::Release);
1016 self.inner
1017 .camera_generation
1018 .fetch_add(1, std::sync::atomic::Ordering::Release);
1019 }
1020
1021 pub fn update_terrain_preserving_camera(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1025 if let Ok(mut guard) = self.inner.state.write() {
1026 if let Some(ref existing) = guard.terrain {
1027 let keep_particles =
1028 terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1029 let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1030 let keep_geo =
1031 existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1032 if keep_particles || keep_ocean || keep_geo {
1033 let mut merged = (*terrain).clone();
1034 if keep_particles {
1035 merged.particle_layers = existing.particle_layers.clone();
1036 merged.particle_textures = existing.particle_textures.clone();
1037 }
1038 if keep_ocean {
1039 merged.ocean = existing.ocean.clone();
1040 }
1041 if keep_geo {
1042 merged.geo_revision = existing.geo_revision;
1043 merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1044 merged.geo_instances = existing.geo_instances.clone();
1045 }
1046 let rev = merged.geo_revision;
1047 guard.terrain = Some(std::sync::Arc::new(merged));
1048 self.inner
1049 .geo_revision
1050 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1051 } else {
1052 let rev = terrain.geo_revision;
1053 guard.terrain = Some(terrain);
1054 self.inner
1055 .geo_revision
1056 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1057 }
1058 } else {
1059 let rev = terrain.geo_revision;
1060 guard.terrain = Some(terrain);
1061 self.inner
1062 .geo_revision
1063 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1064 }
1065 }
1066 self.inner
1067 .geometry_generation
1068 .fetch_add(1, std::sync::atomic::Ordering::Release);
1069 }
1070
1071 pub fn update_terrain_with_camera_preserving_overlays(
1078 &self,
1079 terrain: std::sync::Arc<RetainedTerrainFrame>,
1080 ) {
1081 if let Ok(mut guard) = self.inner.state.write() {
1082 guard.camera = terrain.camera;
1083 if let Some(ref existing) = guard.terrain {
1084 let keep_particles =
1085 terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1086 let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1087 let keep_geo =
1088 existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1089 if keep_particles || keep_ocean || keep_geo {
1090 let mut merged = (*terrain).clone();
1091 if keep_particles {
1092 merged.particle_layers = existing.particle_layers.clone();
1093 merged.particle_textures = existing.particle_textures.clone();
1094 }
1095 if keep_ocean {
1096 merged.ocean = existing.ocean.clone();
1097 }
1098 if keep_geo {
1099 merged.geo_revision = existing.geo_revision;
1100 merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1101 merged.geo_instances = existing.geo_instances.clone();
1102 }
1103 let rev = merged.geo_revision;
1104 guard.terrain = Some(std::sync::Arc::new(merged));
1105 self.inner
1106 .geo_revision
1107 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1108 } else {
1109 let rev = terrain.geo_revision;
1110 guard.terrain = Some(terrain);
1111 self.inner
1112 .geo_revision
1113 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1114 }
1115 } else {
1116 let rev = terrain.geo_revision;
1117 guard.terrain = Some(terrain);
1118 self.inner
1119 .geo_revision
1120 .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1121 }
1122 }
1123 self.inner
1124 .geometry_generation
1125 .fetch_add(1, std::sync::atomic::Ordering::Release);
1126 self.inner
1127 .camera_generation
1128 .fetch_add(1, std::sync::atomic::Ordering::Release);
1129 }
1130
1131 pub fn request_gpu_continuation(&self) {
1133 self.inner
1134 .camera_generation
1135 .fetch_add(1, std::sync::atomic::Ordering::Release);
1136 }
1137
1138 pub fn update_camera_and_dynamic_meshes(
1141 &self,
1142 camera: RetainedCameraUniforms,
1143 dynamic_meshes: Vec<RetainedDynamicMesh>,
1144 ) {
1145 if let Ok(mut guard) = self.inner.state.write() {
1146 guard.camera = camera;
1147 if let Some(ref existing) = guard.terrain {
1148 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1149 camera,
1150 geometry_revision: existing.geometry_revision,
1151 geo_revision: existing.geo_revision,
1152 meshes: existing.meshes.clone(),
1153 instances: existing.instances.clone(),
1154 textures: existing.textures.clone(),
1155 dynamic_meshes,
1156 geo_mesh_assets: existing.geo_mesh_assets.clone(),
1157 geo_instances: existing.geo_instances.clone(),
1158 particle_layers: existing.particle_layers.clone(),
1159 particle_textures: existing.particle_textures.clone(),
1160 ocean: existing.ocean.clone(),
1161 environment: existing.environment.clone(),
1162 }));
1163 }
1164 }
1165 self.inner
1166 .camera_generation
1167 .fetch_add(1, std::sync::atomic::Ordering::Release);
1168 }
1169
1170 pub fn update_geo_objects(
1173 &self,
1174 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1175 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1176 ) {
1177 if let Ok(mut guard) = self.inner.state.write() {
1178 let camera = guard.camera;
1179 let next_geo_rev = self
1180 .inner
1181 .geo_revision
1182 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1183 .wrapping_add(1)
1184 .max(1);
1185 if let Some(ref existing) = guard.terrain {
1186 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1187 camera,
1188 geometry_revision: existing.geometry_revision,
1189 geo_revision: next_geo_rev,
1190 meshes: existing.meshes.clone(),
1191 instances: existing.instances.clone(),
1192 textures: existing.textures.clone(),
1193 dynamic_meshes: existing.dynamic_meshes.clone(),
1194 geo_mesh_assets,
1195 geo_instances,
1196 particle_layers: existing.particle_layers.clone(),
1197 particle_textures: existing.particle_textures.clone(),
1198 ocean: existing.ocean.clone(),
1199 environment: existing.environment.clone(),
1200 }));
1201 } else {
1202 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1203 camera,
1204 geometry_revision: 1,
1205 geo_revision: next_geo_rev,
1206 geo_mesh_assets,
1207 geo_instances,
1208 ..Default::default()
1209 }));
1210 }
1211 }
1212 self.inner
1213 .geometry_generation
1214 .fetch_add(1, std::sync::atomic::Ordering::Release);
1215 self.inner
1216 .camera_generation
1217 .fetch_add(1, std::sync::atomic::Ordering::Release);
1218 }
1219
1220 pub fn update_camera_and_world_overlays(
1222 &self,
1223 camera: RetainedCameraUniforms,
1224 dynamic_meshes: Vec<RetainedDynamicMesh>,
1225 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1226 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1227 ) {
1228 if let Ok(mut guard) = self.inner.state.write() {
1229 guard.camera = camera;
1230 let next_geo_rev = self
1231 .inner
1232 .geo_revision
1233 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1234 .wrapping_add(1)
1235 .max(1);
1236 if let Some(ref existing) = guard.terrain {
1237 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1238 camera,
1239 geometry_revision: existing.geometry_revision,
1240 geo_revision: next_geo_rev,
1241 meshes: existing.meshes.clone(),
1242 instances: existing.instances.clone(),
1243 textures: existing.textures.clone(),
1244 dynamic_meshes,
1245 geo_mesh_assets,
1246 geo_instances,
1247 particle_layers: existing.particle_layers.clone(),
1248 particle_textures: existing.particle_textures.clone(),
1249 ocean: existing.ocean.clone(),
1250 environment: existing.environment.clone(),
1251 }));
1252 } else if !geo_instances.is_empty() || !dynamic_meshes.is_empty() {
1253 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1254 camera,
1255 geometry_revision: 1,
1256 geo_revision: next_geo_rev,
1257 dynamic_meshes,
1258 geo_mesh_assets,
1259 geo_instances,
1260 ..Default::default()
1261 }));
1262 }
1263 }
1264 self.inner
1265 .camera_generation
1266 .fetch_add(1, std::sync::atomic::Ordering::Release);
1267 }
1268
1269 pub fn update_camera_and_geo_objects(
1272 &self,
1273 camera: RetainedCameraUniforms,
1274 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1275 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1276 ) {
1277 if let Ok(mut guard) = self.inner.state.write() {
1278 guard.camera = camera;
1279 let next_geo_rev = self
1280 .inner
1281 .geo_revision
1282 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1283 .wrapping_add(1)
1284 .max(1);
1285 if let Some(ref existing) = guard.terrain {
1286 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1287 camera,
1288 geometry_revision: existing.geometry_revision,
1289 geo_revision: next_geo_rev,
1290 meshes: existing.meshes.clone(),
1291 instances: existing.instances.clone(),
1292 textures: existing.textures.clone(),
1293 dynamic_meshes: existing.dynamic_meshes.clone(),
1294 geo_mesh_assets,
1295 geo_instances,
1296 particle_layers: existing.particle_layers.clone(),
1297 particle_textures: existing.particle_textures.clone(),
1298 ocean: existing.ocean.clone(),
1299 environment: existing.environment.clone(),
1300 }));
1301 } else if !geo_instances.is_empty() {
1302 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1303 camera,
1304 geometry_revision: 1,
1305 geo_revision: next_geo_rev,
1306 geo_mesh_assets,
1307 geo_instances,
1308 ..Default::default()
1309 }));
1310 }
1311 }
1312 self.inner
1313 .camera_generation
1314 .fetch_add(1, std::sync::atomic::Ordering::Release);
1315 }
1316
1317 pub fn update_particles(
1320 &self,
1321 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1322 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1323 ) {
1324 if let Ok(mut guard) = self.inner.state.write() {
1325 let camera = guard.camera;
1326 if let Some(ref existing) = guard.terrain {
1327 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1328 camera,
1329 geometry_revision: existing.geometry_revision,
1330 geo_revision: existing.geo_revision,
1331 meshes: existing.meshes.clone(),
1332 instances: existing.instances.clone(),
1333 textures: existing.textures.clone(),
1334 dynamic_meshes: existing.dynamic_meshes.clone(),
1335 geo_mesh_assets: existing.geo_mesh_assets.clone(),
1336 geo_instances: existing.geo_instances.clone(),
1337 particle_layers,
1338 particle_textures,
1339 ocean: existing.ocean.clone(),
1340 environment: existing.environment.clone(),
1341 }));
1342 } else if !particle_layers.is_empty() {
1343 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1344 camera,
1345 geometry_revision: 1,
1346 particle_layers,
1347 particle_textures,
1348 ..Default::default()
1349 }));
1350 }
1351 }
1352 self.inner
1353 .camera_generation
1354 .fetch_add(1, std::sync::atomic::Ordering::Release);
1355 }
1356
1357 pub fn update_camera_and_particles(
1359 &self,
1360 camera: RetainedCameraUniforms,
1361 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1362 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1363 ) {
1364 if let Ok(mut guard) = self.inner.state.write() {
1365 guard.camera = camera;
1366 if let Some(ref existing) = guard.terrain {
1367 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1368 camera,
1369 geometry_revision: existing.geometry_revision,
1370 geo_revision: existing.geo_revision,
1371 meshes: existing.meshes.clone(),
1372 instances: existing.instances.clone(),
1373 textures: existing.textures.clone(),
1374 dynamic_meshes: existing.dynamic_meshes.clone(),
1375 geo_mesh_assets: existing.geo_mesh_assets.clone(),
1376 geo_instances: existing.geo_instances.clone(),
1377 particle_layers,
1378 particle_textures,
1379 ocean: existing.ocean.clone(),
1380 environment: existing.environment.clone(),
1381 }));
1382 } else if !particle_layers.is_empty() {
1383 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1384 camera,
1385 geometry_revision: 1,
1386 particle_layers,
1387 particle_textures,
1388 ..Default::default()
1389 }));
1390 }
1391 }
1392 self.inner
1393 .camera_generation
1394 .fetch_add(1, std::sync::atomic::Ordering::Release);
1395 }
1396
1397 pub fn update_camera_and_ocean(
1399 &self,
1400 camera: RetainedCameraUniforms,
1401 ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1402 ) {
1403 if let Ok(mut guard) = self.inner.state.write() {
1404 guard.camera = camera;
1405 if let Some(ref existing) = guard.terrain {
1406 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1407 camera,
1408 geometry_revision: existing.geometry_revision,
1409 geo_revision: existing.geo_revision,
1410 meshes: existing.meshes.clone(),
1411 instances: existing.instances.clone(),
1412 textures: existing.textures.clone(),
1413 dynamic_meshes: existing.dynamic_meshes.clone(),
1414 geo_mesh_assets: existing.geo_mesh_assets.clone(),
1415 geo_instances: existing.geo_instances.clone(),
1416 particle_layers: existing.particle_layers.clone(),
1417 particle_textures: existing.particle_textures.clone(),
1418 ocean,
1419 environment: existing.environment.clone(),
1420 }));
1421 } else if ocean.is_some() {
1422 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1423 camera,
1424 geometry_revision: 1,
1425 ocean,
1426 ..Default::default()
1427 }));
1428 }
1429 }
1430 self.inner
1431 .camera_generation
1432 .fetch_add(1, std::sync::atomic::Ordering::Release);
1433 }
1434
1435 pub fn update_camera_and_particles_and_ocean(
1437 &self,
1438 camera: RetainedCameraUniforms,
1439 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1440 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1441 ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1442 ) {
1443 if let Ok(mut guard) = self.inner.state.write() {
1444 guard.camera = camera;
1445 if let Some(ref existing) = guard.terrain {
1446 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1447 camera,
1448 geometry_revision: existing.geometry_revision,
1449 geo_revision: existing.geo_revision,
1450 meshes: existing.meshes.clone(),
1451 instances: existing.instances.clone(),
1452 textures: existing.textures.clone(),
1453 dynamic_meshes: existing.dynamic_meshes.clone(),
1454 geo_mesh_assets: existing.geo_mesh_assets.clone(),
1455 geo_instances: existing.geo_instances.clone(),
1456 particle_layers,
1457 particle_textures,
1458 ocean,
1459 environment: existing.environment.clone(),
1460 }));
1461 } else if !particle_layers.is_empty() || ocean.is_some() {
1462 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1463 camera,
1464 geometry_revision: 1,
1465 particle_layers,
1466 particle_textures,
1467 ocean,
1468 ..Default::default()
1469 }));
1470 }
1471 }
1472 self.inner
1473 .camera_generation
1474 .fetch_add(1, std::sync::atomic::Ordering::Release);
1475 }
1476
1477 pub fn update_camera_and_geo_and_particles(
1479 &self,
1480 camera: RetainedCameraUniforms,
1481 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1482 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1483 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1484 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1485 ) {
1486 if let Ok(mut guard) = self.inner.state.write() {
1487 guard.camera = camera;
1488 let next_geo_rev = self
1489 .inner
1490 .geo_revision
1491 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1492 .wrapping_add(1)
1493 .max(1);
1494 if let Some(ref existing) = guard.terrain {
1495 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1496 camera,
1497 geometry_revision: existing.geometry_revision,
1498 geo_revision: next_geo_rev,
1499 meshes: existing.meshes.clone(),
1500 instances: existing.instances.clone(),
1501 textures: existing.textures.clone(),
1502 dynamic_meshes: existing.dynamic_meshes.clone(),
1503 geo_mesh_assets,
1504 geo_instances,
1505 particle_layers,
1506 particle_textures,
1507 ocean: existing.ocean.clone(),
1508 environment: existing.environment.clone(),
1509 }));
1510 } else if !geo_instances.is_empty() || !particle_layers.is_empty() {
1511 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1512 camera,
1513 geometry_revision: 1,
1514 geo_revision: next_geo_rev,
1515 geo_mesh_assets,
1516 geo_instances,
1517 particle_layers,
1518 particle_textures,
1519 ..Default::default()
1520 }));
1521 }
1522 }
1523 self.inner
1524 .camera_generation
1525 .fetch_add(1, std::sync::atomic::Ordering::Release);
1526 }
1527
1528 pub fn update_camera_and_world_and_particles(
1530 &self,
1531 camera: RetainedCameraUniforms,
1532 dynamic_meshes: Vec<RetainedDynamicMesh>,
1533 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1534 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1535 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1536 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1537 ) {
1538 if let Ok(mut guard) = self.inner.state.write() {
1539 guard.camera = camera;
1540 let next_geo_rev = self
1541 .inner
1542 .geo_revision
1543 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1544 .wrapping_add(1)
1545 .max(1);
1546 if let Some(ref existing) = guard.terrain {
1547 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1548 camera,
1549 geometry_revision: existing.geometry_revision,
1550 geo_revision: next_geo_rev,
1551 meshes: existing.meshes.clone(),
1552 instances: existing.instances.clone(),
1553 textures: existing.textures.clone(),
1554 dynamic_meshes,
1555 geo_mesh_assets,
1556 geo_instances,
1557 particle_layers,
1558 particle_textures,
1559 ocean: existing.ocean.clone(),
1560 environment: existing.environment.clone(),
1561 }));
1562 } else if !geo_instances.is_empty()
1563 || !dynamic_meshes.is_empty()
1564 || !particle_layers.is_empty()
1565 {
1566 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1567 camera,
1568 geometry_revision: 1,
1569 geo_revision: next_geo_rev,
1570 dynamic_meshes,
1571 geo_mesh_assets,
1572 geo_instances,
1573 particle_layers,
1574 particle_textures,
1575 ..Default::default()
1576 }));
1577 }
1578 }
1579 self.inner
1580 .camera_generation
1581 .fetch_add(1, std::sync::atomic::Ordering::Release);
1582 }
1583
1584 pub fn update_camera_and_world_and_particles_and_ocean(
1586 &self,
1587 camera: RetainedCameraUniforms,
1588 dynamic_meshes: Vec<RetainedDynamicMesh>,
1589 geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1590 geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1591 particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1592 particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1593 ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1594 ) {
1595 if let Ok(mut guard) = self.inner.state.write() {
1596 guard.camera = camera;
1597 let next_geo_rev = self
1598 .inner
1599 .geo_revision
1600 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1601 .wrapping_add(1)
1602 .max(1);
1603 if let Some(ref existing) = guard.terrain {
1604 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1605 camera,
1606 geometry_revision: existing.geometry_revision,
1607 geo_revision: next_geo_rev,
1608 meshes: existing.meshes.clone(),
1609 instances: existing.instances.clone(),
1610 textures: existing.textures.clone(),
1611 dynamic_meshes,
1612 geo_mesh_assets,
1613 geo_instances,
1614 particle_layers,
1615 particle_textures,
1616 ocean,
1617 environment: existing.environment.clone(),
1618 }));
1619 } else if !geo_instances.is_empty()
1620 || !dynamic_meshes.is_empty()
1621 || !particle_layers.is_empty()
1622 || ocean.is_some()
1623 {
1624 guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1625 camera,
1626 geometry_revision: 1,
1627 geo_revision: next_geo_rev,
1628 dynamic_meshes,
1629 geo_mesh_assets,
1630 geo_instances,
1631 particle_layers,
1632 particle_textures,
1633 ocean,
1634 ..Default::default()
1635 }));
1636 }
1637 }
1638 self.inner
1639 .camera_generation
1640 .fetch_add(1, std::sync::atomic::Ordering::Release);
1641 }
1642
1643 pub fn set_fallback_scene(&self, scene: std::sync::Arc<Scene3D>) {
1644 if let Ok(mut guard) = self.inner.state.write() {
1645 guard.fallback_scene = Some(scene);
1646 }
1647 self.inner
1648 .overlay_generation
1649 .fetch_add(1, std::sync::atomic::Ordering::Release);
1650 }
1651
1652 #[inline]
1653 pub fn camera_generation(&self) -> u64 {
1654 self.inner
1655 .camera_generation
1656 .load(std::sync::atomic::Ordering::Acquire)
1657 }
1658
1659 #[inline]
1660 pub fn geometry_generation(&self) -> u64 {
1661 self.inner
1662 .geometry_generation
1663 .load(std::sync::atomic::Ordering::Acquire)
1664 }
1665
1666 #[inline]
1667 pub fn overlay_generation(&self) -> u64 {
1668 self.inner
1669 .overlay_generation
1670 .load(std::sync::atomic::Ordering::Acquire)
1671 }
1672
1673 #[inline]
1674 pub fn generations(&self) -> (u64, u64, u64) {
1675 (
1676 self.camera_generation(),
1677 self.geometry_generation(),
1678 self.overlay_generation(),
1679 )
1680 }
1681
1682 pub fn camera(&self) -> RetainedCameraUniforms {
1683 self.inner
1684 .state
1685 .read()
1686 .map(|g| g.camera)
1687 .unwrap_or_default()
1688 }
1689
1690 pub fn snapshot_terrain(&self) -> Option<std::sync::Arc<RetainedTerrainFrame>> {
1691 self.inner.state.read().ok().and_then(|g| g.terrain.clone())
1692 }
1693
1694 pub fn fallback_scene(&self) -> Option<std::sync::Arc<Scene3D>> {
1695 self.inner
1696 .state
1697 .read()
1698 .ok()
1699 .and_then(|g| g.fallback_scene.clone())
1700 }
1701}
1702
1703#[derive(Debug, Default, Clone, PartialEq)]
1709pub struct Scene3D {
1710 pub camera: Camera3D,
1711 pub lights: Vec<Light3D>,
1712 pub meshes: Vec<Mesh3D>,
1713 background: Background3D,
1714 celestial: Vec<CelestialBody3D>,
1715 cloud_shells: Vec<CloudShell3D>,
1716 overlay: Option<Overlay3D>,
1717 camera_up: Option<[f64; 3]>,
1719 textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
1721 retained_terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
1723 retained_handle: Option<RetainedScene3D>,
1725}
1726
1727impl Scene3D {
1728 pub fn new() -> Self {
1729 Self::default()
1730 }
1731
1732 pub fn with_retained_terrain(mut self, terrain: std::sync::Arc<RetainedTerrainFrame>) -> Self {
1733 self.retained_terrain = Some(terrain);
1734 self
1735 }
1736
1737 pub fn set_retained_terrain(&mut self, terrain: Option<std::sync::Arc<RetainedTerrainFrame>>) {
1738 self.retained_terrain = terrain;
1739 }
1740
1741 pub fn retained_terrain(&self) -> Option<&std::sync::Arc<RetainedTerrainFrame>> {
1742 self.retained_terrain.as_ref()
1743 }
1744
1745 pub fn with_retained_handle(mut self, handle: RetainedScene3D) -> Self {
1746 self.retained_handle = Some(handle);
1747 self
1748 }
1749
1750 pub fn set_retained_handle(&mut self, handle: Option<RetainedScene3D>) {
1751 self.retained_handle = handle;
1752 }
1753
1754 pub fn retained_handle(&self) -> Option<&RetainedScene3D> {
1755 self.retained_handle.as_ref()
1756 }
1757
1758 pub fn add_mesh(&mut self, mesh: Mesh3D) {
1759 self.meshes.push(mesh);
1760 }
1761
1762 pub fn add_light(&mut self, light: Light3D) {
1763 self.lights.push(light);
1764 }
1765
1766 pub fn with_background(mut self, background: Background3D) -> Self {
1768 self.background = background;
1769 self
1770 }
1771
1772 pub fn with_celestial(mut self, body: CelestialBody3D) -> Self {
1774 self.celestial.push(body);
1775 self
1776 }
1777
1778 pub fn with_cloud_shell(mut self, shell: CloudShell3D) -> Self {
1780 self.cloud_shells.push(shell);
1781 self
1782 }
1783
1784 pub fn with_overlay(mut self, overlay: Overlay3D) -> Self {
1786 self.overlay = Some(overlay);
1787 self
1788 }
1789
1790 pub fn overlay(&self) -> Option<&Overlay3D> {
1791 self.overlay.as_ref()
1792 }
1793
1794 pub fn overlay_mut(&mut self) -> &mut Overlay3D {
1797 self.overlay.get_or_insert_with(Overlay3D::new)
1798 }
1799
1800 pub fn with_textures(
1803 mut self,
1804 textures: std::sync::Arc<crate::texture3d::TextureStore>,
1805 ) -> Self {
1806 self.textures = Some(textures);
1807 self
1808 }
1809
1810 pub fn set_textures(
1812 &mut self,
1813 textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
1814 ) {
1815 self.textures = textures;
1816 }
1817
1818 pub fn textures(&self) -> Option<&std::sync::Arc<crate::texture3d::TextureStore>> {
1820 self.textures.as_ref()
1821 }
1822
1823 pub fn textures_deref(&self) -> Option<&crate::texture3d::TextureStore> {
1825 self.textures.as_deref()
1826 }
1827
1828 pub fn with_camera_up(mut self, up: [f64; 3]) -> Self {
1832 self.camera_up = Some(up);
1833 self
1834 }
1835
1836 pub fn camera_up(&self) -> Option<[f64; 3]> {
1837 self.camera_up
1838 }
1839
1840 pub fn background(&self) -> Background3D {
1841 self.background
1842 }
1843
1844 pub fn celestial(&self) -> &[CelestialBody3D] {
1845 &self.celestial
1846 }
1847
1848 pub fn cloud_shells(&self) -> &[CloudShell3D] {
1849 &self.cloud_shells
1850 }
1851}
1852
1853pub type TextRasterizer = crate::overlay3d::TextRasterizer;
1859
1860thread_local! {
1861 static TEXT_RASTERIZER: std::cell::Cell<Option<TextRasterizer>> = const { std::cell::Cell::new(None) };
1862}
1863
1864pub fn register_overlay_text_rasterizer(rasterizer: TextRasterizer) {
1866 TEXT_RASTERIZER.with(|slot| slot.set(Some(rasterizer)));
1867}
1868
1869pub fn overlay_text_rasterizer() -> Option<TextRasterizer> {
1871 TEXT_RASTERIZER.with(|slot| slot.get())
1872}
1873
1874use strata_dom::{Attribute, NodeBlueprint, Tag, View};
1879use strata_macro::component;
1880
1881pub trait IntoScene3DProp {
1884 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>>;
1885}
1886
1887impl IntoScene3DProp for Scene3D {
1888 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1889 Some(std::sync::Arc::new(self))
1890 }
1891}
1892
1893impl IntoScene3DProp for Option<Scene3D> {
1894 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1895 self.map(std::sync::Arc::new)
1896 }
1897}
1898
1899impl IntoScene3DProp for std::sync::Arc<Scene3D> {
1900 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1901 Some(self)
1902 }
1903}
1904
1905impl IntoScene3DProp for &std::sync::Arc<Scene3D> {
1906 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1907 Some(std::sync::Arc::clone(self))
1908 }
1909}
1910
1911impl IntoScene3DProp for Option<std::sync::Arc<Scene3D>> {
1912 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1913 self
1914 }
1915}
1916
1917impl IntoScene3DProp for Option<&std::sync::Arc<Scene3D>> {
1918 fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1919 self.map(std::sync::Arc::clone)
1920 }
1921}
1922
1923#[allow(non_snake_case)]
1924pub fn Canvas3D(class: Option<&'static str>, children: Option<Vec<NodeBlueprint>>) -> View {
1925 let mut builder = Canvas3D::builder();
1926 if let Some(c) = class {
1927 builder = builder.class(c);
1928 }
1929 if let Some(ch) = children {
1930 builder = builder.children(ch);
1931 }
1932 builder.build()
1933}
1934
1935#[allow(non_snake_case)]
1936pub struct Canvas3D {}
1937
1938impl Canvas3D {
1939 pub fn builder() -> Canvas3DBuilder {
1940 Canvas3DBuilder::default()
1941 }
1942}
1943
1944pub trait IntoCameraChangeProp {
1947 fn into_camera_change_prop(
1948 self,
1949 ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>;
1950}
1951
1952impl IntoCameraChangeProp for Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1953 fn into_camera_change_prop(
1954 self,
1955 ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1956 self
1957 }
1958}
1959
1960impl IntoCameraChangeProp for std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)> {
1961 fn into_camera_change_prop(
1962 self,
1963 ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1964 Some(self)
1965 }
1966}
1967
1968impl<F: Fn(&crate::orbit_controls::OrbitControls) + 'static> IntoCameraChangeProp for F {
1969 fn into_camera_change_prop(
1970 self,
1971 ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1972 Some(std::rc::Rc::new(self))
1973 }
1974}
1975
1976pub fn attach_orbit_controls_listeners(
1979 attrs: &mut Vec<Attribute>,
1980 scene: Option<&Scene3D>,
1981 width: Option<f32>,
1982 height: Option<f32>,
1983 cb: std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>,
1984) {
1985 use std::cell::RefCell;
1986 use std::rc::Rc;
1987 use strata_dom::{Event, EventType};
1988
1989 let mut initial_controls = match scene {
1990 Some(s) => crate::orbit_controls::OrbitControls::from_camera(&s.camera),
1991 None => crate::orbit_controls::OrbitControls::default(),
1992 };
1993 initial_controls.enable_damping = false;
1994 let fov_deg = match scene.map(|s| &s.camera) {
1995 Some(Camera3D::Perspective {
1996 fov_horizontal_deg, ..
1997 }) => *fov_horizontal_deg,
1998 _ => 60.0,
1999 };
2000 let vw = width.unwrap_or(800.0).max(1.0);
2001 let vh = height.unwrap_or(600.0).max(1.0);
2002 let controls = Rc::new(RefCell::new(initial_controls));
2003
2004 let ctrl_down = Rc::clone(&controls);
2005 attrs.push(Attribute::event_listener(
2006 EventType::PointerDown,
2007 move |ev: Event| {
2008 let btn = ev.button.max(0) as u8;
2009 ctrl_down
2010 .borrow_mut()
2011 .on_pointer_down(ev.client_x as f32, ev.client_y as f32, btn);
2012 },
2013 ));
2014
2015 let ctrl_move = Rc::clone(&controls);
2016 let cb_move = Rc::clone(&cb);
2017 attrs.push(Attribute::event_listener(
2018 EventType::PointerMove,
2019 move |ev: Event| {
2020 let changed = {
2021 let mut c = ctrl_move.borrow_mut();
2022 let active = c.active_mode != crate::orbit_controls::OrbitInteractionMode::None;
2023 if active {
2024 c.on_pointer_move(ev.client_x as f32, ev.client_y as f32, vw, vh, fov_deg);
2025 }
2026 active
2027 };
2028 if changed {
2029 let c = ctrl_move.borrow();
2030 cb_move(&c);
2031 }
2032 },
2033 ));
2034
2035 let ctrl_up = Rc::clone(&controls);
2036 attrs.push(Attribute::event_listener(
2037 EventType::PointerUp,
2038 move |_ev: Event| {
2039 ctrl_up.borrow_mut().on_pointer_up();
2040 },
2041 ));
2042
2043 let ctrl_wheel = Rc::clone(&controls);
2044 let cb_wheel = Rc::clone(&cb);
2045 attrs.push(Attribute::event_listener(
2046 EventType::Wheel,
2047 move |ev: Event| {
2048 ev.default_prevented.set(true);
2049 {
2050 let mut c = ctrl_wheel.borrow_mut();
2051 c.on_wheel(ev.delta_y as f32);
2052 }
2053 let c = ctrl_wheel.borrow();
2054 cb_wheel(&c);
2055 },
2056 ));
2057}
2058
2059#[derive(Default)]
2060pub struct Canvas3DBuilder {
2061 pub scene: Option<std::sync::Arc<Scene3D>>,
2062 pub retained: Option<RetainedScene3D>,
2063 pub uncapped: bool,
2064 pub class: Option<strata_dom::ClassList>,
2065 pub style: Option<String>,
2066 pub id: Option<String>,
2067 pub width: Option<f32>,
2068 pub height: Option<f32>,
2069 pub on_camera_change: Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>,
2070 pub events: Vec<Attribute>,
2071 pub children: Option<Vec<NodeBlueprint>>,
2072}
2073
2074impl Canvas3DBuilder {
2075 pub fn scene(mut self, scene: impl IntoScene3DProp) -> Self {
2076 self.scene = scene.into_scene3d_prop();
2077 self
2078 }
2079
2080 pub fn class(mut self, class: impl Into<strata_dom::ClassList>) -> Self {
2081 self.class = Some(class.into());
2082 self
2083 }
2084
2085 pub fn style(mut self, style: impl Into<String>) -> Self {
2086 self.style = Some(style.into());
2087 self
2088 }
2089
2090 pub fn id(mut self, id: impl Into<String>) -> Self {
2091 self.id = Some(id.into());
2092 self
2093 }
2094
2095 pub fn width(mut self, width: impl Into<Option<f32>>) -> Self {
2096 self.width = width.into();
2097 self
2098 }
2099
2100 pub fn height(mut self, height: impl Into<Option<f32>>) -> Self {
2101 self.height = height.into();
2102 self
2103 }
2104
2105 pub fn on_camera_change(mut self, cb: impl IntoCameraChangeProp) -> Self {
2106 self.on_camera_change = cb.into_camera_change_prop();
2107 self
2108 }
2109
2110 pub fn on_camera_change_fn(
2111 mut self,
2112 cb: impl Fn(&crate::orbit_controls::OrbitControls) + 'static,
2113 ) -> Self {
2114 self.on_camera_change = Some(std::rc::Rc::new(cb));
2115 self
2116 }
2117
2118 fn push_event(
2119 mut self,
2120 ty: strata_dom::EventType,
2121 handler: impl Fn(strata_dom::Event) + 'static,
2122 ) -> Self {
2123 self.events.push(Attribute::event_listener(ty, handler));
2124 self
2125 }
2126
2127 pub fn onmousedown(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2128 self.push_event(strata_dom::EventType::MouseDown, handler)
2129 }
2130
2131 pub fn onmousedown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2132 self.onmousedown(handler)
2133 }
2134
2135 pub fn onmousemove(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2136 self.push_event(strata_dom::EventType::MouseMove, handler)
2137 }
2138
2139 pub fn onmousemove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2140 self.onmousemove(handler)
2141 }
2142
2143 pub fn onmouseup(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2144 self.push_event(strata_dom::EventType::MouseUp, handler)
2145 }
2146
2147 pub fn onmouseup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2148 self.onmouseup(handler)
2149 }
2150
2151 pub fn onwheel(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2152 self.push_event(strata_dom::EventType::Wheel, handler)
2153 }
2154
2155 pub fn onwheel_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2156 self.onwheel(handler)
2157 }
2158
2159 pub fn onpointerdown(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2160 self.push_event(strata_dom::EventType::PointerDown, handler)
2161 }
2162
2163 pub fn onpointerdown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2164 self.onpointerdown(handler)
2165 }
2166
2167 pub fn onpointermove(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2168 self.push_event(strata_dom::EventType::PointerMove, handler)
2169 }
2170
2171 pub fn onpointermove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2172 self.onpointermove(handler)
2173 }
2174
2175 pub fn onpointerup(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2176 self.push_event(strata_dom::EventType::PointerUp, handler)
2177 }
2178
2179 pub fn onpointerup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2180 self.onpointerup(handler)
2181 }
2182
2183 pub fn onclick(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2184 self.push_event(strata_dom::EventType::Click, handler)
2185 }
2186
2187 pub fn onclick_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2188 self.onclick(handler)
2189 }
2190
2191 pub fn onresize(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2192 self.push_event(strata_dom::EventType::Resize, handler)
2193 }
2194
2195 pub fn onresize_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2196 self.onresize(handler)
2197 }
2198
2199 pub fn retained(mut self, handle: impl Into<Option<RetainedScene3D>>) -> Self {
2201 self.retained = handle.into();
2202 self
2203 }
2204
2205 pub fn uncapped(mut self, uncapped: bool) -> Self {
2207 self.uncapped = uncapped;
2208 self
2209 }
2210
2211 pub fn children(mut self, children: Vec<NodeBlueprint>) -> Self {
2212 self.children = Some(children);
2213 self
2214 }
2215
2216 pub fn build(self) -> View {
2217 let mut attrs = Vec::with_capacity(5 + self.events.len());
2218 attrs.push(Attribute::property("data-strata-canvas3d", "true"));
2219 if self.uncapped {
2220 attrs.push(Attribute::property("data-strata-uncapped", "true"));
2221 }
2222 if let Some(id) = self.id {
2223 attrs.push(Attribute::property("id", id));
2224 }
2225 if let Some(w) = self.width {
2226 attrs.push(Attribute::property("width", w.to_string()));
2227 }
2228 if let Some(h) = self.height {
2229 attrs.push(Attribute::property("height", h.to_string()));
2230 }
2231 if let Some(style) = self.style {
2232 attrs.push(Attribute::property("style", style));
2233 }
2234 attrs.extend(self.events);
2235 let effective_scene = match (self.scene, self.retained) {
2236 (Some(mut scene), Some(retained)) => {
2237 if scene.retained_handle().is_none() {
2238 let s = std::sync::Arc::make_mut(&mut scene);
2239 s.set_retained_handle(Some(retained));
2240 }
2241 Some(scene)
2242 }
2243 (Some(scene), None) => Some(scene),
2244 (None, Some(retained)) => {
2245 let mut scene = retained
2246 .fallback_scene()
2247 .map(|s| (*s).clone())
2248 .unwrap_or_default();
2249 scene.set_retained_handle(Some(retained));
2250 Some(std::sync::Arc::new(scene))
2251 }
2252 (None, None) => None,
2253 };
2254 if let Some(cb) = self.on_camera_change {
2255 attach_orbit_controls_listeners(
2256 &mut attrs,
2257 effective_scene.as_deref(),
2258 self.width,
2259 self.height,
2260 cb,
2261 );
2262 }
2263 if let Some(scene) = effective_scene {
2264 let payload: std::sync::Arc<dyn std::any::Any + Send + Sync> = scene;
2265 attrs.push(Attribute::scene_payload_arc(payload));
2266 }
2267 View::new(NodeBlueprint::element(
2268 Tag::Canvas,
2269 self.class.unwrap_or_default(),
2270 attrs,
2271 self.children.unwrap_or_default(),
2272 ))
2273 }
2274}
2275
2276#[component]
2277pub fn PerspectiveCamera(
2278 fov: Option<f32>,
2279 aspect: Option<f32>,
2280 near: Option<f32>,
2281 far: Option<f32>,
2282 position: Option<[f32; 3]>,
2283 target: Option<[f32; 3]>,
2284) -> View {
2285 let mut attrs = Vec::new();
2286 if let Some(f) = fov {
2287 attrs.push(Attribute::property("data-fov", f.to_string()));
2288 }
2289 if let Some(a) = aspect {
2290 attrs.push(Attribute::property("data-aspect", a.to_string()));
2291 }
2292 if let Some(n) = near {
2293 attrs.push(Attribute::property("data-near", n.to_string()));
2294 }
2295 if let Some(fa) = far {
2296 attrs.push(Attribute::property("data-far", fa.to_string()));
2297 }
2298 if let Some(p) = position {
2299 attrs.push(Attribute::property(
2300 "data-position",
2301 format!("{},{},{}", p[0], p[1], p[2]),
2302 ));
2303 }
2304 if let Some(t) = target {
2305 attrs.push(Attribute::property(
2306 "data-target",
2307 format!("{},{},{}", t[0], t[1], t[2]),
2308 ));
2309 }
2310 View::new(NodeBlueprint::element(
2311 Tag::Custom("PerspectiveCamera"),
2312 strata_dom::ClassList::default(),
2313 attrs,
2314 Vec::new(),
2315 ))
2316}
2317
2318#[component]
2319pub fn OrthographicCamera(
2320 left: Option<f32>,
2321 right: Option<f32>,
2322 top: Option<f32>,
2323 bottom: Option<f32>,
2324 near: Option<f32>,
2325 far: Option<f32>,
2326 position: Option<[f32; 3]>,
2327 target: Option<[f32; 3]>,
2328) -> View {
2329 let mut attrs = Vec::new();
2330 if let Some(v) = left {
2331 attrs.push(Attribute::property("data-left", v.to_string()));
2332 }
2333 if let Some(v) = right {
2334 attrs.push(Attribute::property("data-right", v.to_string()));
2335 }
2336 if let Some(v) = top {
2337 attrs.push(Attribute::property("data-top", v.to_string()));
2338 }
2339 if let Some(v) = bottom {
2340 attrs.push(Attribute::property("data-bottom", v.to_string()));
2341 }
2342 if let Some(v) = near {
2343 attrs.push(Attribute::property("data-near", v.to_string()));
2344 }
2345 if let Some(v) = far {
2346 attrs.push(Attribute::property("data-far", v.to_string()));
2347 }
2348 if let Some(p) = position {
2349 attrs.push(Attribute::property(
2350 "data-position",
2351 format!("{},{},{}", p[0], p[1], p[2]),
2352 ));
2353 }
2354 if let Some(t) = target {
2355 attrs.push(Attribute::property(
2356 "data-target",
2357 format!("{},{},{}", t[0], t[1], t[2]),
2358 ));
2359 }
2360 View::new(NodeBlueprint::element(
2361 Tag::Custom("OrthographicCamera"),
2362 strata_dom::ClassList::default(),
2363 attrs,
2364 Vec::new(),
2365 ))
2366}
2367
2368#[component]
2369pub fn AmbientLight(color: Option<&'static str>, intensity: Option<f32>) -> View {
2370 let mut attrs = Vec::new();
2371 if let Some(c) = color {
2372 attrs.push(Attribute::property("data-color", c));
2373 }
2374 if let Some(i) = intensity {
2375 attrs.push(Attribute::property("data-intensity", i.to_string()));
2376 }
2377 View::new(NodeBlueprint::element(
2378 Tag::Custom("AmbientLight"),
2379 strata_dom::ClassList::default(),
2380 attrs,
2381 Vec::new(),
2382 ))
2383}
2384
2385#[component]
2386pub fn DirectionalLight(
2387 position: Option<[f32; 3]>,
2388 color: Option<&'static str>,
2389 intensity: Option<f32>,
2390 cast_shadow: Option<bool>,
2391) -> View {
2392 let mut attrs = Vec::new();
2393 if let Some(p) = position {
2394 attrs.push(Attribute::property(
2395 "data-position",
2396 format!("{},{},{}", p[0], p[1], p[2]),
2397 ));
2398 }
2399 if let Some(c) = color {
2400 attrs.push(Attribute::property("data-color", c));
2401 }
2402 if let Some(i) = intensity {
2403 attrs.push(Attribute::property("data-intensity", i.to_string()));
2404 }
2405 if let Some(s) = cast_shadow {
2406 attrs.push(Attribute::property("data-cast-shadow", s.to_string()));
2407 }
2408 View::new(NodeBlueprint::element(
2409 Tag::Custom("DirectionalLight"),
2410 strata_dom::ClassList::default(),
2411 attrs,
2412 Vec::new(),
2413 ))
2414}
2415
2416#[component]
2417pub fn PointLight(
2418 position: Option<[f32; 3]>,
2419 color: Option<&'static str>,
2420 intensity: Option<f32>,
2421 distance: Option<f32>,
2422) -> View {
2423 let mut attrs = Vec::new();
2424 if let Some(p) = position {
2425 attrs.push(Attribute::property(
2426 "data-position",
2427 format!("{},{},{}", p[0], p[1], p[2]),
2428 ));
2429 }
2430 if let Some(c) = color {
2431 attrs.push(Attribute::property("data-color", c));
2432 }
2433 if let Some(i) = intensity {
2434 attrs.push(Attribute::property("data-intensity", i.to_string()));
2435 }
2436 if let Some(d) = distance {
2437 attrs.push(Attribute::property("data-distance", d.to_string()));
2438 }
2439 View::new(NodeBlueprint::element(
2440 Tag::Custom("PointLight"),
2441 strata_dom::ClassList::default(),
2442 attrs,
2443 Vec::new(),
2444 ))
2445}
2446
2447#[component]
2448pub fn Mesh(
2449 position: Option<[f32; 3]>,
2450 rotation: Option<[f32; 3]>,
2451 scale: Option<[f32; 3]>,
2452 children: Option<Vec<NodeBlueprint>>,
2453) -> View {
2454 let mut attrs = Vec::new();
2455 if let Some(p) = position {
2456 attrs.push(Attribute::property(
2457 "data-position",
2458 format!("{},{},{}", p[0], p[1], p[2]),
2459 ));
2460 }
2461 if let Some(r) = rotation {
2462 attrs.push(Attribute::property(
2463 "data-rotation",
2464 format!("{},{},{}", r[0], r[1], r[2]),
2465 ));
2466 }
2467 if let Some(s) = scale {
2468 attrs.push(Attribute::property(
2469 "data-scale",
2470 format!("{},{},{}", s[0], s[1], s[2]),
2471 ));
2472 }
2473 View::new(NodeBlueprint::element(
2474 Tag::Custom("Mesh"),
2475 strata_dom::ClassList::default(),
2476 attrs,
2477 children.unwrap_or_default(),
2478 ))
2479}
2480
2481#[component]
2482pub fn BoxGeometry(width: Option<f32>, height: Option<f32>, depth: Option<f32>) -> View {
2483 let mut attrs = Vec::new();
2484 if let Some(w) = width {
2485 attrs.push(Attribute::property("data-width", w.to_string()));
2486 }
2487 if let Some(h) = height {
2488 attrs.push(Attribute::property("data-height", h.to_string()));
2489 }
2490 if let Some(d) = depth {
2491 attrs.push(Attribute::property("data-depth", d.to_string()));
2492 }
2493 View::new(NodeBlueprint::element(
2494 Tag::Custom("BoxGeometry"),
2495 strata_dom::ClassList::default(),
2496 attrs,
2497 Vec::new(),
2498 ))
2499}
2500
2501#[component]
2502pub fn SphereGeometry(
2503 radius: Option<f32>,
2504 width_segments: Option<u32>,
2505 height_segments: Option<u32>,
2506) -> View {
2507 let mut attrs = Vec::new();
2508 if let Some(r) = radius {
2509 attrs.push(Attribute::property("data-radius", r.to_string()));
2510 }
2511 if let Some(w) = width_segments {
2512 attrs.push(Attribute::property("data-width-segments", w.to_string()));
2513 }
2514 if let Some(h) = height_segments {
2515 attrs.push(Attribute::property("data-height-segments", h.to_string()));
2516 }
2517 View::new(NodeBlueprint::element(
2518 Tag::Custom("SphereGeometry"),
2519 strata_dom::ClassList::default(),
2520 attrs,
2521 Vec::new(),
2522 ))
2523}
2524
2525#[component]
2526pub fn PlaneGeometry(width: Option<f32>, height: Option<f32>) -> View {
2527 let mut attrs = Vec::new();
2528 if let Some(w) = width {
2529 attrs.push(Attribute::property("data-width", w.to_string()));
2530 }
2531 if let Some(h) = height {
2532 attrs.push(Attribute::property("data-height", h.to_string()));
2533 }
2534 View::new(NodeBlueprint::element(
2535 Tag::Custom("PlaneGeometry"),
2536 strata_dom::ClassList::default(),
2537 attrs,
2538 Vec::new(),
2539 ))
2540}
2541
2542#[component]
2543pub fn CylinderGeometry(
2544 radius_top: Option<f32>,
2545 radius_bottom: Option<f32>,
2546 height: Option<f32>,
2547 radial_segments: Option<u32>,
2548) -> View {
2549 let mut attrs = Vec::new();
2550 if let Some(rt) = radius_top {
2551 attrs.push(Attribute::property("data-radius-top", rt.to_string()));
2552 }
2553 if let Some(rb) = radius_bottom {
2554 attrs.push(Attribute::property("data-radius-bottom", rb.to_string()));
2555 }
2556 if let Some(h) = height {
2557 attrs.push(Attribute::property("data-height", h.to_string()));
2558 }
2559 if let Some(rs) = radial_segments {
2560 attrs.push(Attribute::property("data-radial-segments", rs.to_string()));
2561 }
2562 View::new(NodeBlueprint::element(
2563 Tag::Custom("CylinderGeometry"),
2564 strata_dom::ClassList::default(),
2565 attrs,
2566 Vec::new(),
2567 ))
2568}
2569
2570#[component]
2571pub fn StandardMaterial(
2572 color: Option<&'static str>,
2573 roughness: Option<f32>,
2574 metalness: Option<f32>,
2575) -> View {
2576 let mut attrs = Vec::new();
2577 if let Some(c) = color {
2578 attrs.push(Attribute::property("data-color", c));
2579 }
2580 if let Some(r) = roughness {
2581 attrs.push(Attribute::property("data-roughness", r.to_string()));
2582 }
2583 if let Some(m) = metalness {
2584 attrs.push(Attribute::property("data-metalness", m.to_string()));
2585 }
2586 View::new(NodeBlueprint::element(
2587 Tag::Custom("StandardMaterial"),
2588 strata_dom::ClassList::default(),
2589 attrs,
2590 Vec::new(),
2591 ))
2592}
2593
2594#[component]
2595pub fn ShaderMaterial(
2596 glsl_fragment: Option<&'static str>,
2597 uniform_time: Option<f32>,
2598 uniforms: Option<strata_js::JsValue>,
2599) -> View {
2600 let mut attrs = Vec::new();
2601 if let Some(g) = glsl_fragment {
2602 attrs.push(Attribute::property("data-glsl", g));
2603 }
2604 if let Some(t) = uniform_time {
2605 attrs.push(Attribute::property("data-time", t.to_string()));
2606 }
2607 View::new(NodeBlueprint::element(
2608 Tag::Custom("ShaderMaterial"),
2609 strata_dom::ClassList::default(),
2610 attrs,
2611 Vec::new(),
2612 ))
2613}
2614
2615fn get_3d_attr<'a>(attrs: &'a [strata_dom::Attribute], key: &str) -> Option<&'a str> {
2616 attrs.iter().find_map(|attr| {
2617 if let strata_dom::Attribute::Property { key: k, value: v } = attr {
2618 if k == key {
2619 return Some(v.as_str());
2620 }
2621 }
2622 None
2623 })
2624}
2625
2626fn parse_3d_vec3(s: &str) -> Option<[f32; 3]> {
2627 let mut parts = s.split(',');
2628 let x = parts.next()?.trim().parse::<f32>().ok()?;
2629 let y = parts.next()?.trim().parse::<f32>().ok()?;
2630 let z = parts.next()?.trim().parse::<f32>().ok()?;
2631 Some([x, y, z])
2632}
2633
2634pub fn extract_scene3d_arc_from_blueprint(
2638 canvas_node: &NodeBlueprint,
2639) -> Option<std::sync::Arc<Scene3D>> {
2640 let NodeBlueprint::Element {
2641 attributes,
2642 children,
2643 ..
2644 } = canvas_node
2645 else {
2646 return None;
2647 };
2648
2649 let mut payload_scene: Option<std::sync::Arc<Scene3D>> = None;
2650 for attr in attributes {
2651 if let strata_dom::Attribute::ScenePayload(any) = attr {
2652 if let Ok(arc_scene) = any.clone().downcast::<Scene3D>() {
2653 payload_scene = Some(arc_scene);
2654 break;
2655 }
2656 if let Some(nested_arc) = any.downcast_ref::<std::sync::Arc<Scene3D>>() {
2657 payload_scene = Some(std::sync::Arc::clone(nested_arc));
2658 break;
2659 }
2660 }
2661 }
2662
2663 if let Some(arc_scene) = payload_scene {
2664 if children.is_empty() {
2665 return Some(arc_scene);
2666 }
2667 return Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
2668 canvas_node,
2669 )));
2670 }
2671
2672 Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
2673 canvas_node,
2674 )))
2675}
2676
2677pub fn compile_scene3d_from_blueprint(canvas_node: &NodeBlueprint) -> Scene3D {
2680 let (attributes, children) = match canvas_node {
2681 NodeBlueprint::Element {
2682 attributes,
2683 children,
2684 ..
2685 } => (attributes, children),
2686 _ => return Scene3D::new(),
2687 };
2688
2689 let mut scene = attributes
2690 .iter()
2691 .find_map(|attr| match attr {
2692 strata_dom::Attribute::ScenePayload(any) => {
2693 any.downcast_ref::<Scene3D>().cloned().or_else(|| {
2694 any.downcast_ref::<std::sync::Arc<Scene3D>>()
2695 .map(|a| (**a).clone())
2696 })
2697 }
2698 _ => None,
2699 })
2700 .unwrap_or_default();
2701
2702 for child in children {
2703 if let NodeBlueprint::Element {
2704 tag,
2705 attributes,
2706 children: mesh_children,
2707 ..
2708 } = child
2709 {
2710 match tag {
2711 Tag::Custom("PerspectiveCamera") => {
2712 let fov = get_3d_attr(attributes, "data-fov")
2713 .and_then(|v| v.parse().ok())
2714 .unwrap_or(60.0);
2715 let near = get_3d_attr(attributes, "data-near")
2716 .and_then(|v| v.parse().ok())
2717 .unwrap_or(0.1);
2718 let far = get_3d_attr(attributes, "data-far")
2719 .and_then(|v| v.parse().ok())
2720 .unwrap_or(1000.0);
2721 let position = get_3d_attr(attributes, "data-position")
2722 .and_then(parse_3d_vec3)
2723 .unwrap_or([0.0, 2.0, 5.0]);
2724 let target = get_3d_attr(attributes, "data-target")
2725 .and_then(parse_3d_vec3)
2726 .unwrap_or([0.0, 0.0, 0.0]);
2727 scene.camera = Camera3D::Perspective {
2728 fov_horizontal_deg: fov,
2729 near,
2730 far,
2731 position,
2732 target,
2733 };
2734 }
2735 Tag::Custom("OrthographicCamera") => {
2736 let left = get_3d_attr(attributes, "data-left")
2737 .and_then(|v| v.parse().ok())
2738 .unwrap_or(-5.0);
2739 let right = get_3d_attr(attributes, "data-right")
2740 .and_then(|v| v.parse().ok())
2741 .unwrap_or(5.0);
2742 let top = get_3d_attr(attributes, "data-top")
2743 .and_then(|v| v.parse().ok())
2744 .unwrap_or(5.0);
2745 let bottom = get_3d_attr(attributes, "data-bottom")
2746 .and_then(|v| v.parse().ok())
2747 .unwrap_or(-5.0);
2748 let near = get_3d_attr(attributes, "data-near")
2749 .and_then(|v| v.parse().ok())
2750 .unwrap_or(0.1);
2751 let far = get_3d_attr(attributes, "data-far")
2752 .and_then(|v| v.parse().ok())
2753 .unwrap_or(1000.0);
2754 let position = get_3d_attr(attributes, "data-position")
2755 .and_then(parse_3d_vec3)
2756 .unwrap_or([0.0, 2.0, 5.0]);
2757 let target = get_3d_attr(attributes, "data-target")
2758 .and_then(parse_3d_vec3)
2759 .unwrap_or([0.0, 0.0, 0.0]);
2760 scene.camera = Camera3D::Orthographic {
2761 left,
2762 right,
2763 top,
2764 bottom,
2765 near,
2766 far,
2767 position,
2768 target,
2769 };
2770 }
2771 Tag::Custom("AmbientLight") => {
2772 let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2773 let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2774 let intensity = get_3d_attr(attributes, "data-intensity")
2775 .and_then(|v| v.parse().ok())
2776 .unwrap_or(1.0);
2777 scene.add_light(Light3D::Ambient { color, intensity });
2778 }
2779 Tag::Custom("DirectionalLight") => {
2780 let pos = get_3d_attr(attributes, "data-position")
2781 .and_then(parse_3d_vec3)
2782 .unwrap_or([5.0, 10.0, 7.0]);
2783 let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2784 let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2785 let intensity = get_3d_attr(attributes, "data-intensity")
2786 .and_then(|v| v.parse().ok())
2787 .unwrap_or(1.0);
2788 let cast_shadow = get_3d_attr(attributes, "data-cast-shadow")
2789 .and_then(|v| v.parse().ok())
2790 .unwrap_or(false);
2791 scene.add_light(Light3D::Directional {
2792 position: pos,
2793 color,
2794 intensity,
2795 cast_shadow,
2796 });
2797 }
2798 Tag::Custom("PointLight") => {
2799 let pos = get_3d_attr(attributes, "data-position")
2800 .and_then(parse_3d_vec3)
2801 .unwrap_or([0.0, 2.0, 0.0]);
2802 let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2803 let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2804 let intensity = get_3d_attr(attributes, "data-intensity")
2805 .and_then(|v| v.parse().ok())
2806 .unwrap_or(1.0);
2807 let distance = get_3d_attr(attributes, "data-distance")
2808 .and_then(|v| v.parse().ok())
2809 .unwrap_or(10.0);
2810 scene.add_light(Light3D::Point {
2811 position: pos,
2812 color,
2813 intensity,
2814 distance,
2815 });
2816 }
2817 Tag::Custom("Mesh") => {
2818 let position = get_3d_attr(attributes, "data-position")
2819 .and_then(parse_3d_vec3)
2820 .unwrap_or([0.0, 0.0, 0.0]);
2821 let rotation = get_3d_attr(attributes, "data-rotation")
2822 .and_then(parse_3d_vec3)
2823 .unwrap_or([0.0, 0.0, 0.0]);
2824 let scale = get_3d_attr(attributes, "data-scale")
2825 .and_then(parse_3d_vec3)
2826 .unwrap_or([1.0, 1.0, 1.0]);
2827 let transform = Transform3D {
2828 position,
2829 rotation,
2830 scale,
2831 };
2832
2833 let mut geometry = Geometry3D::Box {
2834 width: 1.0,
2835 height: 1.0,
2836 depth: 1.0,
2837 };
2838 let mut material = Material3D::default();
2839
2840 for sub in mesh_children {
2841 if let NodeBlueprint::Element {
2842 tag: sub_tag,
2843 attributes: sub_attrs,
2844 ..
2845 } = sub
2846 {
2847 match sub_tag {
2848 Tag::Custom("BoxGeometry") => {
2849 let width = get_3d_attr(sub_attrs, "data-width")
2850 .and_then(|v| v.parse().ok())
2851 .unwrap_or(1.0);
2852 let height = get_3d_attr(sub_attrs, "data-height")
2853 .and_then(|v| v.parse().ok())
2854 .unwrap_or(1.0);
2855 let depth = get_3d_attr(sub_attrs, "data-depth")
2856 .and_then(|v| v.parse().ok())
2857 .unwrap_or(1.0);
2858 geometry = Geometry3D::Box {
2859 width,
2860 height,
2861 depth,
2862 };
2863 }
2864 Tag::Custom("SphereGeometry") => {
2865 let radius = get_3d_attr(sub_attrs, "data-radius")
2866 .and_then(|v| v.parse().ok())
2867 .unwrap_or(1.0);
2868 let width_segments =
2869 get_3d_attr(sub_attrs, "data-width-segments")
2870 .and_then(|v| v.parse().ok())
2871 .unwrap_or(16);
2872 let height_segments =
2873 get_3d_attr(sub_attrs, "data-height-segments")
2874 .and_then(|v| v.parse().ok())
2875 .unwrap_or(16);
2876 geometry = Geometry3D::Sphere {
2877 radius,
2878 width_segments,
2879 height_segments,
2880 };
2881 }
2882 Tag::Custom("PlaneGeometry") => {
2883 let width = get_3d_attr(sub_attrs, "data-width")
2884 .and_then(|v| v.parse().ok())
2885 .unwrap_or(1.0);
2886 let height = get_3d_attr(sub_attrs, "data-height")
2887 .and_then(|v| v.parse().ok())
2888 .unwrap_or(1.0);
2889 geometry = Geometry3D::Plane { width, height };
2890 }
2891 Tag::Custom("CylinderGeometry") => {
2892 let radius_top = get_3d_attr(sub_attrs, "data-radius-top")
2893 .and_then(|v| v.parse().ok())
2894 .unwrap_or(1.0);
2895 let radius_bottom =
2896 get_3d_attr(sub_attrs, "data-radius-bottom")
2897 .and_then(|v| v.parse().ok())
2898 .unwrap_or(1.0);
2899 let height = get_3d_attr(sub_attrs, "data-height")
2900 .and_then(|v| v.parse().ok())
2901 .unwrap_or(1.0);
2902 let radial_segments =
2903 get_3d_attr(sub_attrs, "data-radial-segments")
2904 .and_then(|v| v.parse().ok())
2905 .unwrap_or(16);
2906 geometry = Geometry3D::Cylinder {
2907 radius_top,
2908 radius_bottom,
2909 height,
2910 radial_segments,
2911 };
2912 }
2913 Tag::Custom("StandardMaterial") => {
2914 let color_str =
2915 get_3d_attr(sub_attrs, "data-color").unwrap_or("#ffffff");
2916 let color = strata_style::parse_color(color_str)
2917 .unwrap_or(Color::WHITE);
2918 let roughness = get_3d_attr(sub_attrs, "data-roughness")
2919 .and_then(|v| v.parse().ok())
2920 .unwrap_or(0.5);
2921 let metalness = get_3d_attr(sub_attrs, "data-metalness")
2922 .and_then(|v| v.parse().ok())
2923 .unwrap_or(0.0);
2924 material = Material3D::Standard {
2925 color,
2926 roughness,
2927 metalness,
2928 emissive: None,
2929 };
2930 }
2931 Tag::Custom("ShaderMaterial") => {
2932 let glsl =
2933 get_3d_attr(sub_attrs, "data-glsl").map(|s| s.to_string());
2934 let time = get_3d_attr(sub_attrs, "data-time")
2935 .and_then(|v| v.parse().ok())
2936 .unwrap_or(0.0);
2937 let mut uniforms = BTreeMap::new();
2938 uniforms.insert("u_time".to_string(), time);
2939 material = Material3D::Shader {
2940 vertex_shader: None,
2941 fragment_shader: None,
2942 glsl_fragment: glsl,
2943 uniforms,
2944 };
2945 }
2946 _ => {}
2947 }
2948 }
2949 }
2950
2951 scene.add_mesh(Mesh3D {
2952 geometry,
2953 material,
2954 transform,
2955 });
2956 }
2957 _ => {}
2958 }
2959 }
2960 }
2961
2962 scene
2963}