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}
174
175#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
176pub struct SpotLight {
177 pub color: [f32; 3],
178 pub intensity: f32,
179 pub range: f32,
180 pub inner_angle: f32,
182 pub outer_angle: f32,
184 #[serde(default)]
187 pub shadows: bool,
188}
189
190impl Default for SpotLight {
191 fn default() -> Self {
192 Self {
193 color: [1.0; 3],
194 intensity: 1_000.0,
195 range: 10.0,
196 inner_angle: 20.0_f32.to_radians(),
197 outer_angle: 35.0_f32.to_radians(),
198 shadows: false,
199 }
200 }
201}
202
203impl Default for PointLight {
204 fn default() -> Self {
205 Self {
206 color: [1.0; 3],
207 intensity: 1_000.0,
208 range: 10.0,
209 }
210 }
211}
212
213#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
214pub struct AmbientLight {
215 pub color: [f32; 3],
216 pub intensity: f32,
217}
218
219impl Default for AmbientLight {
220 fn default() -> Self {
221 Self {
222 color: [1.0; 3],
223 intensity: 0.1,
224 }
225 }
226}
227
228#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
232pub struct SkyLight {
233 pub sky_color: [f32; 3],
234 pub ground_color: [f32; 3],
235 pub intensity: f32,
236}
237
238impl Default for SkyLight {
239 fn default() -> Self {
240 Self {
241 sky_color: [0.6, 0.75, 1.0],
242 ground_color: [0.3, 0.25, 0.2],
243 intensity: 0.3,
244 }
245 }
246}
247
248#[derive(
250 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
251)]
252pub enum ToneMapper {
253 #[default]
255 Linear,
256 Reinhard,
258 Aces,
260}
261
262#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
266pub struct ToneMapping {
267 pub mapper: ToneMapper,
268 pub exposure: f32,
270}
271
272impl Default for ToneMapping {
273 fn default() -> Self {
274 Self {
275 mapper: ToneMapper::Linear,
276 exposure: 1.0,
277 }
278 }
279}
280
281#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
285pub enum RenderBounds {
286 Sphere { center: [f32; 3], radius: f32 },
287 Aabb { min: [f32; 3], max: [f32; 3] },
288}
289
290impl Default for RenderBounds {
292 fn default() -> Self {
293 RenderBounds::Aabb {
294 min: [-0.5; 3],
295 max: [0.5; 3],
296 }
297 }
298}
299
300impl RenderBounds {
301 pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
307 let matrix = nalgebra::Matrix4::from(*matrix);
308 let linear = matrix.fixed_view::<3, 3>(0, 0);
309 let translation = matrix.fixed_view::<3, 1>(0, 3);
310 match *self {
311 RenderBounds::Sphere { center, radius } => {
312 let scale = (0..3)
313 .map(|axis| linear.column(axis).norm())
314 .fold(0.0_f32, f32::max);
315 let center =
316 linear * nalgebra::Vector3::from(center) + translation;
317 RenderBounds::Sphere {
318 center: center.into(),
319 radius: radius * scale,
320 }
321 }
322 RenderBounds::Aabb { min, max } => {
323 let mut world_min: [f32; 3] = translation.into();
326 let mut world_max = world_min;
327 for row in 0..3 {
328 for column in 0..3 {
329 let a = linear[(row, column)] * min[column];
330 let b = linear[(row, column)] * max[column];
331 world_min[row] += a.min(b);
332 world_max[row] += a.max(b);
333 }
334 }
335 RenderBounds::Aabb {
336 min: world_min,
337 max: world_max,
338 }
339 }
340 }
341 }
342}
343
344#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
345pub struct Visibility {
346 pub visible: bool,
347}
348
349impl Default for Visibility {
350 fn default() -> Self {
351 Self { visible: true }
352 }
353}
354
355#[derive(
356 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
357)]
358pub enum QualityProfile {
359 Auto,
360 Eco,
361 #[default]
362 Balanced,
363 High,
364}
365
366#[derive(
368 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
369)]
370pub enum CullingMode {
371 #[default]
374 Auto,
375 Disabled,
377 Frustum,
379 FrustumAndOcclusion,
383}
384
385#[derive(
389 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
390)]
391pub enum Antialiasing {
392 #[default]
393 Auto,
394 Off,
395 Msaa2,
396 Msaa4,
397}
398
399#[derive(
401 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
402)]
403pub enum ShadowQuality {
404 #[default]
405 Auto,
406 Low,
408 Medium,
410 High,
412}
413
414#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
415pub struct RenderSettings {
416 pub quality: QualityProfile,
417 pub vsync: bool,
418 pub limit_fps: bool,
419 pub max_fps: u32,
420 pub render_scale: f32,
423 pub pixelated: bool,
426 pub background_color: [f32; 4],
428 pub culling: CullingMode,
429 pub antialiasing: Antialiasing,
430 pub shadows: ShadowQuality,
431 pub hard_shadows: bool,
434 pub reflections: bool,
437}
438
439impl Default for RenderSettings {
440 fn default() -> Self {
441 Self {
442 quality: QualityProfile::Auto,
443 vsync: false,
444 limit_fps: false,
445 max_fps: 120,
446 render_scale: 1.0,
447 pixelated: false,
448 background_color: [0.025, 0.04, 0.07, 1.0],
449 culling: CullingMode::Auto,
450 antialiasing: Antialiasing::Auto,
451 shadows: ShadowQuality::Auto,
452 hard_shadows: false,
453 reflections: true,
454 }
455 }
456}
457
458#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
459pub struct PhysicsSettings {
460 pub gravity: [f32; 3],
461 pub enabled: bool,
462}
463
464#[derive(
468 bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
469)]
470pub struct PhysicsBackendStatus {
471 pub gameplay_available: bool,
472 pub gpu_dynamic_available: bool,
473}
474
475impl Default for PhysicsSettings {
476 fn default() -> Self {
477 Self {
478 gravity: [0.0, -9.81, 0.0],
479 enabled: true,
480 }
481 }
482}
483
484#[derive(
486 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
487)]
488pub enum SimulationClass {
489 None,
491 Static,
493 #[default]
495 #[serde(alias = "Gameplay")]
496 Cpu,
497 #[serde(alias = "GpuDynamic")]
499 Gpu,
500}
501
502#[allow(non_upper_case_globals)]
503impl SimulationClass {
504 #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
505 pub const Gameplay: Self = Self::Cpu;
506 #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
507 pub const GpuDynamic: Self = Self::Gpu;
508}
509
510#[derive(
512 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
513)]
514pub enum PhysicsSolver {
515 #[default]
516 Full,
517 Simplified,
518 NoCollision,
519 Space,
520 Custom,
521}
522
523#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
529pub struct PhysicsBody {
530 pub simulation: SimulationClass,
531 pub solver: PhysicsSolver,
532 pub custom_shader: Option<String>,
533}
534
535impl Default for PhysicsBody {
536 fn default() -> Self {
537 Self {
538 simulation: SimulationClass::Cpu,
539 solver: PhysicsSolver::Full,
540 custom_shader: None,
541 }
542 }
543}
544
545impl PhysicsBody {
546 #[must_use]
547 pub fn participates_in_dynamic_simulation(&self) -> bool {
548 matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
549 }
550
551 #[must_use]
552 pub fn uses_gpu(&self) -> bool {
553 self.simulation == SimulationClass::Gpu
554 }
555}
556
557#[derive(
558 Component,
559 Clone,
560 Copy,
561 Debug,
562 Default,
563 Deserialize,
564 PartialEq,
565 Eq,
566 Serialize,
567)]
568pub enum RigidBodyKind {
569 Fixed,
570 #[default]
571 Dynamic,
572 Kinematic,
573}
574
575#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
576pub struct RigidBody {
577 pub kind: RigidBodyKind,
578 pub mass: f32,
579 pub linear_velocity: [f32; 3],
580 pub angular_velocity: [f32; 3],
581 pub gravity_scale: f32,
582}
583
584impl Default for RigidBody {
585 fn default() -> Self {
586 Self {
587 kind: RigidBodyKind::Dynamic,
588 mass: 1.0,
589 linear_velocity: [0.0; 3],
590 angular_velocity: [0.0; 3],
591 gravity_scale: 1.0,
592 }
593 }
594}
595
596#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
597pub enum ColliderShape {
598 Box {
599 half_extents: [f32; 3],
600 },
601 Sphere {
602 radius: f32,
603 },
604 Capsule {
605 half_height: f32,
606 radius: f32,
607 },
608 ConvexMesh,
611 TriangleMesh,
614}
615
616#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
617pub struct Collider {
618 pub shape: ColliderShape,
619 pub friction: f32,
620 pub restitution: f32,
621 pub sensor: bool,
622}
623
624impl Default for Collider {
625 fn default() -> Self {
626 Self {
627 shape: ColliderShape::Box {
628 half_extents: [0.5; 3],
629 },
630 friction: 0.5,
631 restitution: 0.0,
632 sensor: false,
633 }
634 }
635}
636
637#[derive(
638 Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
639)]
640pub struct CollisionLayers {
641 pub memberships: u32,
642 pub filters: u32,
643}
644
645impl Default for CollisionLayers {
646 fn default() -> Self {
647 Self {
648 memberships: u32::MAX,
649 filters: u32::MAX,
650 }
651 }
652}
653
654#[cfg(test)]
655mod tests {
656 use super::*;
657 use bevy_ecs::{component::Component, resource::Resource};
658
659 fn assert_component<T: Component>() {}
660 fn assert_resource<T: Resource>() {}
661
662 #[test]
663 fn canonical_types_implement_bevy_ecs_traits() {
664 assert_component::<SceneId>();
665 assert_component::<GlobalTransform>();
666 assert_component::<Parent>();
667 assert_component::<Children>();
668 assert_component::<Camera>();
669 assert_component::<Name>();
670 assert_component::<ObjectClasses>();
671 assert_component::<DirectionalLight>();
672 assert_component::<PointLight>();
673 assert_component::<SpotLight>();
674 assert_component::<AmbientLight>();
675 assert_component::<SkyLight>();
676 assert_component::<ToneMapping>();
677 assert_component::<RenderBounds>();
678 assert_component::<Visibility>();
679 assert_component::<PhysicsBody>();
680 assert_component::<RigidBodyKind>();
681 assert_component::<RigidBody>();
682 assert_component::<Collider>();
683 assert_component::<CollisionLayers>();
684
685 assert_resource::<RenderSettings>();
686 assert_resource::<PhysicsSettings>();
687 assert_resource::<PhysicsBackendStatus>();
688 }
689
690 #[test]
691 fn defaults_are_ready_for_a_basic_scene() {
692 let identity: [[f32; 4]; 4] =
693 nalgebra::Matrix4::<f32>::identity().into();
694 assert_eq!(GlobalTransform::default().matrix, identity);
695 assert!(Visibility::default().visible);
696 assert_eq!(RigidBody::default().mass, 1.0);
697 assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
698 assert_eq!(CollisionLayers::default().memberships, u32::MAX);
699 assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
700 }
701
702 #[test]
703 fn render_bounds_stay_conservative_under_transforms() {
704 use nalgebra::{Matrix4, Rotation3, Vector3};
705 let matrix: [[f32; 4]; 4] =
706 (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
707 * Rotation3::from_axis_angle(
708 &Vector3::z_axis(),
709 std::f32::consts::FRAC_PI_4,
710 )
711 .to_homogeneous()
712 * Matrix4::new_nonuniform_scaling(&Vector3::new(
713 2.0, 1.0, 3.0,
714 )))
715 .into();
716 let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
717 center: [1.0, 0.0, 0.0],
718 radius: 1.0,
719 })
720 .transformed(&matrix) else {
721 panic!("a sphere stays a sphere");
722 };
723 let half = std::f32::consts::FRAC_1_SQRT_2;
724 let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
725 for (value, expected) in center.iter().zip(expected) {
726 assert!((value - expected).abs() < 1e-5, "{center:?}");
727 }
728 assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
729
730 let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
731 min: [-1.0; 3],
732 max: [1.0; 3],
733 })
734 .transformed(&matrix) else {
735 panic!("a box stays a box");
736 };
737 let reach = 3.0 * half;
740 let expected_min = [10.0 - reach, -reach, -3.0];
741 let expected_max = [10.0 + reach, reach, 3.0];
742 for axis in 0..3 {
743 assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
744 assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
745 }
746 }
747
748 #[test]
749 fn object_classes_clean_and_edit_names() {
750 let mut classes =
751 ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
752 assert_eq!(classes.names, ["gravity", "enemy"]);
753 assert!(classes.contains("gravity"));
754 assert!(!classes.add("enemy"));
755 assert!(classes.remove("enemy"));
756 assert!(!classes.contains("enemy"));
757 }
758
759 #[test]
760 fn physics_body_helpers_follow_simulation_class() {
761 let mut body = PhysicsBody::default();
762 assert!(body.participates_in_dynamic_simulation());
763 assert!(!body.uses_gpu());
764
765 body.simulation = SimulationClass::Gpu;
766 assert!(body.participates_in_dynamic_simulation());
767 assert!(body.uses_gpu());
768
769 body.simulation = SimulationClass::Static;
770 assert!(!body.participates_in_dynamic_simulation());
771 assert!(!body.uses_gpu());
772 }
773}