1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
#![warn(missing_docs)]
pub mod accel;
pub mod base;
pub mod camera;
pub mod collider;
pub mod debug;
pub mod decal;
pub mod dim2;
pub mod graph;
pub mod joint;
pub mod light;
pub mod mesh;
pub mod node;
pub mod particle_system;
pub mod pivot;
pub mod rigidbody;
pub mod sound;
pub mod sprite;
pub mod terrain;
pub mod transform;
pub mod variable;
pub mod visibility;
use crate::{
animation::{machine::container::AnimationMachineContainer, AnimationContainer},
core::{
algebra::Vector2,
color::Color,
futures::future::join_all,
inspect::{Inspect, PropertyInfo},
instant,
pool::{Handle, Pool, Ticket},
sstorage::ImmutableString,
visitor::{Visit, VisitError, VisitResult, Visitor},
},
engine::{resource_manager::ResourceManager, SerializationContext},
material::{shader::SamplerFallback, PropertyValue},
resource::texture::Texture,
scene::{
camera::Camera,
debug::SceneDrawingContext,
graph::{Graph, GraphPerformanceStatistics},
mesh::buffer::{
VertexAttributeDataType, VertexAttributeDescriptor, VertexAttributeUsage,
VertexWriteTrait,
},
mesh::Mesh,
node::Node,
sound::SoundEngine,
variable::{InheritError, InheritableVariable},
},
utils::{lightmap::Lightmap, log::Log, log::MessageKind, navmesh::Navmesh},
};
use fxhash::FxHashMap;
use std::{
any::{Any, TypeId},
fmt::{Display, Formatter},
ops::{Index, IndexMut},
path::Path,
sync::{Arc, Mutex},
time::Duration,
};
pub trait DirectlyInheritableEntity: Any {
fn inheritable_properties_ref(&self) -> Vec<&dyn InheritableVariable>;
fn inheritable_properties_mut(&mut self) -> Vec<&mut dyn InheritableVariable>;
fn as_any(&self) -> &dyn Any;
fn try_inherit_self_properties(
&mut self,
parent: &dyn DirectlyInheritableEntity,
) -> Result<(), InheritError> {
let any_parent = parent.as_any();
if TypeId::of::<Self>() == any_parent.type_id() {
for (dest, src) in self
.inheritable_properties_mut()
.iter_mut()
.zip(parent.inheritable_properties_ref())
{
dest.try_inherit(src)?;
}
Ok(())
} else {
Err(InheritError::TypesMismatch {
left_type: TypeId::of::<Self>(),
right_type: any_parent.type_id(),
})
}
}
fn reset_self_inheritable_properties(&mut self) {
for property in self.inheritable_properties_mut() {
property.reset_modified_flag();
}
}
}
#[macro_export]
macro_rules! impl_directly_inheritable_entity_trait {
($ty:ty; $($name:ident),*) => {
impl crate::scene::DirectlyInheritableEntity for $ty {
fn inheritable_properties_ref(&self)
-> Vec<&dyn crate::scene::variable::InheritableVariable>
{
vec![
$(&self.$name),*
]
}
fn inheritable_properties_mut(&mut self)
-> Vec<&mut dyn crate::scene::variable::InheritableVariable>
{
vec![
$(&mut self.$name),*
]
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
}
}
#[derive(Default, Clone, Debug, Visit)]
pub struct NavMeshContainer {
pool: Pool<Navmesh>,
}
impl NavMeshContainer {
pub fn add(&mut self, navmesh: Navmesh) -> Handle<Navmesh> {
self.pool.spawn(navmesh)
}
pub fn remove(&mut self, handle: Handle<Navmesh>) -> Navmesh {
self.pool.free(handle)
}
pub fn iter(&self) -> impl Iterator<Item = &Navmesh> {
self.pool.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Navmesh> {
self.pool.iter_mut()
}
pub fn handle_from_index(&self, i: u32) -> Handle<Navmesh> {
self.pool.handle_from_index(i)
}
pub fn clear(&mut self) {
self.pool.clear()
}
pub fn is_valid_handle(&self, handle: Handle<Navmesh>) -> bool {
self.pool.is_valid_handle(handle)
}
pub fn at(&self, i: u32) -> Option<&Navmesh> {
self.pool.at(i)
}
pub fn try_get(&self, handle: Handle<Navmesh>) -> Option<&Navmesh> {
self.pool.try_borrow(handle)
}
pub fn at_mut(&mut self, i: u32) -> Option<&mut Navmesh> {
self.pool.at_mut(i)
}
pub fn try_get_mut(&mut self, handle: Handle<Navmesh>) -> Option<&mut Navmesh> {
self.pool.try_borrow_mut(handle)
}
}
impl Index<Handle<Navmesh>> for NavMeshContainer {
type Output = Navmesh;
fn index(&self, index: Handle<Navmesh>) -> &Self::Output {
&self.pool[index]
}
}
impl IndexMut<Handle<Navmesh>> for NavMeshContainer {
fn index_mut(&mut self, index: Handle<Navmesh>) -> &mut Self::Output {
&mut self.pool[index]
}
}
#[derive(Debug, Inspect)]
pub struct Scene {
pub graph: Graph,
#[inspect(skip)]
pub animations: AnimationContainer,
#[inspect(skip)]
pub render_target: Option<Texture>,
#[inspect(skip)]
pub drawing_context: SceneDrawingContext,
#[inspect(skip)]
pub navmeshes: NavMeshContainer,
#[inspect(skip)]
lightmap: Option<Lightmap>,
#[inspect(skip)]
pub performance_statistics: PerformanceStatistics,
pub ambient_lighting_color: Color,
pub enabled: bool,
#[inspect(skip)]
pub animation_machines: AnimationMachineContainer,
}
impl Default for Scene {
fn default() -> Self {
Self {
graph: Default::default(),
animations: Default::default(),
render_target: None,
lightmap: None,
drawing_context: Default::default(),
navmeshes: Default::default(),
performance_statistics: Default::default(),
ambient_lighting_color: Color::opaque(100, 100, 100),
enabled: true,
animation_machines: Default::default(),
}
}
}
#[derive(Clone, Default, Debug)]
pub struct PerformanceStatistics {
pub graph: GraphPerformanceStatistics,
pub animations_update_time: Duration,
}
impl Display for PerformanceStatistics {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Animations: {:?}\n\
Graph: {:?}\n\
\tSync Time: {:?}\n\
\tSound: {:?}\n\
\tPhysics: {:?}\n\
\t\tSimulation: {:?}\n\
\t\tRay cast: {:?}\n\
\tPhysics 2D: {:?}\n\
\t\tSimulation: {:?}\n\
\t\tRay cast: {:?}\n\
\tHierarchy: {:?}",
self.animations_update_time,
self.graph.total(),
self.graph.sync_time,
self.graph.sound_update_time,
self.graph.physics.total(),
self.graph.physics.step_time,
self.graph.physics.total_ray_cast_time.get(),
self.graph.physics2d.total(),
self.graph.physics2d.step_time,
self.graph.physics2d.total_ray_cast_time.get(),
self.graph.hierarchical_properties_time,
)
}
}
pub struct SceneLoader {
scene: Scene,
}
impl SceneLoader {
pub async fn from_file<P: AsRef<Path>>(
path: P,
serialization_context: Arc<SerializationContext>,
) -> Result<Self, VisitError> {
let mut visitor = Visitor::load_binary(path).await?;
Self::load("Scene", serialization_context, &mut visitor)
}
pub fn load(
region_name: &str,
serialization_context: Arc<SerializationContext>,
visitor: &mut Visitor,
) -> Result<Self, VisitError> {
if !visitor.is_reading() {
return Err(VisitError::User(
"Visitor must be in read mode!".to_string(),
));
}
visitor.environment = Some(serialization_context);
let mut scene = Scene::default();
scene.visit(region_name, visitor)?;
Ok(Self { scene })
}
pub async fn finish(self, resource_manager: ResourceManager) -> Scene {
let mut scene = self.scene;
let mut resources = Vec::new();
for node in scene.graph.linear_iter_mut() {
if let Some(shallow_resource) = node.resource.clone() {
let resource = resource_manager
.clone()
.request_model(&shallow_resource.state().path());
node.resource = Some(resource.clone());
resources.push(resource);
}
}
let _ = join_all(resources).await;
for node in scene.graph.linear_iter_mut() {
node.restore_resources(resource_manager.clone());
}
if let Some(lightmap) = scene.lightmap.as_mut() {
for entries in lightmap.map.values_mut() {
for entry in entries.iter_mut() {
resource_manager
.state()
.containers_mut()
.textures
.try_restore_optional_resource(&mut entry.texture);
}
}
}
let mut skybox_textures = Vec::new();
for node in scene.graph.linear_iter() {
if let Some(camera) = node.cast::<Camera>() {
if let Some(skybox) = camera.skybox_ref() {
skybox_textures.extend(skybox.textures().iter().filter_map(|t| t.clone()));
}
}
}
join_all(skybox_textures).await;
let mut animation_resources = Vec::new();
for animation in scene.animations.iter_mut() {
animation.restore_resources(resource_manager.clone());
if let Some(resource) = animation.resource.as_ref() {
animation_resources.push(resource.clone());
}
}
join_all(animation_resources).await;
let mut animation_machines = Vec::new();
for machine in scene.animation_machines.iter_mut() {
machine.restore_resources(resource_manager.clone());
if let Some(resource) = machine.resource.as_ref() {
animation_machines.push(resource.clone());
}
}
join_all(animation_machines).await;
scene.resolve(resource_manager).await;
scene
}
}
impl Scene {
#[inline]
pub fn new() -> Self {
Self {
graph: Graph::new(),
animations: Default::default(),
render_target: None,
lightmap: None,
drawing_context: Default::default(),
navmeshes: Default::default(),
performance_statistics: Default::default(),
ambient_lighting_color: Color::opaque(100, 100, 100),
enabled: true,
animation_machines: Default::default(),
}
}
pub fn remove_node(&mut self, handle: Handle<Node>) {
for descendant in self.graph.traverse_handle_iter(handle) {
self.animations.retain(|animation| {
for track in animation.get_tracks() {
if track.get_node() == descendant {
return false;
}
}
true
});
}
self.graph.remove_node(handle)
}
pub async fn resolve(&mut self, resource_manager: ResourceManager) {
Log::writeln(MessageKind::Information, "Starting resolve...".to_owned());
self.graph.resolve();
self.animations.resolve(&self.graph);
self.animation_machines
.resolve(resource_manager, &mut self.graph, &mut self.animations)
.await;
self.graph.update_hierarchical_data();
if let Some(lightmap) = self.lightmap.as_mut() {
let mut unique_data_set = FxHashMap::default();
for &handle in lightmap.map.keys() {
if let Some(mesh) = self.graph[handle].cast_mut::<Mesh>() {
for surface in mesh.surfaces() {
let data = surface.data();
let key = &*data as *const _ as u64;
unique_data_set.entry(key).or_insert(data);
}
}
}
for (_, data) in unique_data_set.into_iter() {
let mut data = data.lock();
if let Some(patch) = lightmap.patches.get(&data.content_hash()) {
if !data
.vertex_buffer
.has_attribute(VertexAttributeUsage::TexCoord1)
{
data.vertex_buffer
.modify()
.add_attribute(
VertexAttributeDescriptor {
usage: VertexAttributeUsage::TexCoord1,
data_type: VertexAttributeDataType::F32,
size: 2,
divisor: 0,
shader_location: 6,
},
Vector2::<f32>::default(),
)
.unwrap();
}
data.geometry_buffer.set_triangles(patch.triangles.clone());
let mut vertex_buffer_mut = data.vertex_buffer.modify();
for &v in patch.additional_vertices.iter() {
vertex_buffer_mut.duplicate(v as usize);
}
assert_eq!(
vertex_buffer_mut.vertex_count() as usize,
patch.second_tex_coords.len()
);
for (mut view, &tex_coord) in vertex_buffer_mut
.iter_mut()
.zip(patch.second_tex_coords.iter())
{
view.write_2_f32(VertexAttributeUsage::TexCoord1, tex_coord)
.unwrap();
}
} else {
Log::writeln(
MessageKind::Warning,
"Failed to get surface data patch while resolving lightmap!\
This means that surface has changed and lightmap must be regenerated!"
.to_owned(),
);
}
}
for (&handle, entries) in lightmap.map.iter_mut() {
if let Some(mesh) = self.graph[handle].cast_mut::<Mesh>() {
for (entry, surface) in entries.iter_mut().zip(mesh.surfaces_mut()) {
if let Err(e) = surface.material().lock().set_property(
&ImmutableString::new("lightmapTexture"),
PropertyValue::Sampler {
value: entry.texture.clone(),
fallback: SamplerFallback::Black,
},
) {
Log::writeln(
MessageKind::Error,
format!(
"Failed to apply light map texture to material. Reason {:?}",
e
),
)
}
}
}
}
}
Log::writeln(MessageKind::Information, "Resolve succeeded!".to_owned());
}
pub fn set_lightmap(&mut self, lightmap: Lightmap) -> Result<Option<Lightmap>, &'static str> {
for (handle, lightmaps) in lightmap.map.iter() {
if let Some(mesh) = self.graph[*handle].cast_mut::<Mesh>() {
if mesh.surfaces().len() != lightmaps.len() {
return Err("failed to set lightmap, surface count mismatch");
}
for (surface, entry) in mesh.surfaces_mut().iter_mut().zip(lightmaps) {
let texture = entry.texture.clone().unwrap();
if let Err(e) = surface.material().lock().set_property(
&ImmutableString::new("lightmapTexture"),
PropertyValue::Sampler {
value: Some(texture),
fallback: SamplerFallback::Black,
},
) {
Log::writeln(
MessageKind::Error,
format!(
"Failed to apply light map texture to material. Reason {:?}",
e
),
)
}
}
}
}
Ok(std::mem::replace(&mut self.lightmap, Some(lightmap)))
}
pub fn update(&mut self, frame_size: Vector2<f32>, dt: f32) {
let last = instant::Instant::now();
self.animations.update_animations(dt);
self.performance_statistics.animations_update_time = instant::Instant::now() - last;
self.graph.update(frame_size, dt);
self.performance_statistics.graph = self.graph.performance_statistics.clone();
for machine in self.animation_machines.iter_mut() {
machine
.evaluate_pose(&self.animations, dt)
.apply(&mut self.graph);
}
}
pub fn clone<F>(&self, filter: &mut F) -> (Self, FxHashMap<Handle<Node>, Handle<Node>>)
where
F: FnMut(Handle<Node>, &Node) -> bool,
{
let (graph, old_new_map) = self.graph.clone(filter);
let mut animations = self.animations.clone();
for animation in animations.iter_mut() {
animation.retain_tracks(|track| old_new_map.contains_key(&track.get_node()));
for track in animation.get_tracks_mut() {
track.set_node(old_new_map[&track.get_node()]);
}
}
let mut animation_machines = self.animation_machines.clone();
for machine in animation_machines.iter_mut() {
machine.root = old_new_map.get(&machine.root).cloned().unwrap_or_default();
}
(
Self {
graph,
animations,
animation_machines,
render_target: Default::default(),
lightmap: self.lightmap.clone(),
drawing_context: self.drawing_context.clone(),
navmeshes: self.navmeshes.clone(),
performance_statistics: Default::default(),
ambient_lighting_color: self.ambient_lighting_color,
enabled: self.enabled,
},
old_new_map,
)
}
fn visit(&mut self, region_name: &str, visitor: &mut Visitor) -> VisitResult {
let mut region = visitor.enter_region(region_name)?;
self.graph.visit("Graph", &mut region)?;
self.animations.visit("Animations", &mut region)?;
self.lightmap.visit("Lightmap", &mut region)?;
self.navmeshes.visit("NavMeshes", &mut region)?;
self.ambient_lighting_color
.visit("AmbientLightingColor", &mut region)?;
self.enabled.visit("Enabled", &mut region)?;
let _ = self
.animation_machines
.visit("AnimationMachines", &mut region);
Ok(())
}
pub fn save(&mut self, region_name: &str, visitor: &mut Visitor) -> VisitResult {
if visitor.is_reading() {
return Err(VisitError::User(
"Visitor must be in write mode!".to_string(),
));
}
self.visit(region_name, visitor)
}
}
#[derive(Default)]
pub struct SceneContainer {
pool: Pool<Scene>,
sound_engine: Arc<Mutex<SoundEngine>>,
}
impl SceneContainer {
pub(in crate) fn new(sound_engine: Arc<Mutex<SoundEngine>>) -> Self {
Self {
pool: Pool::new(),
sound_engine,
}
}
pub fn is_valid_handle(&self, handle: Handle<Scene>) -> bool {
self.pool.is_valid_handle(handle)
}
pub fn pair_iter(&self) -> impl Iterator<Item = (Handle<Scene>, &Scene)> {
self.pool.pair_iter()
}
pub fn pair_iter_mut(&mut self) -> impl Iterator<Item = (Handle<Scene>, &mut Scene)> {
self.pool.pair_iter_mut()
}
pub fn try_get(&self, handle: Handle<Scene>) -> Option<&Scene> {
self.pool.try_borrow(handle)
}
pub fn try_get_mut(&mut self, handle: Handle<Scene>) -> Option<&mut Scene> {
self.pool.try_borrow_mut(handle)
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &Scene> {
self.pool.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Scene> {
self.pool.iter_mut()
}
#[inline]
pub fn add(&mut self, scene: Scene) -> Handle<Scene> {
self.sound_engine
.lock()
.unwrap()
.add_context(scene.graph.sound_context.native.clone());
self.pool.spawn(scene)
}
#[inline]
pub fn clear(&mut self) {
self.pool.clear()
}
#[inline]
pub fn remove(&mut self, handle: Handle<Scene>) {
self.sound_engine
.lock()
.unwrap()
.remove_context(self.pool[handle].graph.sound_context.native.clone());
self.pool.free(handle);
}
pub fn take_reserve(&mut self, handle: Handle<Scene>) -> (Ticket<Scene>, Scene) {
self.pool.take_reserve(handle)
}
pub fn put_back(&mut self, ticket: Ticket<Scene>, scene: Scene) -> Handle<Scene> {
self.pool.put_back(ticket, scene)
}
pub fn forget_ticket(&mut self, ticket: Ticket<Scene>) {
self.pool.forget_ticket(ticket)
}
}
impl Index<Handle<Scene>> for SceneContainer {
type Output = Scene;
#[inline]
fn index(&self, index: Handle<Scene>) -> &Self::Output {
&self.pool[index]
}
}
impl IndexMut<Handle<Scene>> for SceneContainer {
#[inline]
fn index_mut(&mut self, index: Handle<Scene>) -> &mut Self::Output {
&mut self.pool[index]
}
}