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 pub viewport: Option<[f32; 4]>,
77}
78
79#[derive(Component, Clone, Debug, PartialEq, Eq)]
80pub struct Name(pub String);
81
82impl Name {
83 #[must_use]
84 pub fn as_str(&self) -> &str {
85 &self.0
86 }
87}
88
89impl std::ops::Deref for Name {
90 type Target = str;
91
92 fn deref(&self) -> &str {
93 &self.0
94 }
95}
96
97#[derive(
102 Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
103)]
104pub struct ObjectClasses {
105 pub names: Vec<String>,
107}
108
109impl ObjectClasses {
110 #[must_use]
112 pub fn new(classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
113 let mut result = Self::default();
114 for class in classes {
115 result.add(class);
116 }
117 result
118 }
119
120 pub fn add(&mut self, class: impl Into<String>) -> bool {
122 let class = class.into();
123 let class = class.trim();
124 if class.is_empty() || self.contains(class) {
125 return false;
126 }
127 self.names.push(class.to_owned());
128 true
129 }
130
131 pub fn remove(&mut self, class: &str) -> bool {
133 let old_len = self.names.len();
134 self.names.retain(|current| current != class);
135 self.names.len() != old_len
136 }
137
138 #[must_use]
140 pub fn contains(&self, class: &str) -> bool {
141 self.names.iter().any(|current| current == class)
142 }
143}
144
145#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
146pub struct DirectionalLight {
147 pub color: [f32; 3],
148 pub illuminance: f32,
149 pub shadows: bool,
150}
151
152impl DirectionalLight {
153 pub const LUX_PER_UNIT: f32 = 100_000.0;
156}
157
158impl Default for DirectionalLight {
159 fn default() -> Self {
160 Self {
161 color: [1.0; 3],
162 illuminance: 100_000.0,
163 shadows: true,
164 }
165 }
166}
167
168#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
169pub struct PointLight {
170 pub color: [f32; 3],
171 pub intensity: f32,
172 pub range: f32,
173 #[serde(default)]
176 pub shadows: bool,
177 #[serde(default)]
180 pub radius: f32,
181}
182
183#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
184pub struct SpotLight {
185 pub color: [f32; 3],
186 pub intensity: f32,
187 pub range: f32,
188 pub inner_angle: f32,
190 pub outer_angle: f32,
192 #[serde(default)]
195 pub shadows: bool,
196 #[serde(default)]
199 pub radius: f32,
200}
201
202impl Default for SpotLight {
203 fn default() -> Self {
204 Self {
205 color: [1.0; 3],
206 intensity: 1_000.0,
207 range: 10.0,
208 inner_angle: 20.0_f32.to_radians(),
209 outer_angle: 35.0_f32.to_radians(),
210 shadows: false,
211 radius: 0.0,
212 }
213 }
214}
215
216impl Default for PointLight {
217 fn default() -> Self {
218 Self {
219 color: [1.0; 3],
220 intensity: 1_000.0,
221 range: 10.0,
222 shadows: false,
223 radius: 0.0,
224 }
225 }
226}
227
228#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
229pub struct AmbientLight {
230 pub color: [f32; 3],
231 pub intensity: f32,
232}
233
234impl Default for AmbientLight {
235 fn default() -> Self {
236 Self {
237 color: [1.0; 3],
238 intensity: 0.1,
239 }
240 }
241}
242
243#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
247pub struct SkyLight {
248 pub sky_color: [f32; 3],
249 pub ground_color: [f32; 3],
250 pub intensity: f32,
251}
252
253impl Default for SkyLight {
254 fn default() -> Self {
255 Self {
256 sky_color: [0.6, 0.75, 1.0],
257 ground_color: [0.3, 0.25, 0.2],
258 intensity: 0.3,
259 }
260 }
261}
262
263#[derive(
265 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
266)]
267pub enum ToneMapper {
268 #[default]
270 Linear,
271 Reinhard,
273 Aces,
275}
276
277#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
281pub struct ToneMapping {
282 pub mapper: ToneMapper,
283 pub exposure: f32,
285}
286
287impl Default for ToneMapping {
288 fn default() -> Self {
289 Self {
290 mapper: ToneMapper::Linear,
291 exposure: 1.0,
292 }
293 }
294}
295
296#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
300pub enum RenderBounds {
301 Sphere { center: [f32; 3], radius: f32 },
302 Aabb { min: [f32; 3], max: [f32; 3] },
303}
304
305impl Default for RenderBounds {
307 fn default() -> Self {
308 RenderBounds::Aabb {
309 min: [-0.5; 3],
310 max: [0.5; 3],
311 }
312 }
313}
314
315impl RenderBounds {
316 pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
322 let matrix = nalgebra::Matrix4::from(*matrix);
323 let linear = matrix.fixed_view::<3, 3>(0, 0);
324 let translation = matrix.fixed_view::<3, 1>(0, 3);
325 match *self {
326 RenderBounds::Sphere { center, radius } => {
327 let scale = (0..3)
328 .map(|axis| linear.column(axis).norm())
329 .fold(0.0_f32, f32::max);
330 let center =
331 linear * nalgebra::Vector3::from(center) + translation;
332 RenderBounds::Sphere {
333 center: center.into(),
334 radius: radius * scale,
335 }
336 }
337 RenderBounds::Aabb { min, max } => {
338 let mut world_min: [f32; 3] = translation.into();
341 let mut world_max = world_min;
342 for row in 0..3 {
343 for column in 0..3 {
344 let a = linear[(row, column)] * min[column];
345 let b = linear[(row, column)] * max[column];
346 world_min[row] += a.min(b);
347 world_max[row] += a.max(b);
348 }
349 }
350 RenderBounds::Aabb {
351 min: world_min,
352 max: world_max,
353 }
354 }
355 }
356 }
357}
358
359#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
360pub struct Visibility {
361 pub visible: bool,
362}
363
364impl Default for Visibility {
365 fn default() -> Self {
366 Self { visible: true }
367 }
368}
369
370#[derive(
371 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
372)]
373pub enum QualityProfile {
374 Auto,
375 Eco,
376 #[default]
377 Balanced,
378 High,
379}
380
381#[derive(
383 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
384)]
385pub enum CullingMode {
386 #[default]
389 Auto,
390 Disabled,
392 Frustum,
394 FrustumAndOcclusion,
398}
399
400#[derive(
408 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
409)]
410pub enum Antialiasing {
411 #[default]
412 Auto,
413 Off,
414 Msaa2,
415 Msaa4,
416 Fxaa,
417 Taa,
418}
419
420#[derive(
423 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
424)]
425pub enum ShadowQuality {
426 #[default]
427 Auto,
428 Low,
430 Medium,
432 High,
434}
435
436#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
437pub struct RenderSettings {
438 pub quality: QualityProfile,
439 pub vsync: bool,
440 pub limit_fps: bool,
441 pub max_fps: u32,
442 pub render_scale: f32,
445 pub pixelated: bool,
448 pub upscale_sharpness: f32,
452 pub background_color: [f32; 4],
454 pub culling: CullingMode,
455 pub antialiasing: Antialiasing,
456 pub shadows: ShadowQuality,
457 pub hard_shadows: bool,
460 pub reflections: bool,
463 pub max_texture_size: u32,
467}
468
469impl Default for RenderSettings {
470 fn default() -> Self {
471 Self {
472 quality: QualityProfile::Auto,
473 vsync: false,
474 limit_fps: false,
475 max_fps: 120,
476 render_scale: 1.0,
477 pixelated: false,
478 upscale_sharpness: 0.0,
479 background_color: [0.025, 0.04, 0.07, 1.0],
480 culling: CullingMode::Auto,
481 antialiasing: Antialiasing::Auto,
482 shadows: ShadowQuality::Auto,
483 hard_shadows: false,
484 reflections: true,
485 max_texture_size: 0,
486 }
487 }
488}
489
490#[derive(
493 Component,
494 Clone,
495 Copy,
496 Debug,
497 Default,
498 PartialEq,
499 Eq,
500 Serialize,
501 Deserialize,
502)]
503#[serde(default)]
504pub struct AxisLock {
505 pub linear: [bool; 3],
507 pub angular: [bool; 3],
509}
510
511impl AxisLock {
512 pub const PLANE_XY: Self = Self {
514 linear: [false, false, true],
515 angular: [true, true, false],
516 };
517
518 #[must_use]
520 pub fn mask(&self) -> u32 {
521 self.linear
522 .iter()
523 .chain(&self.angular)
524 .enumerate()
525 .map(|(bit, &locked)| u32::from(locked) << bit)
526 .sum()
527 }
528}
529
530#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
531pub struct PhysicsSettings {
532 pub gravity: [f32; 3],
533 pub enabled: bool,
534 pub kill_y: Option<f32>,
537 pub substeps: u32,
541 pub gpu_locks: AxisLock,
545}
546
547#[derive(
551 bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
552)]
553pub struct PhysicsBackendStatus {
554 pub gameplay_available: bool,
555 pub gpu_dynamic_available: bool,
556}
557
558impl Default for PhysicsSettings {
559 fn default() -> Self {
560 Self {
561 gravity: [0.0, -9.81, 0.0],
562 enabled: true,
563 kill_y: None,
564 substeps: 1,
565 gpu_locks: AxisLock::default(),
566 }
567 }
568}
569
570#[derive(
572 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
573)]
574pub enum SimulationClass {
575 None,
577 Static,
579 #[default]
581 #[serde(alias = "Gameplay")]
582 Cpu,
583 #[serde(alias = "GpuDynamic")]
585 Gpu,
586}
587
588#[allow(non_upper_case_globals)]
589impl SimulationClass {
590 #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
591 pub const Gameplay: Self = Self::Cpu;
592 #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
593 pub const GpuDynamic: Self = Self::Gpu;
594}
595
596#[derive(
598 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
599)]
600pub enum PhysicsSolver {
601 #[default]
602 Full,
603 Simplified,
604 NoCollision,
605 Space,
606 Custom,
607}
608
609#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
615pub struct PhysicsBody {
616 pub simulation: SimulationClass,
617 pub solver: PhysicsSolver,
618 pub custom_shader: Option<String>,
619}
620
621impl Default for PhysicsBody {
622 fn default() -> Self {
623 Self {
624 simulation: SimulationClass::Cpu,
625 solver: PhysicsSolver::Full,
626 custom_shader: None,
627 }
628 }
629}
630
631impl PhysicsBody {
632 #[must_use]
633 pub fn participates_in_dynamic_simulation(&self) -> bool {
634 matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
635 }
636
637 #[must_use]
638 pub fn uses_gpu(&self) -> bool {
639 self.simulation == SimulationClass::Gpu
640 }
641}
642
643#[derive(
644 Component,
645 Clone,
646 Copy,
647 Debug,
648 Default,
649 Deserialize,
650 PartialEq,
651 Eq,
652 Serialize,
653)]
654pub enum RigidBodyKind {
655 Fixed,
656 #[default]
657 Dynamic,
658 Kinematic,
659}
660
661#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
662pub struct RigidBody {
663 pub kind: RigidBodyKind,
664 pub mass: f32,
665 pub linear_velocity: [f32; 3],
666 pub angular_velocity: [f32; 3],
667 pub gravity_scale: f32,
668}
669
670impl Default for RigidBody {
671 fn default() -> Self {
672 Self {
673 kind: RigidBodyKind::Dynamic,
674 mass: 1.0,
675 linear_velocity: [0.0; 3],
676 angular_velocity: [0.0; 3],
677 gravity_scale: 1.0,
678 }
679 }
680}
681
682#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
683pub enum ColliderShape {
684 Box {
685 half_extents: [f32; 3],
686 },
687 Sphere {
688 radius: f32,
689 },
690 Capsule {
691 half_height: f32,
692 radius: f32,
693 },
694 ConvexMesh,
697 TriangleMesh,
700 Heightfield,
703 Polygon,
706 Chain,
709}
710
711#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
712pub struct Collider {
713 pub shape: ColliderShape,
714 pub friction: f32,
715 pub restitution: f32,
716 pub sensor: bool,
717}
718
719impl Default for Collider {
720 fn default() -> Self {
721 Self {
722 shape: ColliderShape::Box {
723 half_extents: [0.5; 3],
724 },
725 friction: 0.5,
726 restitution: 0.0,
727 sensor: false,
728 }
729 }
730}
731
732#[derive(
733 Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
734)]
735pub struct CollisionLayers {
736 pub memberships: u32,
737 pub filters: u32,
738}
739
740impl Default for CollisionLayers {
741 fn default() -> Self {
742 Self {
743 memberships: u32::MAX,
744 filters: u32::MAX,
745 }
746 }
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752 use bevy_ecs::{component::Component, resource::Resource};
753
754 fn assert_component<T: Component>() {}
755 fn assert_resource<T: Resource>() {}
756
757 #[test]
758 fn canonical_types_implement_bevy_ecs_traits() {
759 assert_component::<SceneId>();
760 assert_component::<GlobalTransform>();
761 assert_component::<Parent>();
762 assert_component::<Children>();
763 assert_component::<Camera>();
764 assert_component::<Name>();
765 assert_component::<ObjectClasses>();
766 assert_component::<DirectionalLight>();
767 assert_component::<PointLight>();
768 assert_component::<SpotLight>();
769 assert_component::<AmbientLight>();
770 assert_component::<SkyLight>();
771 assert_component::<ToneMapping>();
772 assert_component::<RenderBounds>();
773 assert_component::<Visibility>();
774 assert_component::<PhysicsBody>();
775 assert_component::<RigidBodyKind>();
776 assert_component::<RigidBody>();
777 assert_component::<Collider>();
778 assert_component::<CollisionLayers>();
779
780 assert_resource::<RenderSettings>();
781 assert_resource::<PhysicsSettings>();
782 assert_resource::<PhysicsBackendStatus>();
783 }
784
785 #[test]
786 fn defaults_are_ready_for_a_basic_scene() {
787 let identity: [[f32; 4]; 4] =
788 nalgebra::Matrix4::<f32>::identity().into();
789 assert_eq!(GlobalTransform::default().matrix, identity);
790 assert!(Visibility::default().visible);
791 assert_eq!(RigidBody::default().mass, 1.0);
792 assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
793 assert_eq!(CollisionLayers::default().memberships, u32::MAX);
794 assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
795 }
796
797 #[test]
798 fn render_bounds_stay_conservative_under_transforms() {
799 use nalgebra::{Matrix4, Rotation3, Vector3};
800 let matrix: [[f32; 4]; 4] =
801 (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
802 * Rotation3::from_axis_angle(
803 &Vector3::z_axis(),
804 std::f32::consts::FRAC_PI_4,
805 )
806 .to_homogeneous()
807 * Matrix4::new_nonuniform_scaling(&Vector3::new(
808 2.0, 1.0, 3.0,
809 )))
810 .into();
811 let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
812 center: [1.0, 0.0, 0.0],
813 radius: 1.0,
814 })
815 .transformed(&matrix) else {
816 panic!("a sphere stays a sphere");
817 };
818 let half = std::f32::consts::FRAC_1_SQRT_2;
819 let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
820 for (value, expected) in center.iter().zip(expected) {
821 assert!((value - expected).abs() < 1e-5, "{center:?}");
822 }
823 assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
824
825 let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
826 min: [-1.0; 3],
827 max: [1.0; 3],
828 })
829 .transformed(&matrix) else {
830 panic!("a box stays a box");
831 };
832 let reach = 3.0 * half;
835 let expected_min = [10.0 - reach, -reach, -3.0];
836 let expected_max = [10.0 + reach, reach, 3.0];
837 for axis in 0..3 {
838 assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
839 assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
840 }
841 }
842
843 #[test]
844 fn object_classes_clean_and_edit_names() {
845 let mut classes =
846 ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
847 assert_eq!(classes.names, ["gravity", "enemy"]);
848 assert!(classes.contains("gravity"));
849 assert!(!classes.add("enemy"));
850 assert!(classes.remove("enemy"));
851 assert!(!classes.contains("enemy"));
852 }
853
854 #[test]
855 fn physics_body_helpers_follow_simulation_class() {
856 let mut body = PhysicsBody::default();
857 assert!(body.participates_in_dynamic_simulation());
858 assert!(!body.uses_gpu());
859
860 body.simulation = SimulationClass::Gpu;
861 assert!(body.participates_in_dynamic_simulation());
862 assert!(body.uses_gpu());
863
864 body.simulation = SimulationClass::Static;
865 assert!(!body.participates_in_dynamic_simulation());
866 assert!(!body.uses_gpu());
867 }
868}