1use bevy_ecs::component::Component;
2use bevy_ecs::entity::Entity;
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6#[derive(Component, Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub struct SceneId(pub Uuid);
10
11impl SceneId {
12 #[must_use]
13 pub fn new() -> Self {
14 Self(Uuid::new_v4())
15 }
16}
17
18impl Default for SceneId {
19 fn default() -> Self {
20 Self::new()
21 }
22}
23
24#[derive(Component, Clone, Copy, Debug, PartialEq)]
26pub struct GlobalTransform {
27 pub matrix: [[f32; 4]; 4],
28}
29
30impl Default for GlobalTransform {
31 fn default() -> Self {
32 Self {
33 matrix: nalgebra::Matrix4::<f32>::identity().into(),
34 }
35 }
36}
37
38#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
39pub struct Parent(pub Entity);
40
41#[derive(Component, Clone, Debug, Default, PartialEq, Eq)]
42pub struct Children(pub Vec<Entity>);
43
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub enum Projection {
46 Perspective {
47 vertical_fov_radians: f32,
48 near: f32,
49 far: f32,
50 },
51 Orthographic {
52 vertical_size: f32,
53 near: f32,
54 far: f32,
55 },
56}
57
58impl Default for Projection {
59 fn default() -> Self {
60 Self::Perspective {
61 vertical_fov_radians: std::f32::consts::FRAC_PI_3,
62 near: 0.1,
63 far: 1_000.0,
64 }
65 }
66}
67
68#[derive(Component, Clone, Copy, Debug, Default, PartialEq)]
69pub struct Camera {
70 pub projection: Projection,
71 pub active: bool,
72 pub priority: i32,
73}
74
75#[derive(Component, Clone, Debug, PartialEq, Eq)]
76pub struct Name(pub String);
77
78#[derive(
83 Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
84)]
85pub struct ObjectClasses {
86 pub names: Vec<String>,
88}
89
90impl ObjectClasses {
91 #[must_use]
93 pub fn new(classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
94 let mut result = Self::default();
95 for class in classes {
96 result.add(class);
97 }
98 result
99 }
100
101 pub fn add(&mut self, class: impl Into<String>) -> bool {
103 let class = class.into();
104 let class = class.trim();
105 if class.is_empty() || self.contains(class) {
106 return false;
107 }
108 self.names.push(class.to_owned());
109 true
110 }
111
112 pub fn remove(&mut self, class: &str) -> bool {
114 let old_len = self.names.len();
115 self.names.retain(|current| current != class);
116 self.names.len() != old_len
117 }
118
119 #[must_use]
121 pub fn contains(&self, class: &str) -> bool {
122 self.names.iter().any(|current| current == class)
123 }
124}
125
126#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
127pub struct DirectionalLight {
128 pub color: [f32; 3],
129 pub illuminance: f32,
130 pub shadows: bool,
131}
132
133impl Default for DirectionalLight {
134 fn default() -> Self {
135 Self {
136 color: [1.0; 3],
137 illuminance: 100_000.0,
138 shadows: true,
139 }
140 }
141}
142
143#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
144pub struct PointLight {
145 pub color: [f32; 3],
146 pub intensity: f32,
147 pub range: f32,
148}
149
150#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
151pub struct SpotLight {
152 pub color: [f32; 3],
153 pub intensity: f32,
154 pub range: f32,
155 pub inner_angle: f32,
157 pub outer_angle: f32,
159}
160
161impl Default for SpotLight {
162 fn default() -> Self {
163 Self {
164 color: [1.0; 3],
165 intensity: 1_000.0,
166 range: 10.0,
167 inner_angle: 20.0_f32.to_radians(),
168 outer_angle: 35.0_f32.to_radians(),
169 }
170 }
171}
172
173impl Default for PointLight {
174 fn default() -> Self {
175 Self {
176 color: [1.0; 3],
177 intensity: 1_000.0,
178 range: 10.0,
179 }
180 }
181}
182
183#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
184pub struct AmbientLight {
185 pub color: [f32; 3],
186 pub intensity: f32,
187}
188
189impl Default for AmbientLight {
190 fn default() -> Self {
191 Self {
192 color: [1.0; 3],
193 intensity: 0.1,
194 }
195 }
196}
197
198#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
202pub struct SkyLight {
203 pub sky_color: [f32; 3],
204 pub ground_color: [f32; 3],
205 pub intensity: f32,
206}
207
208impl Default for SkyLight {
209 fn default() -> Self {
210 Self {
211 sky_color: [0.6, 0.75, 1.0],
212 ground_color: [0.3, 0.25, 0.2],
213 intensity: 0.3,
214 }
215 }
216}
217
218#[derive(
220 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
221)]
222pub enum ToneMapper {
223 #[default]
225 Linear,
226 Reinhard,
228 Aces,
230}
231
232#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
236pub struct ToneMapping {
237 pub mapper: ToneMapper,
238 pub exposure: f32,
240}
241
242impl Default for ToneMapping {
243 fn default() -> Self {
244 Self {
245 mapper: ToneMapper::Linear,
246 exposure: 1.0,
247 }
248 }
249}
250
251#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
255pub enum RenderBounds {
256 Sphere { center: [f32; 3], radius: f32 },
257 Aabb { min: [f32; 3], max: [f32; 3] },
258}
259
260impl Default for RenderBounds {
262 fn default() -> Self {
263 RenderBounds::Aabb {
264 min: [-0.5; 3],
265 max: [0.5; 3],
266 }
267 }
268}
269
270impl RenderBounds {
271 pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
277 let matrix = nalgebra::Matrix4::from(*matrix);
278 let linear = matrix.fixed_view::<3, 3>(0, 0);
279 let translation = matrix.fixed_view::<3, 1>(0, 3);
280 match *self {
281 RenderBounds::Sphere { center, radius } => {
282 let scale = (0..3)
283 .map(|axis| linear.column(axis).norm())
284 .fold(0.0_f32, f32::max);
285 let center =
286 linear * nalgebra::Vector3::from(center) + translation;
287 RenderBounds::Sphere {
288 center: center.into(),
289 radius: radius * scale,
290 }
291 }
292 RenderBounds::Aabb { min, max } => {
293 let mut world_min: [f32; 3] = translation.into();
296 let mut world_max = world_min;
297 for row in 0..3 {
298 for column in 0..3 {
299 let a = linear[(row, column)] * min[column];
300 let b = linear[(row, column)] * max[column];
301 world_min[row] += a.min(b);
302 world_max[row] += a.max(b);
303 }
304 }
305 RenderBounds::Aabb {
306 min: world_min,
307 max: world_max,
308 }
309 }
310 }
311 }
312}
313
314#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
315pub struct Visibility {
316 pub visible: bool,
317}
318
319impl Default for Visibility {
320 fn default() -> Self {
321 Self { visible: true }
322 }
323}
324
325#[derive(
326 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
327)]
328pub enum QualityProfile {
329 Auto,
330 Eco,
331 #[default]
332 Balanced,
333 High,
334}
335
336#[derive(
338 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
339)]
340pub enum CullingMode {
341 #[default]
344 Auto,
345 Disabled,
347 Frustum,
349 FrustumAndOcclusion,
353}
354
355#[derive(
359 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
360)]
361pub enum Antialiasing {
362 #[default]
363 Auto,
364 Off,
365 Msaa2,
366 Msaa4,
367}
368
369#[derive(
371 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
372)]
373pub enum ShadowQuality {
374 #[default]
375 Auto,
376 Low,
378 Medium,
380 High,
382}
383
384#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
385pub struct RenderSettings {
386 pub quality: QualityProfile,
387 pub vsync: bool,
388 pub limit_fps: bool,
389 pub max_fps: u32,
390 pub render_scale: f32,
393 pub background_color: [f32; 4],
395 pub culling: CullingMode,
396 pub antialiasing: Antialiasing,
397 pub shadows: ShadowQuality,
398 pub reflections: bool,
401}
402
403impl Default for RenderSettings {
404 fn default() -> Self {
405 Self {
406 quality: QualityProfile::Auto,
407 vsync: false,
408 limit_fps: false,
409 max_fps: 120,
410 render_scale: 1.0,
411 background_color: [0.025, 0.04, 0.07, 1.0],
412 culling: CullingMode::Auto,
413 antialiasing: Antialiasing::Auto,
414 shadows: ShadowQuality::Auto,
415 reflections: true,
416 }
417 }
418}
419
420#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
421pub struct PhysicsSettings {
422 pub gravity: [f32; 3],
423 pub enabled: bool,
424}
425
426#[derive(
430 bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
431)]
432pub struct PhysicsBackendStatus {
433 pub gameplay_available: bool,
434 pub gpu_dynamic_available: bool,
435}
436
437impl Default for PhysicsSettings {
438 fn default() -> Self {
439 Self {
440 gravity: [0.0, -9.81, 0.0],
441 enabled: true,
442 }
443 }
444}
445
446#[derive(
448 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
449)]
450pub enum SimulationClass {
451 None,
453 Static,
455 #[default]
457 #[serde(alias = "Gameplay")]
458 Cpu,
459 #[serde(alias = "GpuDynamic")]
461 Gpu,
462}
463
464#[allow(non_upper_case_globals)]
465impl SimulationClass {
466 #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
467 pub const Gameplay: Self = Self::Cpu;
468 #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
469 pub const GpuDynamic: Self = Self::Gpu;
470}
471
472#[derive(
474 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
475)]
476pub enum PhysicsSolver {
477 #[default]
478 Full,
479 Simplified,
480 NoCollision,
481 Space,
482 Custom,
483}
484
485#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
491pub struct PhysicsBody {
492 pub simulation: SimulationClass,
493 pub solver: PhysicsSolver,
494 pub custom_shader: Option<String>,
495}
496
497impl Default for PhysicsBody {
498 fn default() -> Self {
499 Self {
500 simulation: SimulationClass::Cpu,
501 solver: PhysicsSolver::Full,
502 custom_shader: None,
503 }
504 }
505}
506
507impl PhysicsBody {
508 #[must_use]
509 pub fn participates_in_dynamic_simulation(&self) -> bool {
510 matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
511 }
512
513 #[must_use]
514 pub fn uses_gpu(&self) -> bool {
515 self.simulation == SimulationClass::Gpu
516 }
517}
518
519#[derive(
520 Component,
521 Clone,
522 Copy,
523 Debug,
524 Default,
525 Deserialize,
526 PartialEq,
527 Eq,
528 Serialize,
529)]
530pub enum RigidBodyKind {
531 Fixed,
532 #[default]
533 Dynamic,
534 Kinematic,
535}
536
537#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
538pub struct RigidBody {
539 pub kind: RigidBodyKind,
540 pub mass: f32,
541 pub linear_velocity: [f32; 3],
542 pub angular_velocity: [f32; 3],
543 pub gravity_scale: f32,
544}
545
546impl Default for RigidBody {
547 fn default() -> Self {
548 Self {
549 kind: RigidBodyKind::Dynamic,
550 mass: 1.0,
551 linear_velocity: [0.0; 3],
552 angular_velocity: [0.0; 3],
553 gravity_scale: 1.0,
554 }
555 }
556}
557
558#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
559pub enum ColliderShape {
560 Box {
561 half_extents: [f32; 3],
562 },
563 Sphere {
564 radius: f32,
565 },
566 Capsule {
567 half_height: f32,
568 radius: f32,
569 },
570 ConvexMesh,
573 TriangleMesh,
576}
577
578#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
579pub struct Collider {
580 pub shape: ColliderShape,
581 pub friction: f32,
582 pub restitution: f32,
583 pub sensor: bool,
584}
585
586impl Default for Collider {
587 fn default() -> Self {
588 Self {
589 shape: ColliderShape::Box {
590 half_extents: [0.5; 3],
591 },
592 friction: 0.5,
593 restitution: 0.0,
594 sensor: false,
595 }
596 }
597}
598
599#[derive(
600 Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
601)]
602pub struct CollisionLayers {
603 pub memberships: u32,
604 pub filters: u32,
605}
606
607impl Default for CollisionLayers {
608 fn default() -> Self {
609 Self {
610 memberships: u32::MAX,
611 filters: u32::MAX,
612 }
613 }
614}
615
616#[cfg(test)]
617mod tests {
618 use super::*;
619 use bevy_ecs::{component::Component, resource::Resource};
620
621 fn assert_component<T: Component>() {}
622 fn assert_resource<T: Resource>() {}
623
624 #[test]
625 fn canonical_types_implement_bevy_ecs_traits() {
626 assert_component::<SceneId>();
627 assert_component::<GlobalTransform>();
628 assert_component::<Parent>();
629 assert_component::<Children>();
630 assert_component::<Camera>();
631 assert_component::<Name>();
632 assert_component::<ObjectClasses>();
633 assert_component::<DirectionalLight>();
634 assert_component::<PointLight>();
635 assert_component::<SpotLight>();
636 assert_component::<AmbientLight>();
637 assert_component::<SkyLight>();
638 assert_component::<ToneMapping>();
639 assert_component::<RenderBounds>();
640 assert_component::<Visibility>();
641 assert_component::<PhysicsBody>();
642 assert_component::<RigidBodyKind>();
643 assert_component::<RigidBody>();
644 assert_component::<Collider>();
645 assert_component::<CollisionLayers>();
646
647 assert_resource::<RenderSettings>();
648 assert_resource::<PhysicsSettings>();
649 assert_resource::<PhysicsBackendStatus>();
650 }
651
652 #[test]
653 fn defaults_are_ready_for_a_basic_scene() {
654 let identity: [[f32; 4]; 4] =
655 nalgebra::Matrix4::<f32>::identity().into();
656 assert_eq!(GlobalTransform::default().matrix, identity);
657 assert!(Visibility::default().visible);
658 assert_eq!(RigidBody::default().mass, 1.0);
659 assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
660 assert_eq!(CollisionLayers::default().memberships, u32::MAX);
661 assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
662 }
663
664 #[test]
665 fn render_bounds_stay_conservative_under_transforms() {
666 use nalgebra::{Matrix4, Rotation3, Vector3};
667 let matrix: [[f32; 4]; 4] =
668 (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
669 * Rotation3::from_axis_angle(
670 &Vector3::z_axis(),
671 std::f32::consts::FRAC_PI_4,
672 )
673 .to_homogeneous()
674 * Matrix4::new_nonuniform_scaling(&Vector3::new(
675 2.0, 1.0, 3.0,
676 )))
677 .into();
678 let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
679 center: [1.0, 0.0, 0.0],
680 radius: 1.0,
681 })
682 .transformed(&matrix) else {
683 panic!("a sphere stays a sphere");
684 };
685 let half = std::f32::consts::FRAC_1_SQRT_2;
686 let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
687 for (value, expected) in center.iter().zip(expected) {
688 assert!((value - expected).abs() < 1e-5, "{center:?}");
689 }
690 assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
691
692 let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
693 min: [-1.0; 3],
694 max: [1.0; 3],
695 })
696 .transformed(&matrix) else {
697 panic!("a box stays a box");
698 };
699 let reach = 3.0 * half;
702 let expected_min = [10.0 - reach, -reach, -3.0];
703 let expected_max = [10.0 + reach, reach, 3.0];
704 for axis in 0..3 {
705 assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
706 assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
707 }
708 }
709
710 #[test]
711 fn object_classes_clean_and_edit_names() {
712 let mut classes =
713 ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
714 assert_eq!(classes.names, ["gravity", "enemy"]);
715 assert!(classes.contains("gravity"));
716 assert!(!classes.add("enemy"));
717 assert!(classes.remove("enemy"));
718 assert!(!classes.contains("enemy"));
719 }
720
721 #[test]
722 fn physics_body_helpers_follow_simulation_class() {
723 let mut body = PhysicsBody::default();
724 assert!(body.participates_in_dynamic_simulation());
725 assert!(!body.uses_gpu());
726
727 body.simulation = SimulationClass::Gpu;
728 assert!(body.participates_in_dynamic_simulation());
729 assert!(body.uses_gpu());
730
731 body.simulation = SimulationClass::Static;
732 assert!(!body.participates_in_dynamic_simulation());
733 assert!(!body.uses_gpu());
734 }
735}