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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
use crate::camera::Camera2d;
use crate::color::Color;
use crate::prelude::InstanceData2d;
use crate::resource::vertex_index::VertexIndex;
use crate::resource::{
GpuMesh2d, Material2d, MaterialManager2d, MeshManager2d, RenderContext2d, Texture,
TextureManager,
};
use crate::scene::Object2d;
use glamx::{Pose2, Rot2, Vec2};
use std::cell::{Ref, RefCell, RefMut};
use std::f32;
use std::path::Path;
use std::rc::{Rc, Weak};
use std::sync::Arc;
// XXX: once something like `fn foo(self: Rc<RefCell<SceneNode2d>>)` is allowed, this extra struct
// will not be needed any more.
/// The data contained by a `SceneNode2d`.
pub struct SceneNodeData2d {
local_scale: Vec2,
local_transform: Pose2,
world_scale: Vec2,
world_transform: Pose2,
visible: bool,
up_to_date: bool,
children: Vec<SceneNode2d>,
object: Option<Object2d>,
parent: Option<Weak<RefCell<SceneNodeData2d>>>,
}
/// A node of the scene graph.
///
/// This may represent a group of other nodes, and/or contain an object that can be rendered.
#[derive(Clone)]
pub struct SceneNode2d {
data: Rc<RefCell<SceneNodeData2d>>,
}
impl SceneNodeData2d {
// XXX: Because `node.borrow_mut().parent = Some(self.data.downgrade())`
// causes a weird compiler error:
//
// ```
// error: mismatched types: expected `&std::cell::RefCell<scene::scene_node::SceneNodeData2d>`
// but found
// `std::option::Option<std::rc::Weak<std::cell::RefCell<scene::scene_node::SceneNodeData2d>>>`
// (expe cted &-ptr but found enum std::option::Option)
// ```
fn set_parent(&mut self, parent: Weak<RefCell<SceneNodeData2d>>) {
self.parent = Some(parent);
}
// TODO: this exists because of a similar bug as `set_parent`.
fn remove_from_parent(&mut self, to_remove: &SceneNode2d) {
let _ = self.parent.as_ref().map(|p| {
if let Some(bp) = p.upgrade() {
bp.borrow_mut().remove(to_remove);
}
});
}
fn remove(&mut self, o: &SceneNode2d) {
if let Some(i) = self
.children
.iter()
.rposition(|e| std::ptr::eq(&*o.data, &*e.data))
{
let _ = self.children.swap_remove(i);
}
}
/// Whether this node contains an `Object2d`.
#[inline]
pub fn has_object(&self) -> bool {
self.object.is_some()
}
/// Whether this node has no parent.
#[inline]
pub fn is_root(&self) -> bool {
self.parent.is_none()
}
/// Prepare the scene graph rooted by this node for rendering.
pub fn prepare(&mut self, camera: &mut dyn Camera2d, context: &RenderContext2d) {
if self.visible {
self.do_prepare(Pose2::IDENTITY, Vec2::ONE, camera, context)
}
}
fn do_prepare(
&mut self,
transform: Pose2,
scale: Vec2,
camera: &mut dyn Camera2d,
context: &RenderContext2d,
) {
if !self.up_to_date {
self.up_to_date = true;
self.world_transform = transform * self.local_transform;
self.world_scale = scale * self.local_scale;
}
if let Some(ref mut o) = self.object {
o.prepare(self.world_transform, self.world_scale, camera, context)
}
for c in self.children.iter_mut() {
let mut bc = c.data_mut();
if bc.visible {
bc.do_prepare(self.world_transform, self.world_scale, camera, context)
}
}
}
/// Render the scene graph rooted by this node.
pub fn render(
&mut self,
camera: &mut dyn Camera2d,
render_pass: &mut wgpu::RenderPass<'_>,
context: &RenderContext2d,
) {
if self.visible {
self.do_render(Pose2::IDENTITY, Vec2::ONE, camera, render_pass, context)
}
}
fn do_render(
&mut self,
transform: Pose2,
scale: Vec2,
camera: &mut dyn Camera2d,
render_pass: &mut wgpu::RenderPass<'_>,
context: &RenderContext2d,
) {
if !self.up_to_date {
self.up_to_date = true;
self.world_transform = transform * self.local_transform;
self.world_scale = scale * self.local_scale;
}
if let Some(ref mut o) = self.object {
o.render(
self.world_transform,
self.world_scale,
camera,
render_pass,
context,
)
}
for c in self.children.iter_mut() {
let mut bc = c.data_mut();
if bc.visible {
bc.do_render(
self.world_transform,
self.world_scale,
camera,
render_pass,
context,
)
}
}
}
/// A reference to the object possibly contained by this node.
#[inline]
pub fn object(&self) -> Option<&Object2d> {
self.object.as_ref()
}
/// A mutable reference to the object possibly contained by this node.
#[inline]
pub fn object_mut(&mut self) -> Option<&mut Object2d> {
self.object.as_mut()
}
/// A reference to the object possibly contained by this node.
///
/// # Failure
/// Fails of this node does not contains an object.
#[inline]
pub fn get_object(&self) -> &Object2d {
self.object()
.expect("This scene node does not contain an Object2d.")
}
/// A mutable reference to the object possibly contained by this node.
///
/// # Failure
/// Fails of this node does not contains an object.
#[inline]
pub fn get_object_mut(&mut self) -> &mut Object2d {
self.object_mut()
.expect("This scene node does not contain an Object2d.")
}
fn invalidate(&mut self) {
self.up_to_date = false;
for c in self.children.iter_mut() {
let mut dm = c.data_mut();
if dm.up_to_date {
dm.invalidate()
}
}
}
// TODO: make this public?
fn update(&mut self) {
if !self.up_to_date {
if let Some(ref mut p) = self.parent {
if let Some(dp) = p.upgrade() {
let mut dp = dp.borrow_mut();
dp.update();
self.world_transform = self.local_transform * dp.world_transform;
self.world_scale = self.local_scale * dp.local_scale;
self.up_to_date = true;
return;
}
}
// no parent
self.world_transform = self.local_transform;
self.world_scale = self.local_scale;
self.up_to_date = true;
}
}
}
impl Default for SceneNode2d {
fn default() -> Self {
Self::empty()
}
}
impl SceneNode2d {
/// Creates a new scene node that is not rooted.
pub fn new(local_scale: Vec2, local_transform: Pose2, object: Option<Object2d>) -> SceneNode2d {
let data = SceneNodeData2d {
local_scale,
local_transform,
world_transform: local_transform,
world_scale: local_scale,
visible: true,
up_to_date: false,
children: Vec::new(),
object,
parent: None,
};
SceneNode2d {
data: Rc::new(RefCell::new(data)),
}
}
/// Creates a new empty, not rooted, node with identity transformations.
pub fn empty() -> SceneNode2d {
SceneNode2d::new(Vec2::ONE, Pose2::IDENTITY, None)
}
// ==================
// Primitive constructors
// ==================
/// Creates a new scene node with a rectangle mesh.
///
/// The rectangle is initially axis-aligned and centered at (0, 0).
///
/// # Arguments
/// * `wx` - the rectangle extent along the x axis
/// * `wy` - the rectangle extent along the y axis
pub fn rectangle(wx: f32, wy: f32) -> SceneNode2d {
Self::geom_with_name("rectangle", Vec2::new(wx, wy))
.expect("Unable to load the default rectangle geometry.")
}
/// Creates a new scene node with a circle mesh.
///
/// The circle is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the circle radius
pub fn circle(r: f32) -> SceneNode2d {
Self::geom_with_name("circle", Vec2::new(r * 2.0, r * 2.0))
.expect("Unable to load the default circle geometry.")
}
/// Creates a new scene node with a circle mesh with custom subdivisions.
///
/// The circle is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the circle radius
/// * `nsubdiv` - number of subdivisions around the circumference
pub fn circle_with_subdiv(r: f32, nsubdiv: u32) -> SceneNode2d {
let mut circle_vtx = vec![Vec2::ZERO];
let mut circle_ids = Vec::new();
for i in 0..nsubdiv {
let ang = (i as f32) / (nsubdiv as f32) * f32::consts::TAU;
circle_vtx.push(Vec2::new(ang.cos(), ang.sin()) * r);
circle_ids.push([
0,
circle_vtx.len() as VertexIndex - 2,
circle_vtx.len() as VertexIndex - 1,
]);
}
circle_ids.push([0, circle_vtx.len() as VertexIndex - 1, 1]);
let circle = GpuMesh2d::new(circle_vtx, circle_ids, None, false);
Self::mesh(Rc::new(RefCell::new(circle)), Vec2::ONE)
}
/// Creates a new scene node with a 2D capsule mesh.
///
/// The capsule is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the capsule caps radius
/// * `h` - the capsule height
pub fn capsule(r: f32, h: f32) -> SceneNode2d {
let name = format!("capsule_{}_{}", r, h);
let mesh = MeshManager2d::get_global_manager(|mm| {
if let Some(geom) = mm.get(&name) {
geom
} else {
// Create the capsule geometry.
let mut capsule_vtx = vec![Vec2::ZERO];
let mut capsule_ids = Vec::new();
let nsamples = 50;
for i in 0..=nsamples {
let ang = (i as f32) / (nsamples as f32) * f32::consts::PI;
capsule_vtx.push(Vec2::new(ang.cos() * r, ang.sin() * r + h / 2.0));
capsule_ids.push([
0,
capsule_vtx.len() as VertexIndex - 2,
capsule_vtx.len() as VertexIndex - 1,
]);
}
for i in nsamples..=nsamples * 2 {
let ang = (i as f32) / (nsamples as f32) * f32::consts::PI;
capsule_vtx.push(Vec2::new(ang.cos() * r, ang.sin() * r - h / 2.0));
capsule_ids.push([
0,
capsule_vtx.len() as VertexIndex - 2,
capsule_vtx.len() as VertexIndex - 1,
]);
}
capsule_ids.push([0, capsule_vtx.len() as VertexIndex - 1, 1]);
let capsule = GpuMesh2d::new(capsule_vtx, capsule_ids, None, false);
let mesh = Rc::new(RefCell::new(capsule));
mm.add(mesh.clone(), &name);
mesh
}
});
Self::mesh(mesh, Vec2::ONE)
}
/// Creates a new scene node with a 2D capsule mesh with custom subdivisions.
///
/// The capsule is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the capsule caps radius
/// * `h` - the capsule height
/// * `nsubdiv` - number of subdivisions for each semicircular cap
pub fn capsule_with_subdiv(r: f32, h: f32, nsubdiv: u32) -> SceneNode2d {
let mut capsule_vtx = vec![Vec2::ZERO];
let mut capsule_ids = Vec::new();
for i in 0..=nsubdiv {
let ang = (i as f32) / (nsubdiv as f32) * f32::consts::PI;
capsule_vtx.push(Vec2::new(ang.cos() * r, ang.sin() * r + h / 2.0));
capsule_ids.push([
0,
capsule_vtx.len() as VertexIndex - 2,
capsule_vtx.len() as VertexIndex - 1,
]);
}
for i in nsubdiv..=nsubdiv * 2 {
let ang = (i as f32) / (nsubdiv as f32) * f32::consts::PI;
capsule_vtx.push(Vec2::new(ang.cos() * r, ang.sin() * r - h / 2.0));
capsule_ids.push([
0,
capsule_vtx.len() as VertexIndex - 2,
capsule_vtx.len() as VertexIndex - 1,
]);
}
capsule_ids.push([0, capsule_vtx.len() as VertexIndex - 1, 1]);
let capsule = GpuMesh2d::new(capsule_vtx, capsule_ids, None, false);
Self::mesh(Rc::new(RefCell::new(capsule)), Vec2::ONE)
}
/// Creates a new scene node with a polyline.
pub fn polyline(
vertices: Vec<Vec2>,
indices: Option<Vec<[u32; 2]>>,
line_width: f32,
) -> SceneNode2d {
let indices = if let Some(indices) = indices {
indices
.into_iter()
.map(|idx| [idx[0], idx[0], idx[1]])
.collect()
} else {
(0..vertices.len() - 1)
.map(|i| [i as u32, i as u32, i as u32 + 1])
.collect()
};
let mesh = GpuMesh2d::new(vertices, indices, None, false);
let mut node = Self::mesh(Rc::new(RefCell::new(mesh)), Vec2::ONE);
node.set_surface_rendering_activation(false);
node.set_lines_width(line_width, true);
node
}
/// Creates a new scene node using the geometry registered as `geometry_name`.
pub fn geom_with_name(geometry_name: &str, scale: Vec2) -> Option<SceneNode2d> {
MeshManager2d::get_global_manager(|mm| mm.get(geometry_name)).map(|g| Self::mesh(g, scale))
}
/// Creates a new scene node using a 2D mesh.
pub fn mesh(mesh: Rc<RefCell<GpuMesh2d>>, scale: Vec2) -> SceneNode2d {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let mat = MaterialManager2d::get_global_manager(|mm| mm.get_default());
let object = Object2d::new(mesh, 1.0, 1.0, 1.0, tex, mat);
SceneNode2d::new(scale, Pose2::IDENTITY, Some(object))
}
/// Creates a new scene node using a convex polyline.
pub fn convex_polygon(polygon: Vec<Vec2>, scale: Vec2) -> SceneNode2d {
let mut indices = Vec::new();
for i in 1..polygon.len() - 1 {
indices.push([0, i as VertexIndex, i as VertexIndex + 1]);
}
let mesh = GpuMesh2d::new(polygon, indices, None, false);
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let mat = MaterialManager2d::get_global_manager(|mm| mm.get_default());
let object = Object2d::new(Rc::new(RefCell::new(mesh)), 1.0, 1.0, 1.0, tex, mat);
SceneNode2d::new(scale, Pose2::IDENTITY, Some(object))
}
/// Removes this node from its parent.
pub fn detach(&mut self) {
let self_self = self.clone();
self.data_mut().remove_from_parent(&self_self);
self.data_mut().parent = None
}
/// The data of this scene node.
pub fn data(&self) -> Ref<'_, SceneNodeData2d> {
self.data.borrow()
}
/// The data of this scene node.
pub fn data_mut(&mut self) -> RefMut<'_, SceneNodeData2d> {
self.data.borrow_mut()
}
/*
*
* Methods to add objects.
*
*/
/// Adds a node without object to this node children.
pub fn add_group(&mut self) -> SceneNode2d {
let node = SceneNode2d::empty();
self.add_child(node.clone());
node
}
/// Adds a node as a child of `parent`.
///
/// # Failures:
/// Fails if `node` already has a parent.
pub fn add_child(&mut self, node: SceneNode2d) {
assert!(
node.data().is_root(),
"The added node must not have a parent yet."
);
let mut node = node;
let self_weak_ptr = Rc::downgrade(&self.data);
node.data_mut().set_parent(self_weak_ptr);
self.data_mut().children.push(node)
}
/// Adds a node containing an object to this node children.
pub fn add_object(
&mut self,
local_scale: Vec2,
local_transform: Pose2,
object: Object2d,
) -> SceneNode2d {
let node = SceneNode2d::new(local_scale, local_transform, Some(object));
self.add_child(node.clone());
node
}
/// Adds a rectangle as a children of this node. The rectangle is initially axis-aligned and centered
/// at (0, 0).
///
/// # Arguments
/// * `wx` - the rectangle extent along the x axis
/// * `wy` - the rectangle extent along the y axis
pub fn add_rectangle(&mut self, wx: f32, wy: f32) -> SceneNode2d {
let node = Self::rectangle(wx, wy);
self.add_child(node.clone());
node
}
/// Adds a circle as a children of this node. The circle is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the circle radius
pub fn add_circle(&mut self, r: f32) -> SceneNode2d {
let node = Self::circle(r);
self.add_child(node.clone());
node
}
/// Adds a circle with custom subdivisions as a child of this node.
///
/// The circle is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the circle radius
/// * `nsubdiv` - number of subdivisions around the circumference
pub fn add_circle_with_subdiv(&mut self, r: f32, nsubdiv: u32) -> SceneNode2d {
let node = Self::circle_with_subdiv(r, nsubdiv);
self.add_child(node.clone());
node
}
pub fn add_polyline(
&mut self,
vertices: Vec<Vec2>,
indices: Option<Vec<[u32; 2]>>,
line_width: f32,
) -> SceneNode2d {
let node = Self::polyline(vertices, indices, line_width);
self.add_child(node.clone());
node
}
/// Adds a 2D capsule as a children of this node. The capsule is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the capsule caps radius
/// * `h` - the capsule height
pub fn add_capsule(&mut self, r: f32, h: f32) -> SceneNode2d {
let node = Self::capsule(r, h);
self.add_child(node.clone());
node
}
/// Adds a 2D capsule with custom subdivisions as a child of this node.
///
/// The capsule is initially centered at (0, 0).
///
/// # Arguments
/// * `r` - the capsule caps radius
/// * `h` - the capsule height
/// * `nsubdiv` - number of subdivisions for each semicircular cap
pub fn add_capsule_with_subdiv(&mut self, r: f32, h: f32, nsubdiv: u32) -> SceneNode2d {
let node = Self::capsule_with_subdiv(r, h, nsubdiv);
self.add_child(node.clone());
node
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec2) -> Option<SceneNode2d> {
Self::geom_with_name(geometry_name, scale).inspect(|node| {
self.add_child(node.clone());
})
}
/// Creates and adds a new object to this node children using a 2D mesh.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<GpuMesh2d>>, scale: Vec2) -> SceneNode2d {
let node = Self::mesh(mesh, scale);
self.add_child(node.clone());
node
}
/// Creates and adds a new object to this node children using a convex polyline
pub fn add_convex_polygon(&mut self, polygon: Vec<Vec2>, scale: Vec2) -> SceneNode2d {
let node = Self::convex_polygon(polygon, scale);
self.add_child(node.clone());
node
}
/// Applies a closure to each object contained by this node and its descendants.
#[inline]
pub fn apply_to_scene_nodes_mut_recursive<F: FnMut(&mut SceneNode2d)>(&mut self, f: &mut F) {
f(self);
for c in self.data_mut().children.iter_mut() {
c.apply_to_scene_nodes_mut_recursive(f)
}
}
/// Applies a closure to each object contained by this node and its descendants.
#[inline]
pub fn apply_to_scene_nodes_recursive<F: FnMut(&SceneNode2d)>(&self, f: &mut F) {
f(self);
for c in self.data().children.iter() {
c.apply_to_scene_nodes_recursive(f)
}
}
//
//
// fwd
//
//
/// Prepare the scene graph rooted by this node for rendering.
pub fn prepare(&mut self, camera: &mut dyn Camera2d, context: &RenderContext2d) {
self.data_mut().prepare(camera, context)
}
/// Render the scene graph rooted by this node.
pub fn render(
&mut self,
camera: &mut dyn Camera2d,
render_pass: &mut wgpu::RenderPass<'_>,
context: &RenderContext2d,
) {
self.data_mut().render(camera, render_pass, context)
}
/// Sets the material of this node's object only.
///
/// # See also
/// * [`Self::set_material_recursive`] - to also modify all descendants.
#[inline]
pub fn set_material(&mut self, material: Rc<RefCell<Box<dyn Material2d + 'static>>>) -> Self {
self.apply_to_object_mut(&mut |o| o.set_material(material.clone()));
self.clone()
}
/// Sets the material of this node's object and all its descendants.
///
/// # See also
/// * [`Self::set_material`] - to only modify this node.
#[inline]
pub fn set_material_recursive(
&mut self,
material: Rc<RefCell<Box<dyn Material2d + 'static>>>,
) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_material(material.clone()));
self.clone()
}
/// Sets the material of this node's object only.
///
/// The material must already have been registered as `name`.
///
/// # See also
/// * [`Self::set_material_with_name_recursive`] - to also modify all descendants.
#[inline]
pub fn set_material_with_name(&mut self, name: &str) -> Self {
let material = MaterialManager2d::get_global_manager(|tm| {
tm.get(name).unwrap_or_else(|| {
panic!("Invalid attempt to use the unregistered material: {}", name)
})
});
self.set_material(material)
}
/// Sets the material of this node's object and all its descendants.
///
/// The material must already have been registered as `name`.
///
/// # See also
/// * [`Self::set_material_with_name`] - to only modify this node.
#[inline]
pub fn set_material_with_name_recursive(&mut self, name: &str) -> Self {
let material = MaterialManager2d::get_global_manager(|tm| {
tm.get(name).unwrap_or_else(|| {
panic!("Invalid attempt to use the unregistered material: {}", name)
})
});
self.set_material_recursive(material)
}
/// Sets the width of the lines drawn for this node's object only.
///
/// If `use_perspective` is true, width is in world units and scales with camera zoom.
/// If `use_perspective` is false, width is in screen pixels and stays constant.
///
/// # See also
/// * [`Self::set_lines_width_recursive`] - to also modify all descendants.
#[inline]
pub fn set_lines_width(&mut self, width: f32, use_perspective: bool) -> Self {
self.apply_to_object_mut(&mut |o| o.set_lines_width(width, use_perspective));
self.clone()
}
/// Sets the width of the lines drawn for this node's object and all its descendants.
///
/// If `use_perspective` is true, width is in world units and scales with camera zoom.
/// If `use_perspective` is false, width is in screen pixels and stays constant.
///
/// # See also
/// * [`Self::set_lines_width`] - to only modify this node.
#[inline]
pub fn set_lines_width_recursive(&mut self, width: f32, use_perspective: bool) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_lines_width(width, use_perspective));
self.clone()
}
/// Sets the color of the lines drawn for this node's object only.
///
/// # See also
/// * [`Self::set_lines_color_recursive`] - to also modify all descendants.
#[inline]
pub fn set_lines_color(&mut self, color: Option<Color>) -> Self {
self.apply_to_object_mut(&mut |o| o.set_lines_color(color));
self.clone()
}
/// Sets the color of the lines drawn for this node's object and all its descendants.
///
/// # See also
/// * [`Self::set_lines_color`] - to only modify this node.
#[inline]
pub fn set_lines_color_recursive(&mut self, color: Option<Color>) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_lines_color(color));
self.clone()
}
/// Sets the size of the points drawn for this node's object only.
///
/// If `use_perspective` is true, size is in world units and scales with camera zoom.
/// If `use_perspective` is false, size is in screen pixels and stays constant.
///
/// # See also
/// * [`Self::set_points_size_recursive`] - to also modify all descendants.
#[inline]
pub fn set_points_size(&mut self, size: f32, use_perspective: bool) -> Self {
self.apply_to_object_mut(&mut |o| o.set_points_size(size, use_perspective));
self.clone()
}
/// Sets the size of the points drawn for this node's object and all its descendants.
///
/// If `use_perspective` is true, size is in world units and scales with camera zoom.
/// If `use_perspective` is false, size is in screen pixels and stays constant.
///
/// # See also
/// * [`Self::set_points_size`] - to only modify this node.
#[inline]
pub fn set_points_size_recursive(&mut self, size: f32, use_perspective: bool) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_points_size(size, use_perspective));
self.clone()
}
/// Sets the color of the points drawn for this node's object only.
///
/// # See also
/// * [`Self::set_points_color_recursive`] - to also modify all descendants.
#[inline]
pub fn set_points_color(&mut self, color: Option<Color>) -> Self {
self.apply_to_object_mut(&mut |o| o.set_points_color(color));
self.clone()
}
/// Sets the color of the points drawn for this node's object and all its descendants.
///
/// # See also
/// * [`Self::set_points_color`] - to only modify this node.
#[inline]
pub fn set_points_color_recursive(&mut self, color: Option<Color>) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_points_color(color));
self.clone()
}
/// Activates or deactivates the rendering of the surfaces of this node's object only.
///
/// # See also
/// * [`Self::set_surface_rendering_activation_recursive`] - to also modify all descendants.
#[inline]
pub fn set_surface_rendering_activation(&mut self, active: bool) -> Self {
self.apply_to_object_mut(&mut |o| o.set_surface_rendering_activation(active));
self.clone()
}
/// Activates or deactivates the rendering of the surfaces of this node's object and all its
/// descendants.
///
/// # See also
/// * [`Self::set_surface_rendering_activation`] - to only modify this node.
#[inline]
pub fn set_surface_rendering_activation_recursive(&mut self, active: bool) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_surface_rendering_activation(active));
self.clone()
}
/// Activates or deactivates backface culling for this node's object only.
///
/// # See also
/// * [`Self::enable_backface_culling_recursive`] - to also modify all descendants.
#[inline]
pub fn enable_backface_culling(&mut self, active: bool) -> Self {
self.apply_to_object_mut(&mut |o| o.enable_backface_culling(active));
self.clone()
}
/// Activates or deactivates backface culling for this node's object and all its descendants.
///
/// # See also
/// * [`Self::enable_backface_culling`] - to only modify this node.
#[inline]
pub fn enable_backface_culling_recursive(&mut self, active: bool) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.enable_backface_culling(active));
self.clone()
}
/// Mutably accesses the vertices of this node's object only.
///
/// # See also
/// * [`Self::modify_vertices_recursive`] - to also modify all descendants.
#[inline(always)]
pub fn modify_vertices<F: FnMut(&mut Vec<Vec2>)>(&mut self, f: &mut F) {
self.apply_to_object_mut(&mut |o| o.modify_vertices(f))
}
/// Mutably accesses the vertices of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::modify_vertices`] - to only modify this node.
#[inline(always)]
pub fn modify_vertices_recursive<F: FnMut(&mut Vec<Vec2>)>(&mut self, f: &mut F) {
self.apply_to_objects_mut_recursive(&mut |o| o.modify_vertices(f))
}
/// Accesses the vertices of this node's object only.
///
/// # See also
/// * [`Self::read_vertices_recursive`] - to also access all descendants.
#[inline(always)]
pub fn read_vertices<F: FnMut(&[Vec2])>(&self, f: &mut F) {
self.apply_to_object(&mut |o| o.read_vertices(f))
}
/// Accesses the vertices of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::read_vertices`] - to only access this node.
#[inline(always)]
pub fn read_vertices_recursive<F: FnMut(&[Vec2])>(&self, f: &mut F) {
self.apply_to_objects_recursive(&mut |o| o.read_vertices(f))
}
/// Mutably accesses the faces of this node's object only.
///
/// # See also
/// * [`Self::modify_faces_recursive`] - to also modify all descendants.
#[inline(always)]
pub fn modify_faces<F: FnMut(&mut Vec<[VertexIndex; 3]>)>(&mut self, f: &mut F) {
self.apply_to_object_mut(&mut |o| o.modify_faces(f))
}
/// Mutably accesses the faces of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::modify_faces`] - to only modify this node.
#[inline(always)]
pub fn modify_faces_recursive<F: FnMut(&mut Vec<[VertexIndex; 3]>)>(&mut self, f: &mut F) {
self.apply_to_objects_mut_recursive(&mut |o| o.modify_faces(f))
}
/// Accesses the faces of this node's object only.
///
/// # See also
/// * [`Self::read_faces_recursive`] - to also access all descendants.
#[inline(always)]
pub fn read_faces<F: FnMut(&[[VertexIndex; 3]])>(&self, f: &mut F) {
self.apply_to_object(&mut |o| o.read_faces(f))
}
/// Accesses the faces of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::read_faces`] - to only access this node.
#[inline(always)]
pub fn read_faces_recursive<F: FnMut(&[[VertexIndex; 3]])>(&self, f: &mut F) {
self.apply_to_objects_recursive(&mut |o| o.read_faces(f))
}
/// Mutably accesses the texture coordinates of this node's object only.
///
/// # See also
/// * [`Self::modify_uvs_recursive`] - to also modify all descendants.
#[inline(always)]
pub fn modify_uvs<F: FnMut(&mut Vec<Vec2>)>(&mut self, f: &mut F) {
self.apply_to_object_mut(&mut |o| o.modify_uvs(f))
}
/// Mutably accesses the texture coordinates of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::modify_uvs`] - to only modify this node.
#[inline(always)]
pub fn modify_uvs_recursive<F: FnMut(&mut Vec<Vec2>)>(&mut self, f: &mut F) {
self.apply_to_objects_mut_recursive(&mut |o| o.modify_uvs(f))
}
/// Accesses the texture coordinates of this node's object only.
///
/// # See also
/// * [`Self::read_uvs_recursive`] - to also access all descendants.
#[inline(always)]
pub fn read_uvs<F: FnMut(&[Vec2])>(&self, f: &mut F) {
self.apply_to_object(&mut |o| o.read_uvs(f))
}
/// Accesses the texture coordinates of this node's object and all its descendants.
///
/// The provided closure is called once per object.
///
/// # See also
/// * [`Self::read_uvs`] - to only access this node.
#[inline(always)]
pub fn read_uvs_recursive<F: FnMut(&[Vec2])>(&self, f: &mut F) {
self.apply_to_objects_recursive(&mut |o| o.read_uvs(f))
}
/// Get the visibility status of node.
#[inline]
pub fn is_visible(&self) -> bool {
let data = self.data();
data.visible
}
/// Sets the visibility of this node.
///
/// The node and its children are not rendered if it is not visible.
#[inline]
pub fn set_visible(&mut self, visible: bool) -> Self {
self.data_mut().visible = visible;
self.clone()
}
/// Sets the color of this node's object only.
///
/// Colors components must be on the range `[0.0, 1.0]`.
///
/// # See also
/// * [`Self::set_color_recursive`] - to also modify all descendants.
#[inline]
pub fn set_color(&mut self, color: Color) -> Self {
self.apply_to_object_mut(&mut |o| o.set_color(color));
self.clone()
}
/// Sets the color of this node's object and all its descendants.
///
/// Colors components must be on the range `[0.0, 1.0]`.
///
/// # See also
/// * [`Self::set_color`] - to only modify this node.
#[inline]
pub fn set_color_recursive(&mut self, color: Color) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_color(color));
self.clone()
}
/// Sets the texture of this node's object only.
///
/// The texture is loaded from a file and registered by the global `TextureManager`.
///
/// # Arguments
/// * `path` - relative path of the texture on the disk
/// * `name` - &str identifier to store this texture under
///
/// # See also
/// * [`Self::set_texture_from_file_recursive`] - to also modify all descendants.
#[inline]
pub fn set_texture_from_file(&mut self, path: &Path, name: &str) -> Self {
let texture = TextureManager::get_global_manager(|tm| tm.add(path, name));
self.set_texture(texture)
}
/// Sets the texture of this node's object and all its descendants.
///
/// The texture is loaded from a file and registered by the global `TextureManager`.
///
/// # Arguments
/// * `path` - relative path of the texture on the disk
/// * `name` - &str identifier to store this texture under
///
/// # See also
/// * [`Self::set_texture_from_file`] - to only modify this node.
#[inline]
pub fn set_texture_from_file_recursive(&mut self, path: &Path, name: &str) -> Self {
let texture = TextureManager::get_global_manager(|tm| tm.add(path, name));
self.set_texture_recursive(texture)
}
/// Sets the texture of this node's object only.
///
/// The texture is loaded from a byte slice and registered by the global `TextureManager`.
///
/// # Arguments
/// * `image_data` - slice of bytes containing encoded image
/// * `name` - &str identifier to store this texture under
///
/// # See also
/// * [`Self::set_texture_from_memory_recursive`] - to also modify all descendants.
#[inline]
pub fn set_texture_from_memory(&mut self, image_data: &[u8], name: &str) -> Self {
let texture =
TextureManager::get_global_manager(|tm| tm.add_image_from_memory(image_data, name));
self.set_texture(texture)
}
/// Sets the texture of this node's object and all its descendants.
///
/// The texture is loaded from a byte slice and registered by the global `TextureManager`.
///
/// # Arguments
/// * `image_data` - slice of bytes containing encoded image
/// * `name` - &str identifier to store this texture under
///
/// # See also
/// * [`Self::set_texture_from_memory`] - to only modify this node.
#[inline]
pub fn set_texture_from_memory_recursive(&mut self, image_data: &[u8], name: &str) -> Self {
let texture =
TextureManager::get_global_manager(|tm| tm.add_image_from_memory(image_data, name));
self.set_texture_recursive(texture)
}
/// Sets the texture of this node's object only.
///
/// The texture must already have been registered as `name`.
///
/// # See also
/// * [`Self::set_texture_with_name_recursive`] - to also modify all descendants.
#[inline]
pub fn set_texture_with_name(&mut self, name: &str) -> Self {
let texture = TextureManager::get_global_manager(|tm| {
tm.get(name).unwrap_or_else(|| {
panic!("Invalid attempt to use the unregistered texture: {}", name)
})
});
self.set_texture(texture)
}
/// Sets the texture of this node's object and all its descendants.
///
/// The texture must already have been registered as `name`.
///
/// # See also
/// * [`Self::set_texture_with_name`] - to only modify this node.
#[inline]
pub fn set_texture_with_name_recursive(&mut self, name: &str) -> Self {
let texture = TextureManager::get_global_manager(|tm| {
tm.get(name).unwrap_or_else(|| {
panic!("Invalid attempt to use the unregistered texture: {}", name)
})
});
self.set_texture_recursive(texture)
}
/// Sets the texture of this node's object only.
///
/// # See also
/// * [`Self::set_texture_recursive`] - to also modify all descendants.
pub fn set_texture(&mut self, texture: Arc<Texture>) -> Self {
self.apply_to_object_mut(&mut |o| o.set_texture(texture.clone()));
self.clone()
}
/// Sets the texture of this node's object and all its descendants.
///
/// # See also
/// * [`Self::set_texture`] - to only modify this node.
pub fn set_texture_recursive(&mut self, texture: Arc<Texture>) -> Self {
self.apply_to_objects_mut_recursive(&mut |o| o.set_texture(texture.clone()));
self.clone()
}
/// Applies a closure to this node's object (if any).
///
/// # See also
/// * [`Self::apply_to_objects_mut_recursive`] - to also apply to all descendants.
#[inline]
pub fn apply_to_object_mut<F: FnMut(&mut Object2d)>(&mut self, f: &mut F) {
let mut data = self.data_mut();
if let Some(ref mut o) = data.object {
f(o)
}
}
/// Applies a closure to this node's object (if any).
///
/// # See also
/// * [`Self::apply_to_objects_recursive`] - to also apply to all descendants.
#[inline]
pub fn apply_to_object<F: FnMut(&Object2d)>(&self, f: &mut F) {
let data = self.data();
if let Some(ref o) = data.object {
f(o)
}
}
/// Applies a closure to each object contained by this node and its descendants.
///
/// # See also
/// * [`Self::apply_to_object_mut`] - to only apply to this node.
#[inline]
pub fn apply_to_objects_mut_recursive<F: FnMut(&mut Object2d)>(&mut self, f: &mut F) {
let mut data = self.data_mut();
if let Some(ref mut o) = data.object {
f(o)
}
for c in data.children.iter_mut() {
c.apply_to_objects_mut_recursive(f)
}
}
/// Applies a closure to each object contained by this node and its descendants.
///
/// # See also
/// * [`Self::apply_to_object`] - to only apply to this node.
#[inline]
pub fn apply_to_objects_recursive<F: FnMut(&Object2d)>(&self, f: &mut F) {
let data = self.data();
if let Some(ref o) = data.object {
f(o)
}
for c in data.children.iter() {
c.apply_to_objects_recursive(f)
}
}
// TODO: add folding?
/// Sets the local scaling factors of the object.
#[inline]
pub fn set_local_scale(&mut self, sx: f32, sy: f32) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_scale = Vec2::new(sx, sy);
drop(data);
self.clone()
}
/// Returns the scaling factors of the object.
#[inline]
pub fn local_scale(&self) -> Vec2 {
let data = self.data();
data.local_scale
}
/// This node local transformation.
#[inline]
pub fn local_transformation(&self) -> Pose2 {
let data = self.data();
data.local_transform
}
/// Inverse of this node local transformation.
#[inline]
pub fn inverse_local_transformation(&self) -> Pose2 {
let data = self.data();
data.local_transform.inverse()
}
/// This node’s world pose (translation and rotation).
///
/// This will force an update of the world transformation of its parents if they have been
/// invalidated.
#[inline]
pub fn world_pose(&self) -> Pose2 {
let mut data = self.data.borrow_mut();
data.update();
data.world_transform
}
/// This node world scale.
///
/// This will force an update of the world transformation of its parents if they have been
/// invalidated.
#[inline]
pub fn world_scale(&self) -> Vec2 {
let mut data = self.data.borrow_mut();
data.update();
data.world_scale
}
/// Appends a transformation to this node local transformation.
#[inline]
pub fn transform(&mut self, t: Pose2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform = t * data.local_transform;
drop(data);
self.clone()
}
/// Prepends a transformation to this node local transformation.
#[inline]
pub fn prepend_transform(&mut self, t: Pose2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform *= t;
drop(data);
self.clone()
}
/// Set this node local transformation.
#[inline]
pub fn set_pose(&mut self, t: Pose2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform = t;
drop(data);
self.clone()
}
/// This node local translation.
#[inline]
pub fn position(&self) -> Vec2 {
let data = self.data();
data.local_transform.translation
}
/// Appends a translation to this node local transformation.
#[inline]
pub fn translate(&mut self, t: Vec2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform = Pose2::from_translation(t) * data.local_transform;
drop(data);
self.clone()
}
/// Prepends a translation to this node local transformation.
#[inline]
pub fn prepend_translation(&mut self, t: Vec2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform *= Pose2::from_translation(t);
drop(data);
self.clone()
}
/// Sets the local translation of this node.
#[inline]
pub fn set_position(&mut self, t: Vec2) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform.translation = t;
drop(data);
self.clone()
}
/// This node local rotation (in radians).
#[inline]
pub fn rotation(&self) -> Rot2 {
let data = self.data();
data.local_transform.rotation
}
/// Appends a rotation to this node local transformation.
#[inline]
pub fn append_rotation(&mut self, angle: f32) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform = Pose2::rotation(angle) * data.local_transform;
drop(data);
self.clone()
}
/// Appends a rotation to this node local transformation.
#[inline]
pub fn rotate(&mut self, angle: f32) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform.rotation = Rot2::from_angle(angle) * data.local_transform.rotation;
drop(data);
self.clone()
}
/// Prepends a rotation to this node local transformation.
#[inline]
pub fn prepend_rotation(&mut self, angle: f32) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform *= Pose2::rotation(angle);
drop(data);
self.clone()
}
/// Sets the local rotation of this node (in radians).
#[inline]
pub fn set_rotation(&mut self, angle: f32) -> Self {
let mut data = self.data_mut();
data.invalidate();
data.local_transform.rotation = Rot2::from_angle(angle);
drop(data);
self.clone()
}
/// Sets the instances for rendering multiple duplicates of this scene node.
///
/// This only duplicates this scene node, not any of its children.
pub fn set_instances(&mut self, instances: &[InstanceData2d]) -> Self {
self.data_mut().get_object_mut().set_instances(instances);
self.clone()
}
}