-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlua_scripting.rs
915 lines (734 loc) Β· 38.9 KB
/
lua_scripting.rs
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
use std::collections::HashMap;
use mlua::{Lua, Value as LuaValue, Result as LuaResult, Function as LuaFunction, Table as LuaTable};
use crate::ecs::SceneManager;
use crate::ecs::AttributeType;
use crate::ecs::AttributeValue;
use serde_json::Value as JsonValue;
use uuid::Uuid;
use std::fs;
use mlua::{LuaSerdeExt, UserData};
use crate::physics_engine::PhysicsEngine;
use rapier2d::prelude::*;
use std::path::PathBuf;
use egui::Key;
use crate::gui::scene_hierarchy::predefined_entities::PREDEFINED_ENTITIES;
use crate::project_manager::ProjectManager;
use crate::input_handler::InputHandler;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ScriptState {
pub state: HashMap<String, JsonValue>,
}
pub struct LuaScripting {
pub lua: Lua,
accumulated_time: f32,
script_state: ScriptState,
}
impl LuaScripting {
pub fn new() -> Self {
LuaScripting {
lua: Lua::new(),
accumulated_time: 0.0,
script_state: ScriptState::default(),
}
}
}
// In Lua:
// - `accumulated_time` is read-only.
// - `script_state` is writable.
// - `scene_manager` was previously accessible for both reading and writing. However, for safety reasons
// and to ensure that position updates happen within the physics engine, `scene_manager` is no longer
// directly accessible. Instead, it can be read and modified through specific bound functions.
impl LuaScripting {
// This is for binding physics engine functions to Lua
pub fn initialize_bindings_physics_engine(&mut self, physics_engine: &mut PhysicsEngine, scene_manager: &mut SceneManager) -> Result<(), mlua::Error> {
let physics_engine_ref = physics_engine as *mut PhysicsEngine;
let scene_manager_ref = scene_manager as *const SceneManager;
// Binding set_velocity
let set_velocity = self.lua.create_function(move |_, (entity_id, x, y): (String, f32, f32)| {
let physics_engine = unsafe { &mut *physics_engine_ref };
let uuid = Uuid::parse_str(&entity_id).map_err(|e| {
eprintln!("Invalid UUID '{}': {}", entity_id, e);
mlua::Error::external(format!("Invalid UUID '{}': {}", entity_id, e))
})?;
if !physics_engine.has_rigid_body(&uuid) {
eprintln!("Entity '{}' not found in physics engine.", uuid);
return Err(mlua::Error::external(format!(
"Entity '{}' not found in physics engine",
uuid
)));
}
// Set the velocity
let velocity = vector![x, y];
// eprintln!("Setting velocity for entity '{}': {:?}", uuid, velocity);
physics_engine.set_velocity(&uuid, velocity);
Ok(())
})?;
self.lua.globals().set("set_velocity", set_velocity)?;
// Binding apply_force
let apply_force = self.lua.create_function(move |_, (entity_id, x, y): (String, f32, f32)| {
let physics_engine = unsafe { &mut *physics_engine_ref };
let uuid = Uuid::parse_str(&entity_id).map_err(|e| {
eprintln!("Invalid UUID '{}': {}", entity_id, e);
mlua::Error::external(format!("Invalid UUID '{}': {}", entity_id, e))
})?;
if !physics_engine.has_rigid_body(&uuid) {
eprintln!("Entity '{}' not found in physics engine.", uuid);
return Err(mlua::Error::external(format!(
"Entity '{}' not found in physics engine",
uuid
)));
}
// Set the force
let force = vector![x, y];
// eprintln!("Setting force for entity '{}': {:?}", uuid, force);
physics_engine.apply_force(&uuid, force);
Ok(())
})?;
self.lua.globals().set("apply_force", apply_force)?;
// Binding apply_impulse
let apply_impulse = self.lua.create_function(move |_, (entity_id, x, y): (String, f32, f32)| {
let physics_engine = unsafe { &mut *physics_engine_ref };
let uuid = Uuid::parse_str(&entity_id).map_err(|e| {
eprintln!("Invalid UUID '{}': {}", entity_id, e);
mlua::Error::external(format!("Invalid UUID '{}': {}", entity_id, e))
})?;
if !physics_engine.has_rigid_body(&uuid) {
eprintln!("Entity '{}' not found in physics engine.", uuid);
return Err(mlua::Error::external(format!(
"Entity '{}' not found in physics engine",
uuid
)));
}
// Set the impulse
let impulse = vector![x, y];
// eprintln!("Setting impulse for entity '{}': {:?}", uuid, impulse);
physics_engine.apply_impulse(&uuid, impulse);
Ok(())
})?;
self.lua.globals().set("apply_impulse", apply_impulse)?;
// Binding add_entity (Rust) to add_entity_to_physics_engine (Lua)
let add_entity_to_physics_engine = self.lua.create_function(move |_, entity_id: String| {
let physics_engine = unsafe { &mut *physics_engine_ref };
let scene_manager = unsafe { &*scene_manager_ref };
let uuid = Uuid::parse_str(&entity_id).map_err(|e| {
mlua::Error::external(format!("Invalid UUID '{}': {}", entity_id, e))
})?;
if let Some(active_scene) = scene_manager.get_active_scene() {
if let Some(entity) = active_scene.entities.get(&uuid) {
physics_engine.add_entity(entity);
// println!("Entity '{}' added to physics engine.", uuid);
return Ok(());
}
}
Err(mlua::Error::external(format!(
"Entity '{}' not found in active scene",
uuid
)))
})?;
self.lua.globals().set("add_entity_to_physics_engine", add_entity_to_physics_engine)?;
// Binding remove_entity (Rust) to remove_entity_from_physics_engine (Lua)
let remove_entity_from_physics_engine = self.lua.create_function(move |_, entity_id: String| {
let physics_engine = unsafe { &mut *physics_engine_ref };
let uuid = Uuid::parse_str(&entity_id).map_err(|e| {
mlua::Error::external(format!("Invalid UUID '{}': {}", entity_id, e))
})?;
physics_engine.remove_entity(uuid);
// println!("Entity '{}' removed from physics engine.", uuid);
return Ok(());
})?;
self.lua.globals().set("remove_entity_from_physics_engine", remove_entity_from_physics_engine)?;
println!("Lua physics engine bindings initialized successfully.");
Ok(())
}
pub fn initialize_bindings_input_handler(&mut self, input_handler: &mut InputHandler) -> Result<(), mlua::Error> {
let input_handler_ref = input_handler as *mut InputHandler;
// Binding is_key_just_pressed
let is_key_just_pressed = self.lua.create_function(move |_, key: String| {
let input_handler = unsafe { &*input_handler_ref };
// Convert the key string to a Key enum
let parsed_key = Key::from_name(&key).ok_or_else(|| {
let error_message = format!("Invalid key '{}'", key);
eprintln!("{}", error_message);
mlua::Error::external(error_message)
})?;
// Check if the key was just pressed
let just_pressed = input_handler.is_key_just_pressed(parsed_key);
Ok(just_pressed)
})?;
self.lua.globals().set("is_key_just_pressed", is_key_just_pressed)?;
println!("Lua input handler bindings initialized successfully.");
Ok(())
}
// This is for binding ECS functions to Lua
pub fn initialize_bindings_ecs(&mut self, scene_manager: &mut SceneManager) -> Result<(), mlua::Error> {
let scene_manager_ref = scene_manager as *mut SceneManager;
// Binding add_entity
let add_entity = self.lua.create_function(move |_, (scene_id, entity_name): (String, String)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity_id = scene.create_entity(&entity_name)
.map_err(|e| mlua::Error::external(format!("Failed to create entity '{}': {}", entity_name, e)))?;
match scene.get_entity(entity_id) {
Ok(entity) => {
println!("Entity '{}' created in scene '{}':", entity_id, scene_uuid);
for (attr_name, attr) in &entity.attributes {
println!(
" Attribute: {} -> {:?} (Type: {:?})",
attr_name, attr.value, attr.data_type
);
}
}
Err(e) => {
println!(
"Entity '{}' created but failed to retrieve attributes for debug: {}",
entity_id, e
);
}
}
// println!("Entity '{}' created in scene '{}'", entity_id, scene_uuid);
Ok(entity_id.to_string())
})?;
self.lua.globals().set("add_entity", add_entity)?;
// Binding delete_entity
let remove_entity = self.lua.create_function(move |_, (scene_id, entity_id): (String, String)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let success = scene.delete_entity(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Failed to delete entity '{}': {}", entity_uuid, e)))?;
if success {
println!("Entity '{}' deleted from scene '{}'", entity_uuid, scene_uuid);
} else {
println!("Entity '{}' not found in scene '{}'", entity_uuid, scene_uuid);
}
Ok(success)
})?;
self.lua.globals().set("remove_entity", remove_entity)?;
// This uses create_entity, and add attributes inside the Lua, due to somehow create_physical_entity not working
let create_physical_entity = self.lua.create_function(move |_, (scene_id, name, x, y, z): (String, String, f32, f32, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity_id = scene.create_entity(&name)
.map_err(|e| mlua::Error::external(format!("Failed to create physical entity '{}': {}", name, e)))?;
// Assign default attributes based on predefined entities
if let Ok(entity) = scene.get_entity_mut(entity_id) {
if let Some(predefined) = PREDEFINED_ENTITIES.iter().find(|e| e.name == "Physics") {
for (attr_name, attr_type, attr_value) in predefined.attributes.iter() {
// Create attributes for the entity
let _ = entity.create_attribute(attr_name, attr_type.clone(), attr_value.clone());
}
}
} else {
return Err(mlua::Error::external(format!(
"Failed to retrieve entity with ID '{}'",
entity_id
)));
}
// println!("Physical entity '{}' created in scene '{}'", entity_id, scene_uuid);
Ok(entity_id.to_string())
})?;
self.lua.globals().set("create_physical_entity", create_physical_entity)?;
// Update Single Entity Attribute Binding
let set_x = self.lua.create_function(move |_, (scene_id, entity_id, value): (String, String, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.set_x(value)
.map_err(|e| mlua::Error::external(format!("Failed to set x: {}", e)))?;
// println!(
// "Set x to '{}' for entity '{}' in scene '{}'",
// value, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("set_x", set_x)?;
let set_y = self.lua.create_function(move |_, (scene_id, entity_id, value): (String, String, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.set_y(value)
.map_err(|e| mlua::Error::external(format!("Failed to set y: {}", e)))?;
// println!(
// "Set y to '{}' for entity '{}' in scene '{}'",
// value, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("set_y", set_y)?;
let set_z = self.lua.create_function(move |_, (scene_id, entity_id, value): (String, String, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.set_z(value)
.map_err(|e| mlua::Error::external(format!("Failed to set z: {}", e)))?;
// println!(
// "Set z to '{}' for entity '{}' in scene '{}'",
// value, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("set_z", set_z)?;
let set_position = self.lua.create_function(move |_, (scene_id, entity_id, x, y): (String, String, f32, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.set_position(x, y, 0.0)
.map_err(|e| mlua::Error::external(format!("Failed to set position: {}", e)))?;
// println!(
// "Set position to '({}, {}, 0.0)' for entity '{}' in scene '{}'",
// x, y, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("set_position", set_position)?;
// Add Image Binding
let add_image = self.lua.create_function(move |_, (entity_id, image_path): (String, String)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_active_scene_mut()
.ok_or_else(|| mlua::Error::external("No active scene found"))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
let full_image_path = PathBuf::from(ProjectManager::get_project_path().unwrap().to_string()).join(&image_path);
entity.add_image(full_image_path)
.map_err(|e| mlua::Error::external(format!("Failed to add image to entity '{}': {}", entity_uuid, e)))?;
// println!("Image added to entity '{}'", entity_uuid);
Ok(())
})?;
self.lua.globals().set("add_image", add_image)?;
// Set Script Binding
let set_script = self.lua.create_function(move |_, (entity_id, script_path): (String, String)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_active_scene_mut()
.ok_or_else(|| mlua::Error::external("No active scene found"))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
let full_script_path = PathBuf::from(ProjectManager::get_project_path().unwrap().to_string()).join(&script_path);
entity.set_script(full_script_path)
.map_err(|e| mlua::Error::external(format!("Failed to set script for entity '{}': {}", entity_uuid, e)))?;
// println!("Script set for entity '{}'", entity_uuid);
Ok(())
})?;
self.lua.globals().set("set_script", set_script)?;
let update_entity_attribute_bool = self.lua.create_function(move |_, (scene_id, entity_id, attr_name, value): (String, String, String, bool)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
// Parse UUIDs
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
// Find the scene
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
// Find the entity
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
// Find the attribute ID using the attribute name
let attr_id = entity
.get_attribute_by_name(&attr_name)
.map_err(|e| mlua::Error::external(format!("Attribute '{}' not found: {}", attr_name, e)))?
.id;
// Update the attribute value
scene
.update_entity_attribute(entity_uuid, attr_id, AttributeValue::Boolean(value))
.map_err(|e| mlua::Error::external(format!("Failed to update attribute '{}': {}", attr_name, e)))?;
println!(
"Boolean attribute '{}' updated to '{}' for entity '{}' in scene '{}'",
attr_name, value, entity_uuid, scene_uuid
);
Ok(())
})?;
self.lua.globals().set("update_entity_attribute_bool", update_entity_attribute_bool)?;
// Function to create a float attribute
let create_attribute_float = self.lua.create_function(move |_, (scene_id, entity_id, attr_name, value): (String, String, String, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.create_attribute(&attr_name, AttributeType::Float, AttributeValue::Float(value))
.map_err(|e| mlua::Error::external(format!("Failed to create float attribute '{}': {}", attr_name, e)))?;
// println!(
// "Float attribute '{}' with value '{}' created for entity '{}' in scene '{}'",
// attr_name, value, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("create_attribute_float", create_attribute_float)?;
// Function to create a bool attribute
let create_attribute_bool = self.lua.create_function(move |_, (scene_id, entity_id, attr_name, value): (String, String, String, bool)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.create_attribute(&attr_name, AttributeType::Boolean, AttributeValue::Boolean(value))
.map_err(|e| mlua::Error::external(format!("Failed to create boolean attribute '{}': {}", attr_name, e)))?;
// println!(
// "Boolean attribute '{}' with value '{}' created for entity '{}' in scene '{}'",
// attr_name, value, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("create_attribute_bool", create_attribute_bool)?;
// Function to create a vector2 attribute
let create_attribute_vector2 = self.lua.create_function(move |_, (scene_id, entity_id, attr_name, x, y): (String, String, String, f32, f32)| {
let scene_manager = unsafe { &mut *scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let entity_uuid = Uuid::parse_str(&entity_id)
.map_err(|e| mlua::Error::external(format!("Invalid entity UUID '{}': {}", entity_id, e)))?;
let scene = scene_manager
.get_scene_mut(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let entity = scene.get_entity_mut(entity_uuid)
.map_err(|e| mlua::Error::external(format!("Entity '{}' not found: {}", entity_uuid, e)))?;
entity.create_attribute(&attr_name, AttributeType::Vector2, AttributeValue::Vector2(x, y))
.map_err(|e| mlua::Error::external(format!("Failed to create vector2 attribute '{}': {}", attr_name, e)))?;
// println!(
// "Vector2 attribute '{}' with value '({}, {})' created for entity '{}' in scene '{}'",
// attr_name, x, y, entity_uuid, scene_uuid
// );
Ok(())
})?;
self.lua.globals().set("create_attribute_vector2", create_attribute_vector2)?;
// TODO: list_entities_name_x_y is not working, need to be fixed
let list_entities_name_x_y = self.lua.create_function(move |lua, scene_id: String| {
let scene_manager = unsafe { &*scene_manager_ref };
let scene_uuid = Uuid::parse_str(&scene_id)
.map_err(|e| mlua::Error::external(format!("Invalid scene UUID '{}': {}", scene_id, e)))?;
let scene = scene_manager
.get_scene(scene_uuid)
.ok_or_else(|| mlua::Error::external(format!("Scene '{}' not found", scene_uuid)))?;
let lua_table = lua.create_table()?;
for (index, (entity_id, entity)) in scene.entities.iter().enumerate() {
let name = &entity.name;
let (x, y) = if let Ok(position_attr) = entity.get_attribute_by_name("position") {
if let AttributeValue::Vector2(x, y) = position_attr.value {
(x, y)
} else {
(0.0, 0.0)
}
} else {
(0.0, 0.0)
};
// Create a table for each entity
let entity_data = lua.create_table()?;
entity_data.set("id", entity_id.to_string())?;
entity_data.set("name", name.to_string())?;
entity_data.set("x", x)?;
entity_data.set("y", y)?;
// println!("Entity '{}' list for scene '{}'", entity_id, name);
// Add the entity table to the main table
lua_table.set(index + 1, entity_data)?;
}
Ok(lua_table)
})?;
self.lua.globals().set("list_entities_name_x_y", list_entities_name_x_y)?;
println!("ECS bindings initialized successfully.");
Ok(())
}
/// Load SceneManager into Lua global space
pub fn load_scene_manager(&mut self, scene_manager: &SceneManager) -> Result<(), mlua::Error> {
// Serialize SceneManager as Lua userdata
self.lua = Lua::new();
let globals = self.lua.globals();
globals.set("scene_manager", self.lua.to_value(scene_manager)?)?;
Ok(())
}
pub fn load_script_state(&self) -> Result<(), mlua::Error> {
// Serialize ScriptState as Lua userdata
let globals = self.lua.globals();
globals.set("script_state", self.lua.to_value(&self.script_state)?)?;
Ok(())
}
pub fn update_script_state(&mut self) -> Result<(), String> {
// Update the script_state from Lua
let globals = self.lua.globals();
let script_state_lua: LuaValue = globals
.get("script_state")
.map_err(|e| format!("Error accessing Lua script_state: {}", e))?;
let script_state_json = self.lua.from_value(script_state_lua).map_err(|e| {
eprintln!("Error converting Lua script_state to JSON: {:?}", e);
format!("Failed to convert Lua script_state to JSON: {}", e)
})?;
// Deserialize JSON into ScriptState
self.script_state = serde_json::from_value(script_state_json)
.map_err(|e| format!("Error deserializing JSON script_state: {}", e))?;
println!("Script state updated: {:?}", self.script_state);
Ok(())
}
pub fn run_scripts_for_scene(
&mut self,
scene_manager: &mut SceneManager,
active_scene_id: Uuid,
) -> Result<(), String> {
let active_scene = scene_manager
.get_scene_mut(active_scene_id)
.ok_or_else(|| "Active scene not found.".to_string())?;
for (entity_id, entity) in &mut active_scene.entities {
if let Some(script_path) = &entity.script {
// println!("Found script for entity {}: {:?}", entity_id, script_path);
let script_content = std::fs::read_to_string(script_path)
.map_err(|e| format!("Error reading script file for entity {}: {}", entity_id, e))?;
self.lua
.load(&script_content)
.exec()
.map_err(|e| format!("Error executing script for entity {}: {}", entity_id, e))?;
let update_function: LuaFunction = self
.lua
.globals()
.get("update")
.map_err(|e| format!("Error: Script for entity {} does not define update(): {}", entity_id, e))?;
update_function
.call::<()>((active_scene_id.to_string(), entity_id.to_string()))
.map_err(|e| format!("Error executing update() in script for entity {}: {}", entity_id, e))?;
}
}
if let Err(e) = self.update_script_state() {
eprintln!("Error updating script state: {}", e);
} else {
println!("Script state updated successfully!");
}
println!("Lua scripts executed successfully for scene {}", active_scene_id);
Ok(())
}
/// Convert JSON Value to Lua Value
pub fn lua_to_json(&self, lua_value: LuaValue) -> Result<JsonValue, mlua::Error> {
match lua_value {
LuaValue::Table(table) => {
let mut is_array = true;
let mut array = Vec::new();
let mut map = serde_json::Map::new();
for pair in table.pairs::<LuaValue, LuaValue>() {
let (key, value) = pair?;
match key {
LuaValue::Integer(i) if i > 0 => {
if is_array {
let index = (i - 1) as usize; // Convert 1-based Lua index to 0-based
if index == array.len() {
array.push(self.lua_to_json(value)?);
} else {
is_array = false;
}
}
}
LuaValue::String(key_str) => {
is_array = false;
map.insert(key_str.to_str()?.to_string(), self.lua_to_json(value)?);
}
_ => {
return Err(mlua::Error::FromLuaConversionError {
from: "Lua key",
to: "JSON key".to_string(),
message: Some("Lua table keys must be strings or positive integers.".to_string()),
});
}
}
}
if is_array {
Ok(JsonValue::Array(array))
} else {
Ok(JsonValue::Object(map))
}
}
LuaValue::String(s) => Ok(JsonValue::String(s.to_str()?.to_string())),
LuaValue::Integer(i) => Ok(JsonValue::Number(i.into())),
LuaValue::Number(n) => Ok(JsonValue::Number(
serde_json::Number::from_f64(n).ok_or_else(|| mlua::Error::RuntimeError("Invalid float".into()))?,
)),
LuaValue::Boolean(b) => Ok(JsonValue::Bool(b)),
LuaValue::Nil => Ok(JsonValue::Null),
LuaValue::LightUserData(_) => {
// Skip LightUserData
eprintln!("Warning: Skipping LightUserData during JSON conversion.");
Ok(JsonValue::Null)
},
other => {
eprintln!("Error: Unsupported Lua value type. Value: {:?}", other);
Err(mlua::Error::FromLuaConversionError {
from: "Unsupported Lua value",
to: "JSON".to_string(),
message: Some(format!("Unsupported Lua value type: {:?}", other)),
})
}
}
}
pub fn json_to_lua(&self, value: &JsonValue) -> Result<LuaTable, mlua::Error> {
match value {
JsonValue::Object(map) => {
let table = self.lua.create_table()?;
for (key, val) in map {
table.set(key.clone(), self.value_to_lua(val)?)?;
}
Ok(table)
}
JsonValue::Array(array) => {
let table = self.lua.create_table()?;
for (i, val) in array.iter().enumerate() {
table.raw_set((i + 1) as i64, self.value_to_lua(val)?)?; // Ensure Lua arrays are 1-based
}
Ok(table)
}
_ => Err(mlua::Error::FromLuaConversionError {
from: "json",
to: "LuaTable".to_string(),
message: Some("Root value must be an object or an array.".to_string()),
}),
}
}
fn value_to_lua(&self, value: &JsonValue) -> Result<LuaValue, mlua::Error> {
match value {
JsonValue::Object(map) => Ok(LuaValue::Table(self.json_to_lua(value)?)),
JsonValue::Array(array) => {
let table = self.lua.create_table()?;
for (i, val) in array.iter().enumerate() {
table.raw_set((i + 1) as i64, self.value_to_lua(val)?)?; // Properly handle arrays as Lua arrays
}
Ok(LuaValue::Table(table))
}
JsonValue::String(s) => Ok(LuaValue::String(self.lua.create_string(s)?)),
JsonValue::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(LuaValue::Integer(i))
} else if let Some(f) = n.as_f64() {
Ok(LuaValue::Number(f))
} else {
Err(mlua::Error::FromLuaConversionError {
from: "number",
to: "LuaValue".to_string(),
message: None,
})
}
}
JsonValue::Bool(b) => Ok(LuaValue::Boolean(*b)),
JsonValue::Null => Ok(LuaValue::Nil),
}
}
pub fn run_entity_scripts(
&mut self,
scene_manager: &mut SceneManager,
active_scene_id: Uuid,
) -> Result<(), String> {
let mut scripts_to_run = Vec::new();
if let Some(active_scene) = scene_manager.get_scene_mut(active_scene_id) {
for (entity_id, entity) in &active_scene.entities {
if let Some(script_path) = &entity.script {
scripts_to_run.push((entity_id.clone(), script_path.clone()));
}
}
} else {
return Err("Active scene not found.".to_string());
}
for (entity_id, script_path) in scripts_to_run {
// println!("Found script for entity {}: {:?}", entity_id, script_path);
let script_content = std::fs::read_to_string(&script_path)
.map_err(|e| format!("Error reading script file for entity {}: {}", entity_id, e))?;
// println!("Executing script for entity {}...", entity_id);
// Load the Lua script
let lua_function = self.lua
.load(&script_content)
.into_function()
.map_err(|e| format!("Error loading script for entity {}: {}", entity_id, e))?;
self.execute_entity_script(lua_function, scene_manager, active_scene_id, entity_id)?;
}
Ok(())
}
fn execute_entity_script(
&self,
lua_function: LuaFunction,
scene_manager: &mut SceneManager,
scene_id: Uuid,
entity_id: Uuid,
) -> Result<(), String> {
// Serialize the scene_manager to pass to Lua
let json_scene_manager =
serde_json::to_value(scene_manager).map_err(|e| format!("Serialization error: {}", e))?;
let lua_scene_manager = self
.json_to_lua(&json_scene_manager)
.map_err(|e| format!("Error converting JSON to Lua: {}", e))?;
// Call the Lua function, passing the scene_id and entity_id as arguments
lua_function
.call::<()>((lua_scene_manager, scene_id.to_string(), entity_id.to_string()))
.map_err(|e| format!("Error executing Lua script: {}", e))
}
pub fn initializing_global_variables(&mut self, input_handler: &InputHandler) {
self.update_global_time(0.0);
self.load_script_state();
self.bind_keys_pressed(input_handler).unwrap();
}
pub fn update_global_time(&mut self, delta_time: f32) -> Result<(), String> {
// Increment accumulated time and sync with Lua
self.accumulated_time += delta_time;
self.lua
.globals()
.set("accumulated_time", self.accumulated_time)
.map_err(|e| e.to_string())
}
pub fn bind_keys_pressed(&self, input_handler: &InputHandler) -> Result<(), mlua::Error> {
let keys_pressed_table = self.lua.create_table()?;
for (index, key) in input_handler.get_all_active_inputs().iter().enumerate() {
keys_pressed_table.set(index + 1, key.to_string())?;
}
self.lua.globals().set("keys_pressed", keys_pressed_table)?;
Ok(())
}
}