gizmo-scripting 0.10.0

A custom ECS and physics engine aimed for realistic simulations.
Documentation
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
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
use gizmo_core::input::Input;
use gizmo_core::World;
use mlua::prelude::*;
use mlua::RegistryKey;
use std::collections::BTreeMap;
use std::sync::Arc;
use tracing::{debug, error, info, trace, warn};


/// Wakes the body a script just wrote a velocity to.
///
/// Required, not defensive. `PhysicsWorld::sync_bodies` **drops** a velocity written to a sleeping
/// dynamic body, because storing one makes a stale impulse: nothing reads it while the body
/// sleeps, and whatever wakes the body later applies it in full. `RigidBody::wake_up`'s own doc
/// states the contract — change a velocity, wake the body — and these four commands were the
/// scripting half of the engine ignoring it. A script that pushed a settled crate saw nothing
/// happen, and then saw the crate leap when something unrelated disturbed the stack.
///
/// Called after the `Velocity` borrow is released, because this takes its own on `RigidBody`.
fn wake_after_velocity_write(world: &mut World, id: u32) {
    let mut rbs = world.borrow_mut::<gizmo_physics_rigid::components::RigidBody>();
    if let Some(mut rb) = rbs.get_mut(id) {
        rb.wake_up();
    }
}

use crate::api_ai;
use crate::api_audio;
use crate::api_entity;
use crate::api_fighter;
use crate::api_input;
use crate::api_physics;
use crate::api_scene;
use crate::api_time;
use crate::api_vehicle;
use crate::commands::{CommandQueue, ScriptCommand};

/// Lua Scripting Motoru — Genişletilmiş API ile oyun mantığını yönetir
pub struct ScriptEngine {
    lua: Lua,
    /// Loaded scripts, keyed by path — **ordered**, and that is load-bearing rather than tidy.
    ///
    /// This was a `std::collections::HashMap`, whose `RandomState` is seeded per process, so the
    /// order `update` ran scripts in changed from run to run. Two scripts pushing commands that
    /// touch the same entity therefore resolved in a random order, and this engine's headline
    /// contract is same-platform bit-identical replay. A `BTreeMap` costs a comparison per lookup
    /// and makes the order a property of the scripts' paths instead of of the allocator.
    loaded_scripts: BTreeMap<String, (String, RegistryKey)>,
    command_queue: Arc<CommandQueue>,
    /// Hook ticks left for the Lua call currently running; see [`ScriptEngine::arm_budget`].
    budget: Arc<std::sync::atomic::AtomicU32>,
    /// Ticks handed out per call. `instructions / HOOK_INSTRUCTION_STEP`.
    budget_ticks: u32,
    elapsed_time: f32,
    /// Log messages emitted from Lua (`print`), stored as `(level, message)` pairs.
    pub log_queue: Arc<std::sync::Mutex<Vec<(String, String)>>>, // (Level, Message)
}

// `Send` is NOT hand-written: mlua is built with its `send` feature (see this
// crate's Cargo.toml), which makes `Lua: Send`, and every other field is already
// `Send`. The compiler derives it — if that ever stops holding we want the build
// to break rather than an `unsafe impl` to paper over it.

// SAFETY: `Lua` is `Send` but deliberately **not** `Sync` — mlua mutates the
// underlying `lua_State` through `&Lua`, so two threads holding `&Lua` would
// race. `Sync` on this type therefore has exactly one precondition:
//
//   *** No `&self` method of `ScriptEngine` may touch `self.lua`. ***
//
// That precondition holds by construction. The complete set of `&self` methods
// is `flush_commands`, `get_pending_audio_scene_commands` and `command_queue`;
// none of them reads `self.lua` (they only drain the `Arc<CommandQueue>` and the
// `Arc<Mutex<..>>` log queue, both of which are `Sync` on their own). Every
// method that does reach the VM — `new`, `load_script`, `reload_script`,
// `update`, `has_function`, `run_entity_update`, … — takes `&mut self`, so the
// borrow checker makes concurrent VM access unrepresentable: a caller needs
// `ResMut<ScriptEngine>`, which the scheduler treats as an exclusive write.
//
// `Sync` is required because `ScriptEngine` is stored as a `World` resource and
// `World::insert_resource` demands `Send + Sync`.
//
// If you add a `&self` method, it must not touch `self.lua`. The regression test
// `shared_methods_never_reach_the_lua_vm` at the bottom of this file records the
// audited list; update it deliberately, not incidentally.
unsafe impl Sync for ScriptEngine {}

// `Lua` does not implement `Debug`, so the engine provides a manual summary that
// omits the VM internals while still surfacing useful state.
impl std::fmt::Debug for ScriptEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptEngine")
            .field("lua", &"<Lua VM>")
            .field("loaded_scripts", &self.loaded_scripts.keys())
            .field("elapsed_time", &self.elapsed_time)
            .field(
                "queued_commands",
                &self.command_queue.len(),
            )
            .field(
                "queued_logs",
                &self.log_queue.lock().map(|q| q.len()).unwrap_or(0),
            )
            .finish()
    }
}

/// One value a script exposes to the editor.
///
/// Three kinds, because those are the three a property inspector can edit without inventing a
/// widget: a number, a flag, and a name. A script that needs more structure than this wants a
/// table it manages itself, not an inspector row.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ScriptValue {
    Num(f64),
    Bool(bool),
    Text(String),
}

impl ScriptValue {
    /// The label the inspector shows for this kind, and what a mismatched override is checked
    /// against: an override whose kind differs from the declaration is never *coerced*, because
    /// silently turning `true` into `1` is how a script starts misbehaving in a way nobody can
    /// trace to the editor.
    ///
    /// It is not *ignored* either, and this note used to say it was. Nothing filters
    /// [`Script::properties`] on its way to Lua — see
    /// `every_stored_property_reaches_the_script_declared_or_not`. The editor acted on the wrong
    /// half of that sentence: it dropped mismatched overrides from its display and showed the
    /// declared default, while the script kept running on the stale value. The inspector now
    /// shows every stored value and marks the odd ones instead.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Num(_) => "number",
            Self::Bool(_) => "bool",
            Self::Text(_) => "text",
        }
    }
}

/// ECS Componenti: Varlığın üzerine hangi Lua script'inin takılı olduğunu tutar
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Script {
    pub file_path: String,
    #[serde(default, skip)]
    pub initialized: bool, // on_init çağrıldı mı?
    /// Per-entity overrides for the properties this script declares.
    ///
    /// Scripts are loaded once per PATH — two entities running the same file share one Lua
    /// environment — so a per-entity value cannot live in that environment. It lives here and is
    /// handed to `on_entity_update` as its third argument.
    ///
    /// A `BTreeMap` for the same reason the loaded-script map is one: this crate's contract is
    /// same-platform bit-identical replay, and a `HashMap`'s iteration order is seeded per process.
    #[serde(default)]
    pub properties: std::collections::BTreeMap<String, ScriptValue>,
}

impl Script {
    pub fn new(path: &str) -> Self {
        Self {
            file_path: path.to_string(),
            initialized: false,
            properties: std::collections::BTreeMap::new(),
        }
    }
}

/// Lua'ya geçirilecek entity verisi (geriye dönük uyumluluk için)
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ScriptContext {
    pub entity_id: u32,
    pub dt: f32,
    pub position: [f32; 3],
    pub velocity: [f32; 3],
    pub key_w: bool,
    pub key_a: bool,
    pub key_s: bool,
    pub key_d: bool,
    pub key_space: bool,
    pub key_up: bool,
    pub key_down: bool,
    pub key_left: bool,
    pub key_right: bool,
}

/// Lua'dan dönen değişiklikler (geriye dönük uyumluluk)
#[derive(Clone, Debug, Default)]
pub struct ScriptResult {
    pub new_position: Option<[f32; 3]>,
    pub new_velocity: Option<[f32; 3]>,
}

impl ScriptEngine {
    /// Instructions between two hook firings. The hook itself is an atomic load and a compare, so
    /// this is not about the hook's cost — it is the resolution of the budget, and 10 000
    /// instructions is far below one frame's worth of anything sane.
    const HOOK_INSTRUCTION_STEP: u32 = 10_000;

    /// Default ceiling for a single call into Lua: `on_update` for one script, one entity hook,
    /// or the top level of a script being loaded.
    ///
    /// Two million instructions is generously above what a per-frame script should ever execute
    /// and far below "the window stopped responding". It is a runaway guard, not a performance
    /// budget: a script that trips it has a bug, and the alternative to tripping it was hanging
    /// the process, because `while true do end` in a Lua VM the host has no timeout on is
    /// unrecoverable — no signal, no watchdog, and the frame never ends.
    pub const DEFAULT_INSTRUCTION_BUDGET: u32 = 2_000_000;

    /// Default ceiling on the VM's heap. Reached, an allocation fails as a catchable Lua error
    /// instead of the process growing until the OOM killer decides which program dies — which on
    /// a machine running an editor and a game is not necessarily this one.
    pub const DEFAULT_MEMORY_LIMIT: usize = 64 * 1024 * 1024;

    pub fn new() -> Result<Self, LuaError> {
        let lua = Lua::new();
        let command_queue = Arc::new(CommandQueue::new());
        let log_queue = Arc::new(std::sync::Mutex::new(Vec::new()));

        // === SANDBOX: Tehlikeli modülleri kapat ===
        lua.globals().set("os", LuaNil)?;
        lua.globals().set("io", LuaNil)?;
        lua.globals().set("loadfile", LuaNil)?;
        lua.globals().set("dofile", LuaNil)?;
        lua.globals().set("require", LuaNil)?;
        lua.globals().set("package", LuaNil)?;
        lua.globals().set("debug", LuaNil)?;
        lua.globals().set("loadstring", LuaNil)?;
        lua.globals().set("load", LuaNil)?;

        // === RUNAWAY GUARD: instruction budget + memory ceiling ===
        // Without these a script is unbounded in both time and space, and the host has no way to
        // take control back: `while true do end` never yields, mlua's `call` never returns, and
        // the frame — the window, the editor, the game — is simply over. The budget is armed per
        // call (see `arm_budget`), so one runaway script loses its own frame and the scripts
        // ordered after it still run.
        let budget = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let hook_budget = budget.clone();
        lua.set_hook(
            mlua::HookTriggers::new().every_nth_instruction(Self::HOOK_INSTRUCTION_STEP),
            move |_lua, _debug| {
                // Not `fetch_sub` alone: at zero that wraps to `u32::MAX` and the guard silently
                // stops guarding. Load-then-store is safe here because the VM is single-threaded
                // by construction — every method that reaches it takes `&mut self`.
                let left = hook_budget.load(std::sync::atomic::Ordering::Relaxed);
                if left == 0 {
                    return Err(LuaError::RuntimeError(
                        "script exceeded its instruction budget for this call (infinite loop?)"
                            .to_string(),
                    ));
                }
                hook_budget.store(left - 1, std::sync::atomic::Ordering::Relaxed);
                Ok(())
            },
        );
        lua.set_memory_limit(Self::DEFAULT_MEMORY_LIMIT)?;

        // === TEMEL PRINT FONKSİYONU ===
        let lq_clone1 = log_queue.clone();
        lua.globals().set(
            "print_engine",
            lua.create_function(move |_, msg: String| {
                if let Ok(mut q) = lq_clone1.lock() {
                    q.push(("info".to_string(), msg));
                }
                Ok(())
            })?,
        )?;

        // Orijinal print'i de engine çıktısına yönlendir
        let lq_clone2 = log_queue.clone();
        lua.globals().set(
            "print",
            lua.create_function(move |_, values: LuaMultiValue| {
                let parts: Vec<String> = values
                    .iter()
                    .map(|v| {
                        if let mlua::Value::String(s) = v {
                            s.to_str().unwrap_or("").to_string()
                        } else if let mlua::Value::Number(n) = v {
                            n.to_string()
                        } else if let mlua::Value::Integer(i) = v {
                            i.to_string()
                        } else if let mlua::Value::Boolean(b) = v {
                            b.to_string()
                        } else {
                            format!("{:?}", v)
                        }
                    })
                    .collect();
                if let Ok(mut q) = lq_clone2.lock() {
                    q.push(("info".to_string(), parts.join("\t")));
                }
                Ok(())
            })?,
        )?;

        // === VEC3 YARDIMCI FONKSİYONLARI ===
        lua.load(
            r#"
            function vec3(x, y, z)
                return { x = x or 0, y = y or 0, z = z or 0 }
            end
            
            function vec3_add(a, b)
                return vec3(a.x + b.x, a.y + b.y, a.z + b.z)
            end
            
            function vec3_sub(a, b)
                return vec3(a.x - b.x, a.y - b.y, a.z - b.z)
            end
            
            function vec3_scale(v, s)
                return vec3(v.x * s, v.y * s, v.z * s)
            end
            
            function vec3_length(v)
                return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z)
            end
            
            function vec3_normalize(v)
                local len = vec3_length(v)
                if len > 0.0001 then
                    return vec3(v.x / len, v.y / len, v.z / len)
                end
                return vec3(0, 0, 0)
            end
            
            function vec3_dot(a, b)
                return a.x * b.x + a.y * b.y + a.z * b.z
            end
            
            function vec3_cross(a, b)
                return vec3(
                    a.y * b.z - a.z * b.y,
                    a.z * b.x - a.x * b.z,
                    a.x * b.y - a.y * b.x
                )
            end
            
            function vec3_lerp(a, b, t)
                return vec3(
                    a.x + (b.x - a.x) * t,
                    a.y + (b.y - a.y) * t,
                    a.z + (b.z - a.z) * t
                )
            end
            
            function vec3_distance(a, b)
                return vec3_length(vec3_sub(a, b))
            end
            
            -- Clamp utility
            function clamp(value, min, max)
                return math.max(min, math.min(max, value))
            end
            
            -- Lerp utility
            function lerp(a, b, t)
                return a + (b - a) * t
            end
        "#,
        )
        .exec()?;

        // === API MODÜLLERİNİ KAYDET ===
        api_entity::register_entity_api(&lua, command_queue.clone())?;
        api_fighter::register_fighter_api(&lua, command_queue.clone())?;
        api_input::register_input_api(&lua)?;
        api_physics::register_physics_api(&lua, command_queue.clone())?;
        api_scene::register_scene_api(&lua, command_queue.clone())?;
        api_audio::register_audio_api(&lua, command_queue.clone())?;
        api_time::register_time_api(&lua)?;
        api_vehicle::register_vehicle_api(&lua, command_queue.clone())?;
        api_ai::register_ai_api(&lua, command_queue.clone())?;

        info!("[Scripting] ScriptEngine başlatıldı — Lua 5.4 sandbox aktif, API modülleri kayıtlı");
        Ok(Self {
            lua,
            loaded_scripts: BTreeMap::new(),
            command_queue,
            budget,
            budget_ticks: Self::DEFAULT_INSTRUCTION_BUDGET / Self::HOOK_INSTRUCTION_STEP,
            elapsed_time: 0.0,
            log_queue,
        })
    }

    /// Hand the next call into Lua a fresh instruction budget.
    ///
    /// Per CALL, not per frame: `update` runs every loaded script, and a budget shared across them
    /// would let the first script to misbehave spend everyone's — which is the same failure the
    /// error-isolation fix removed from this loop, in a different currency.
    fn arm_budget(&self) {
        self.budget
            .store(self.budget_ticks, std::sync::atomic::Ordering::Relaxed);
    }

    /// Change the per-call instruction ceiling. Rounded down to a multiple of the hook step, and
    /// never to zero — a budget of zero would fail every script on its first hook.
    pub fn set_instruction_budget(&mut self, instructions: u32) {
        self.budget_ticks = (instructions / Self::HOOK_INSTRUCTION_STEP).max(1);
    }

    /// Change the VM's heap ceiling in bytes. Returns the previous limit.
    pub fn set_memory_limit(&mut self, bytes: usize) -> Result<usize, LuaError> {
        self.lua.set_memory_limit(bytes)
    }

    #[tracing::instrument(skip_all, name = "script_load", fields(path = %path))]
    pub fn load_script(&mut self, path: &str) -> Result<(), String> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            error!(path, error = %e, "[Scripting] Script dosyası okunamadı");
            format!("Script okunamadı {}: {}", path, e)
        })?;
        let byte_len = content.len();

        let env = self.lua.create_table().map_err(|e| e.to_string())?;

        // Link to _G via metatable: reads fall through to the shared globals (that is how a script
        // sees `entity`, `input`, `print`), writes land on the script's own table.
        let meta = self.lua.create_table().map_err(|e| e.to_string())?;
        meta.set("__index", self.lua.globals())
            .map_err(|e| e.to_string())?;
        env.set_metatable(Some(meta));

        // `_G` inside a script means the SCRIPT's table, not the engine's globals.
        //
        // Without this the isolation was one-way and easy to step around by accident: an implicit
        // `FOO = 1` stayed local, but the very next thing a Lua author reaches for — `_G.FOO = 1`,
        // which every tutorial spells as "the explicit way to make a global" — wrote straight into
        // the shared table, where the next script read it. Measured before the fix: script A set
        // `_G.LEAK` and script B read it back. Two scripts sharing a mutable namespace by accident
        // is a race with the load order, and the load order is alphabetical.
        //
        // Pointing `_G` at the env keeps the idiom meaning what the author expects — a global for
        // this script — while `__index` still exposes the engine API for reading.
        env.set("_G", env.clone()).map_err(|e| e.to_string())?;

        // Script'i İzole env içinde çalıştır
        self.arm_budget();
        self.lua
            .load(&content)
            .set_environment(env.clone())
            .exec()
            .map_err(|e| {
                error!(path, bytes = byte_len, error = %e, "[Scripting] Lua derleme/çalıştırma hatası");
                format!("Lua hata {}: {}", path, e)
            })?;

        let key = self
            .lua
            .create_registry_value(env)
            .map_err(|e| e.to_string())?;

        // Replace existing key if it exists to free old memory
        if let Some((_, old_key)) = self.loaded_scripts.insert(path.to_string(), (content, key)) {
            debug!(path, "[Scripting] Var olan script değiştirildi (hot-reload), eski sürüm boşaltılıyor");
            // Eskiden `let _ =` ile sessizce yutuluyordu; başarısızlık Lua registry
            // belleğini sızdırır. Davranış aynı (yine yok say) ama artık en azından loglanır.
            if let Err(e) = self.lua.remove_registry_value(old_key) {
                warn!(path, error = %e, "[Scripting] Eski script registry değeri boşaltılamadı (olası Lua bellek sızıntısı)");
            }
        }

        info!(path, bytes = byte_len, "🔧 [Scripting] Script yüklendi ve izole edildi");
        Ok(())
    }

    /// Her frame çağrılan güncelleme — World verilerini Lua'ya aktarır, scriptleri çalıştırır
    #[tracing::instrument(skip_all, name = "script_update")]
    pub fn update(&mut self, world: &World, input: &Input, dt: f32) -> Result<(), String> {
        self.elapsed_time += dt;

        // 1. World verilerini Lua'ya aktar (read snapshot)
        api_entity::update_entity_read_api(&self.lua, world)
            .map_err(|e| format!("Entity API güncelleme hatası: {}", e))?;
        api_fighter::update_fighter_read_api(&self.lua, world)
            .map_err(|e| format!("Fighter API güncelleme hatası: {}", e))?;
        api_input::update_input_api(&self.lua, input)
            .map_err(|e| format!("Input API güncelleme hatası: {}", e))?;
        api_scene::update_scene_api(&self.lua, world)
            .map_err(|e| format!("Scene API güncelleme hatası: {}", e))?;
        api_time::update_time_api(&self.lua, dt, self.elapsed_time, 1.0 / dt.max(0.0001))
            .map_err(|e| format!("Time API güncelleme hatası: {}", e))?;
        api_physics::update_physics_api(&self.lua, world)
            .map_err(|e| format!("Physics API güncelleme hatası: {}", e))?;

        // 2. on_update callback'ini çağır — her yüklü script'in KENDİ env'inden.
        //    Script'ler izole bir env içinde çalıştırıldığından (load_script), top-level
        //    `function on_update` globals'a DEĞİL o env'e yazılır; globals'tan okumak
        //    (eski kod) onu ASLA bulamaz → hook sessizce hiç çalışmazdı.
        let ctx_table = self.lua.create_table().map_err(|e| e.to_string())?;
        ctx_table.set("dt", dt).map_err(|e| e.to_string())?;
        ctx_table
            .set("elapsed", self.elapsed_time)
            .map_err(|e| e.to_string())?;

        // **One script's failure must not cancel the others.** This loop used to `?` on the first
        // runtime error, so a single throwing script silently stopped every script ordered after it
        // for that frame — and with the map now ordered by path, "after it" is a stable and
        // therefore reliably silent set. Errors are collected and reported together instead; a
        // broken script loses its own frame and nobody else's.
        // Wrapped in the call-time query scope: for the length of this loop — and only for it —
        // the physics API carries functions that hold `&World` and can answer a question the
        // engine could not have precomputed. See `api_physics::with_call_time_queries`.
        let lua = &self.lua;
        let scripts = &self.loaded_scripts;
        let budget = &self.budget;
        let budget_ticks = self.budget_ticks;
        let mut failures = Vec::new();
        api_physics::with_call_time_queries(lua, world, || {
            for (path, (_, key)) in scripts {
                let env: mlua::Table = match lua.registry_value(key) {
                    Ok(env) => env,
                    Err(e) => {
                        failures.push(format!("{path}: env okunamadı: {e}"));
                        continue;
                    }
                };
                if let Ok(func) = env.get::<_, LuaFunction>("on_update") {
                    budget.store(budget_ticks, std::sync::atomic::Ordering::Relaxed);
                    if let Err(e) = func.call::<_, ()>(ctx_table.clone()) {
                        warn!(path = %path, error = %e, "[Scripting] on_update çalışma-zamanı hatası");
                        failures.push(format!("Lua on_update hatası ({path}): {e}"));
                    }
                }
            }
            Ok(())
        })
        .map_err(|e| format!("script scope hatası: {e}"))?;

        if failures.is_empty() {
            Ok(())
        } else {
            // Every failure, not just the first: a caller that logs this sees the whole frame's
            // damage rather than one arbitrary script's share of it.
            Err(failures.join(" | "))
        }
    }

    /// Per-entity script güncelleme — Script component'i olan entity'ler için izole ortamda çalıştırır
    /// The properties a script DECLARES, read from its `properties` table.
    ///
    /// The convention is a plain assignment at the top of the file:
    ///
    /// ```lua
    /// properties = { open_speed = 2.4, locked = false }
    /// ```
    ///
    /// which lands in the script's own environment (`_G` is that environment — see `load_script`).
    /// This is the schema and the defaults: the editor lists these names, and an entity that has
    /// not overridden one runs with the declared value.
    ///
    /// Anything that is not a number, boolean or string is skipped rather than guessed at — a
    /// nested table is a script's own business and not an inspector row.
    pub fn declared_properties(
        &self,
        script_path: &str,
    ) -> std::collections::BTreeMap<String, ScriptValue> {
        let mut out = std::collections::BTreeMap::new();
        let Some((_, key)) = self.loaded_scripts.get(script_path) else {
            return out;
        };
        let Ok(env) = self.lua.registry_value::<mlua::Table>(key) else {
            return out;
        };
        let Ok(table) = env.get::<_, mlua::Table>("properties") else {
            return out;
        };
        for pair in table.pairs::<String, mlua::Value>() {
            let Ok((name, value)) = pair else { continue };
            let converted = match value {
                mlua::Value::Number(n) => Some(ScriptValue::Num(n)),
                mlua::Value::Integer(i) => Some(ScriptValue::Num(i as f64)),
                mlua::Value::Boolean(b) => Some(ScriptValue::Bool(b)),
                mlua::Value::String(s) => s.to_str().ok().map(|t| ScriptValue::Text(t.to_string())),
                _ => None,
            };
            if let Some(v) = converted {
                out.insert(name, v);
            }
        }
        out
    }


    /// Reads a numeric expression out of a loaded script's environment. Test-only.
    #[cfg(test)]
    pub fn eval_number(&self, script_path: &str, expr: &str) -> Option<f64> {
        let (_, key) = self.loaded_scripts.get(script_path)?;
        let env: mlua::Table = self.lua.registry_value(key).ok()?;
        self.lua
            .load(format!("return {expr}"))
            .set_environment(env)
            .eval::<f64>()
            .ok()
    }

    /// Runs `on_entity_update(entity_id, dt, props)` for one entity.
    ///
    /// `properties` are that entity's own values — the third argument exists because scripts are
    /// loaded per PATH, so two entities running the same file share one Lua environment and cannot
    /// each keep a value in it. Passing them is additive: a script whose `on_entity_update` takes
    /// two parameters simply ignores the third, which is why this did not need a new hook name.
    pub fn update_entity(
        &mut self,
        entity_id: u32,
        script_path: &str,
        dt: f32,
        properties: &std::collections::BTreeMap<String, ScriptValue>,
    ) -> Result<(), String> {
        if let Some((_, key)) = self.loaded_scripts.get(script_path) {
            let env: mlua::Table = self.lua.registry_value(key).map_err(|e| e.to_string())?;

            // on_entity_update(entity_id, dt, props) çağır (varsa)
            if let Ok(func) = env.get::<_, LuaFunction>("on_entity_update") {
                let props = self.lua.create_table().map_err(|e| e.to_string())?;
                for (name, value) in properties {
                    let set = match value {
                        ScriptValue::Num(n) => props.set(name.as_str(), *n),
                        ScriptValue::Bool(b) => props.set(name.as_str(), *b),
                        ScriptValue::Text(t) => props.set(name.as_str(), t.as_str()),
                    };
                    set.map_err(|e| e.to_string())?;
                }
                self.arm_budget();
                func.call::<_, ()>((entity_id, dt, props)).map_err(|e| {
                    warn!(entity_id, script_path, error = %e, "[Scripting] on_entity_update çalışma-zamanı hatası");
                    format!(
                        "Lua on_entity_update hatası (entity {} mod {}): {}",
                        entity_id, script_path, e
                    )
                })?;
            }
        } else {
            trace!(entity_id, script_path, "[Scripting] update_entity: script yüklü değil, atlandı");
        }
        Ok(())
    }

    /// Komut kuyruğundaki tüm komutları World'e uygular ve oyun mantığı için kalan komutları döndürür
    #[tracing::instrument(skip_all, name = "script_flush_commands")]
    pub fn flush_commands(&self, world: &mut World, dt: f32) -> Vec<ScriptCommand> {
        let commands = self.command_queue.drain();
        let total = commands.len();
        let mut unhandled = Vec::new();

        for cmd in commands {
            match cmd {
                ScriptCommand::SetPosition(id, pos) => {
                    let mut transforms = world.borrow_mut::<gizmo_physics_core::Transform>();
                    if let Some(mut t) = transforms.get_mut(id) {
                        t.position = pos;
                    } else {
                        trace!(entity = id, "[Scripting] SetPosition: hedefte Transform yok, komut atlandı");
                    }
                }
                ScriptCommand::SetRotation(id, rot) => {
                    let mut transforms = world.borrow_mut::<gizmo_physics_core::Transform>();
                    if let Some(mut t) = transforms.get_mut(id) {
                        t.rotation = rot;
                    } else {
                        trace!(entity = id, "[Scripting] SetRotation: hedefte Transform yok, komut atlandı");
                    }
                }
                ScriptCommand::SetScale(id, scale) => {
                    let mut transforms = world.borrow_mut::<gizmo_physics_core::Transform>();
                    if let Some(mut t) = transforms.get_mut(id) {
                        t.scale = scale;
                    } else {
                        trace!(entity = id, "[Scripting] SetScale: hedefte Transform yok, komut atlandı");
                    }
                }
                ScriptCommand::SetVelocity(id, vel) => {
                    let mut written = false;
                    {
                        let mut velocities = world.borrow_mut::<gizmo_physics_rigid::components::Velocity>();
                        if let Some(mut v) = velocities.get_mut(id) {
                            v.linear = vel;
                            written = true;
                        } else {
                            trace!(entity = id, "[Scripting] SetVelocity: hedefte Velocity yok, komut atlandı");
                        }
                    }
                    if written {
                        wake_after_velocity_write(world, id);
                    }
                }
                ScriptCommand::SetAngularVelocity(id, ang_vel) => {
                    let mut written = false;
                    {
                        let mut velocities = world.borrow_mut::<gizmo_physics_rigid::components::Velocity>();
                        if let Some(mut v) = velocities.get_mut(id) {
                            v.angular = ang_vel;
                            written = true;
                        } else {
                            trace!(entity = id, "[Scripting] SetAngularVelocity: hedefte Velocity yok, komut atlandı");
                        }
                    }
                    if written {
                        wake_after_velocity_write(world, id);
                    }
                }
                ScriptCommand::ApplyForce(id, force) => {
                    let rbs = world.borrow::<gizmo_physics_rigid::components::RigidBody>();
                    if let Some(rb) = rbs.get(id) {
                        if rb.mass > 0.0 {
                            let accel = force * (1.0 / rb.mass);
                            drop(rbs);
                            // RigidBody var ama Velocity yoksa sıfır hızla oluştur ki
                            // kuvvet sessizce kaybolmasın.
                            if world
                                .borrow::<gizmo_physics_rigid::components::Velocity>()
                                .get(id)
                                .is_none()
                            {
                                if let Some(e) = world.entity(id) {
                                    world.add_component(
                                        e,
                                        gizmo_physics_rigid::components::Velocity::new(
                                            gizmo_math::Vec3::ZERO,
                                        ),
                                    );
                                }
                            }
                            {
                                let mut vels =
                                    world.borrow_mut::<gizmo_physics_rigid::components::Velocity>();
                                if let Some(mut v) = vels.get_mut(id) {
                                    v.linear += accel * dt;
                                }
                            }
                            wake_after_velocity_write(world, id);
                        }
                    } else {
                        trace!(entity = id, "[Scripting] ApplyForce: hedefte RigidBody yok, kuvvet yok sayıldı");
                    }
                }
                ScriptCommand::ApplyImpulse(id, impulse) => {
                    let rbs = world.borrow::<gizmo_physics_rigid::components::RigidBody>();
                    if let Some(rb) = rbs.get(id) {
                        if rb.mass > 0.0 {
                            let delta_v = impulse * (1.0 / rb.mass);
                            drop(rbs);
                            // RigidBody var ama Velocity yoksa sıfır hızla oluştur ki
                            // impuls sessizce kaybolmasın.
                            if world
                                .borrow::<gizmo_physics_rigid::components::Velocity>()
                                .get(id)
                                .is_none()
                            {
                                if let Some(e) = world.entity(id) {
                                    world.add_component(
                                        e,
                                        gizmo_physics_rigid::components::Velocity::new(
                                            gizmo_math::Vec3::ZERO,
                                        ),
                                    );
                                }
                            }
                            {
                                let mut vels =
                                    world.borrow_mut::<gizmo_physics_rigid::components::Velocity>();
                                if let Some(mut v) = vels.get_mut(id) {
                                    v.linear += delta_v;
                                }
                            }
                            wake_after_velocity_write(world, id);
                        }
                    } else {
                        trace!(entity = id, "[Scripting] ApplyImpulse: hedefte RigidBody yok, impuls yok sayıldı");
                    }
                }
                ScriptCommand::AddRigidBody {
                    id,
                    mass,
                    use_gravity,
                } => {
                    let entity = world.entity(id);
                    if let Some(e) = entity {
                        let rb = gizmo_physics_rigid::components::RigidBody::new(mass, use_gravity);
                        world.add_component(e, rb);
                        // Make sure velocity exists so it can move
                        if world
                            .borrow::<gizmo_physics_rigid::components::Velocity>()
                            .get(id)
                            .is_none()
                        {
                            world.add_component(
                                e,
                                gizmo_physics_rigid::components::Velocity::new(gizmo_math::Vec3::ZERO),
                            );
                        }
                    } else {
                        trace!(entity = id, "[Scripting] AddRigidBody: entity bulunamadı, komut atlandı");
                    }
                }
                ScriptCommand::AddBoxCollider { id, hx, hy, hz } => {
                    let entity = world.entity(id);
                    if let Some(e) = entity {
                        let col =
                            gizmo_physics_core::Collider::aabb(gizmo_math::Vec3::new(hx, hy, hz));
                        world.add_component(e, col);
                    } else {
                        trace!(entity = id, "[Scripting] AddBoxCollider: entity bulunamadı, komut atlandı");
                    }
                }
                ScriptCommand::AddSphereCollider { id, radius } => {
                    let entity = world.entity(id);
                    if let Some(e) = entity {
                        let col = gizmo_physics_core::Collider::sphere(radius);
                        world.add_component(e, col);
                    } else {
                        trace!(entity = id, "[Scripting] AddSphereCollider: entity bulunamadı, komut atlandı");
                    }
                }

                // The three vehicle commands used to be matched here with empty bodies: Lua could
                // call them, they queued, and they vanished without a word. Applying them properly
                // needs `VehicleController`, which lives in `gizmo-physics-dynamics` and is not a
                // dependency of this crate — adding one to reach three commands is the wrong trade,
                // and the host that flushes these does have it. So they fall through to `unhandled`
                // like everything else this crate cannot apply itself, and the host is told.

                ScriptCommand::SpawnEntity { name, position } => {
                    let entity = world.spawn();
                    world.add_component(entity, gizmo_core::EntityName::new(&name));
                    world
                        .add_component(entity, gizmo_physics_core::Transform::new(position));
                    let msg = format!(
                        "Entity spawn: '{}' at ({:.1}, {:.1}, {:.1})",
                        name, position.x, position.y, position.z
                    );
                    if let Ok(mut q) = self.log_queue.lock() {
                        q.push(("info".to_string(), msg));
                    }
                }
                ScriptCommand::SpawnPrefab {
                    name,
                    prefab_type,
                    position,
                } => {
                    let entity = world.spawn();
                    world.add_component(entity, gizmo_core::EntityName::new(&name));
                    world
                        .add_component(entity, gizmo_physics_core::Transform::new(position));
                    world.add_component(entity, gizmo_core::PrefabRequest(prefab_type.clone()));
                }
                ScriptCommand::DestroyEntity(id) => {
                    world.despawn_by_id(id);
                    if let Ok(mut q) = self.log_queue.lock() {
                        q.push(("info".to_string(), format!("Entity destroyed: {}", id)));
                    }
                }
ScriptCommand::SetEntityName(id, name) => {
                    let mut names = world.borrow_mut::<gizmo_core::EntityName>();
                    if let Some(mut n) = names.get_mut(id) {
                        n.0 = name;
                    } else {
                        trace!(entity = id, "[Scripting] SetEntityName: hedefte EntityName yok, komut atlandı");
                    }
                }
ScriptCommand::PlayAnimation { id, name, blend, loop_anim } => {
                    let mut players = world.borrow_mut::<gizmo_animation::skeletal::AnimationPlayer>();
                    if let Some(mut player) = players.get_mut(id) {
                        player.play_animation_by_name(&name, blend, loop_anim);
                    } else {
                        trace!(entity = id, anim = %name, "[Scripting] PlayAnimation: hedefte AnimationPlayer yok, komut atlandı");
                    }
                }
                ScriptCommand::SetAnimationSpeed(id, speed) => {
                    let mut players = world.borrow_mut::<gizmo_animation::skeletal::AnimationPlayer>();
                    if let Some(mut player) = players.get_mut(id) {
                        player.speed = speed;
                    } else {
                        trace!(entity = id, "[Scripting] SetAnimationSpeed: hedefte AnimationPlayer yok, komut atlandı");
                    }
                }
                ScriptCommand::AddNavAgent(id) => {
                    let entity = world.entity(id);
                    if let Some(e) = entity {
                        world.add_component(e, gizmo_ai::components::NavAgent::default());
                    } else {
                        trace!(entity = id, "[Scripting] AddNavAgent: entity bulunamadı, komut atlandı");
                    }
                }
                ScriptCommand::SetAiTarget(id, target) => {
                    let mut agents = world.borrow_mut::<gizmo_ai::components::NavAgent>();
                    if let Some(mut agent) = agents.get_mut(id) {
                        agent.set_target(target);
                    } else {
                        trace!(entity = id, "[Scripting] SetAiTarget: hedefte NavAgent yok, komut atlandı");
                    }
                }
                ScriptCommand::ClearAiTarget(id) => {
                    let mut agents = world.borrow_mut::<gizmo_ai::components::NavAgent>();
                    if let Some(mut agent) = agents.get_mut(id) {
                        // Must clear the TARGET, not just the path — clearing only the path
                        // leaves target set, so ai_navigation_system recomputes and keeps going.
                        agent.clear_target();
                    } else {
                        trace!(entity = id, "[Scripting] ClearAiTarget: hedefte NavAgent yok, komut atlandı");
                    }
                }
                ScriptCommand::SetFighterMove { id, name, startup, active, recovery, damage } => {
                    let mut fighters = world.borrow_mut::<gizmo_physics_core::components::FighterController>();
                    if let Some(mut fighter) = fighters.get_mut(id) {
                        let mut frame_data =
                            gizmo_physics_core::components::fighter::FrameData::default();
                        frame_data.startup = startup;
                        frame_data.active = active;
                        frame_data.recovery = recovery;
                        frame_data.damage = damage;
                        let mut combat_move =
                            gizmo_physics_core::components::fighter::CombatMove::default();
                        combat_move.name = name;
                        combat_move.frame_data = frame_data;
                        fighter.active_move = Some(combat_move);
                        fighter.current_move_frame = 0;
                    } else {
                        trace!(entity = id, "[Scripting] SetFighterMove: hedefte FighterController yok, komut atlandı");
                    }
                }
                ScriptCommand::ApplyHitstop(id, frames) => {
                    let mut fighters = world.borrow_mut::<gizmo_physics_core::components::FighterController>();
                    if let Some(mut fighter) = fighters.get_mut(id) {
                        fighter.apply_hitstop(frames);
                    } else {
                        trace!(entity = id, frames, "[Scripting] ApplyHitstop: hedefte FighterController yok, komut atlandı");
                    }
                }
                ScriptCommand::ApplyHitstun(id, frames) => {
                    let mut fighters = world.borrow_mut::<gizmo_physics_core::components::FighterController>();
                    if let Some(mut fighter) = fighters.get_mut(id) {
                        fighter.apply_hitstun(frames);
                    } else {
                        trace!(entity = id, frames, "[Scripting] ApplyHitstun: hedefte FighterController yok, komut atlandı");
                    }
                }
                // The scene, dialogue, race and camera commands used to be matched here by an
                // arm whose body was empty and whose comment said they would "already appear in
                // unhandled". They could not: this arm consumed them, so the `other` catch-all
                // below never saw them and the host was never told. Deleting the arm is the whole
                // fix — they now fall through and are returned, which is what the comment claimed.
                other => {
                    unhandled.push(other);
                }
            }
        }

        if total > 0 {
            trace!(
                total,
                unhandled = unhandled.len(),
                "[Scripting] script komut kuyruğu boşaltıldı"
            );
        }
        unhandled
    }

    /// Runtime'da bekleyen ses/sahne komutlarını döndürür (demo tarafında ele alınır)
    pub fn get_pending_audio_scene_commands(&self) -> Vec<ScriptCommand> {
        // Flush zaten çağrıldıysa bu boş dönecek
        // Alternatif: flush'tan önce çağrılmalı
        Vec::new()
    }

    /// Script'in hot-reload edilip edilmeyeceğini kontrol eder
    pub fn reload_if_changed(&mut self, path: &str) -> Result<bool, String> {
        let current =
            std::fs::read_to_string(path).map_err(|e| format!("Script okunamadı: {}", e))?;

        if let Some((cached_code, _)) = self.loaded_scripts.get(path) {
            if *cached_code == current {
                return Ok(false);
            }
        }

        self.load_script(path)?;
        Ok(true)
    }

    /// Belirli bir isimdeki Lua fonksiyonunun var olup olmadığını kontrol eder
    ///
    /// Takes `&mut self` even though it only reads: `registry_value` mutates the
    /// underlying `lua_State`, and the `unsafe impl Sync` above is only sound
    /// while no `&self` method reaches the VM.
    pub fn has_function(&mut self, path: &str, name: &str) -> bool {
        if let Some((_, key)) = self.loaded_scripts.get(path) {
            if let Ok(env) = self.lua.registry_value::<mlua::Table>(key) {
                return env.get::<_, LuaFunction>(name).is_ok();
            }
        }
        false
    }

    /// Belirli bir isimdeki Lua fonksiyonunu çağırır (per-entity scriptler için)
    ///
    /// Takes `&mut self`: calling into the VM mutates the `lua_State`, and the
    /// `unsafe impl Sync` above is only sound while no `&self` method does that.
    pub fn run_entity_update(
        &mut self,
        path: &str,
        func_name: &str,
        ctx: &ScriptContext,
    ) -> Result<ScriptResult, String> {
        let env: mlua::Table = if let Some((_, key)) = self.loaded_scripts.get(path) {
            self.lua.registry_value(key).map_err(|e| e.to_string())?
        } else {
            return Err(format!("Script not loaded: {}", path));
        };

        let func: LuaFunction = match env.get(func_name) {
            Ok(f) => f,
            Err(e) => {
                trace!(path, func_name, error = %e, "[Scripting] run_entity_update: fonksiyon alınamadı, varsayılan sonuç");
                return Ok(ScriptResult::default());
            }
        };

        let ctx_table = self.lua.create_table().map_err(|e| e.to_string())?;
        ctx_table
            .set("entity_id", ctx.entity_id)
            .map_err(|e| e.to_string())?;
        ctx_table.set("dt", ctx.dt).map_err(|e| e.to_string())?;
        ctx_table
            .set("elapsed", self.elapsed_time)
            .map_err(|e| e.to_string())?;

        let pos = self.lua.create_table().map_err(|e| e.to_string())?;
        pos.set("x", ctx.position[0]).map_err(|e| e.to_string())?;
        pos.set("y", ctx.position[1]).map_err(|e| e.to_string())?;
        pos.set("z", ctx.position[2]).map_err(|e| e.to_string())?;
        ctx_table.set("position", pos).map_err(|e| e.to_string())?;

        let vel = self.lua.create_table().map_err(|e| e.to_string())?;
        vel.set("x", ctx.velocity[0]).map_err(|e| e.to_string())?;
        vel.set("y", ctx.velocity[1]).map_err(|e| e.to_string())?;
        vel.set("z", ctx.velocity[2]).map_err(|e| e.to_string())?;
        ctx_table.set("velocity", vel).map_err(|e| e.to_string())?;

        let input = self.lua.create_table().map_err(|e| e.to_string())?;
        input.set("w", ctx.key_w).map_err(|e| e.to_string())?;
        input.set("a", ctx.key_a).map_err(|e| e.to_string())?;
        input.set("s", ctx.key_s).map_err(|e| e.to_string())?;
        input.set("d", ctx.key_d).map_err(|e| e.to_string())?;
        input
            .set("space", ctx.key_space)
            .map_err(|e| e.to_string())?;
        input.set("up", ctx.key_up).map_err(|e| e.to_string())?;
        input.set("down", ctx.key_down).map_err(|e| e.to_string())?;
        input.set("left", ctx.key_left).map_err(|e| e.to_string())?;
        input
            .set("right", ctx.key_right)
            .map_err(|e| e.to_string())?;
        ctx_table.set("input", input).map_err(|e| e.to_string())?;

        self.arm_budget();
        let result_table: LuaTable = func.call(ctx_table).map_err(|e| {
            warn!(path, func_name, error = %e, "[Scripting] run_entity_update: Lua çalışma-zamanı hatası");
            format!("Lua runtime: {}", e)
        })?;

        let mut result = ScriptResult::default();

        if let Ok(pos) = result_table.get::<_, LuaTable>("position") {
            let x: f32 = pos.get("x").unwrap_or(0.0);
            let y: f32 = pos.get("y").unwrap_or(0.0);
            let z: f32 = pos.get("z").unwrap_or(0.0);
            result.new_position = Some([x, y, z]);
        }

        if let Ok(vel) = result_table.get::<_, LuaTable>("velocity") {
            let x: f32 = vel.get("x").unwrap_or(0.0);
            let y: f32 = vel.get("y").unwrap_or(0.0);
            let z: f32 = vel.get("z").unwrap_or(0.0);
            result.new_velocity = Some([x, y, z]);
        }

        Ok(result)
    }

    /// Komut kuyruğuna doğrudan erişim (internals)
    pub fn command_queue(&self) -> &Arc<CommandQueue> {
        &self.command_queue
    }
}

gizmo_core::impl_component!(Script);

#[cfg(test)]
mod soundness {
    use super::*;

    /// `ScriptEngine` must be `Send + Sync` — it is stored as a `World`
    /// resource and `insert_resource` requires both.
    ///
    /// `Send` is derived (mlua's `send` feature makes `Lua: Send`); `Sync` is
    /// the hand-written `unsafe impl` above.
    #[test]
    fn script_engine_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ScriptEngine>();
    }

    /// Locks the precondition of the `unsafe impl Sync for ScriptEngine`:
    /// **no `&self` method may touch `self.lua`**, because mlua mutates the
    /// `lua_State` through `&Lua` and two threads sharing `&ScriptEngine` would
    /// race on it.
    ///
    /// The audited shared surface is exactly these three methods, none of which
    /// reads `self.lua`:
    ///   - `flush_commands`
    ///   - `get_pending_audio_scene_commands`
    ///   - `command_queue`
    ///
    /// This test calls each of them through a genuinely shared `&ScriptEngine`
    /// obtained from two threads at once. It cannot prove the absence of a
    /// future `&self` VM access on its own — but it does prove these three stay
    /// callable from a shared reference, so converting one of them to
    /// `&mut self` (the correct move if it ever needs the VM) breaks this test
    /// and forces the SAFETY comment to be revisited.
    #[test]
    fn shared_methods_never_reach_the_lua_vm() {
        let engine = ScriptEngine::new().expect("Lua VM");
        let shared = &engine;

        std::thread::scope(|s| {
            for _ in 0..2 {
                s.spawn(move || {
                    // Every `&self` method on the audited list, exercised
                    // concurrently. If any of these grew a `self.lua` access,
                    // this is a data race that Miri/TSan would flag here.
                    let _ = shared.get_pending_audio_scene_commands();
                    let _ = shared.command_queue().len();
                });
            }
        });

        // `flush_commands` needs a &mut World, so drive it on one thread — the
        // point is only that it is reachable through `&self`.
        let mut world = gizmo_core::World::new();
        let _ = shared.flush_commands(&mut world, 1.0 / 60.0);
    }

    /// The two methods that DO reach the VM must require exclusive access, so
    /// the borrow checker — not a comment — prevents concurrent VM use.
    ///
    /// This is a compile-time assertion: it only builds while both take
    /// `&mut self`. Reverting either to `&self` fails to compile here.
    #[test]
    fn vm_touching_methods_require_exclusive_access() {
        fn _needs_mut(e: &mut ScriptEngine) {
            let _ = e.has_function("nope.lua", "on_update");
        }
        fn _needs_mut_2(e: &mut ScriptEngine, ctx: &ScriptContext) {
            let _ = e.run_entity_update("nope.lua", "on_update", ctx);
        }
    }
}

#[cfg(test)]
mod tests {

    /// One script's globals must not be another's, including the explicit spelling.
    ///
    /// Each script already ran in its own environment, so an implicit `FOO = 1` stayed local. But
    /// `_G` resolved to the ENGINE's globals through the environment's `__index`, so `_G.FOO = 1`
    /// — the spelling every Lua tutorial gives for "make this global" — wrote into the shared
    /// table and the next script read it back. Measured, not theorised: script A set `_G.LEAK` and
    /// script B saw `from-a`. Two scripts sharing a mutable namespace by accident is a race with
    /// the load order, and the load order is alphabetical.
    #[test]
    fn a_script_cannot_reach_another_through_g() {
        let dir = std::env::temp_dir().join(format!("gizmo_sandbox_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = dir.join("a_writer.lua");
        let b = dir.join("b_reader.lua");
        std::fs::write(&a, "function on_update(c)\n  _G.LEAK = 'from-a'\n  IMPLICIT = 'also-a'\nend\n")
            .unwrap();
        std::fs::write(
            &b,
            "function on_update(c)\n  print('LEAK=' .. tostring(_G.LEAK))\n  print('IMPLICIT=' .. tostring(IMPLICIT))\nend\n",
        )
        .unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        engine.load_script(a.to_str().unwrap()).unwrap();
        engine.load_script(b.to_str().unwrap()).unwrap();
        engine.update(&World::new(), &Input::default(), 0.016).unwrap();

        let log = engine.log_queue.lock().unwrap().clone();
        let said = |needle: &str| log.iter().any(|(_, m)| m.contains(needle));
        assert!(said("LEAK=nil"), "`_G.X` from one script reached another: {log:?}");
        assert!(said("IMPLICIT=nil"), "an implicit global reached another script: {log:?}");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// …and the containment must not have cost the script its API. `_G` is the script's own table
    /// now, but reads still fall through to the engine's globals, which is what makes `print`,
    /// `input` and the rest visible at all.
    #[test]
    fn a_script_still_reaches_the_engine_api_and_its_own_globals() {
        let dir = std::env::temp_dir().join(format!("gizmo_sandbox2_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("s.lua");
        std::fs::write(
            &path,
            "function on_update(c)\n  _G.MINE = 5\n  print('mine=' .. tostring(MINE))\n  print('api=' .. tostring(_G.input ~= nil and _G.print ~= nil))\n  print('std=' .. tostring(string.rep('x', 2)))\nend\n",
        )
        .unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        engine.load_script(path.to_str().unwrap()).unwrap();
        engine.update(&World::new(), &Input::default(), 0.016).unwrap();

        let log = engine.log_queue.lock().unwrap().clone();
        let said = |needle: &str| log.iter().any(|(_, m)| m.contains(needle));
        assert!(said("mine=5"), "a script's own `_G` write must be visible to itself: {log:?}");
        assert!(said("api=true"), "the engine API must still resolve through `_G`: {log:?}");
        assert!(said("std=xx"), "the Lua standard library must still resolve: {log:?}");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A script cannot rewrite the engine API out from under the other scripts.
    ///
    /// `_G` isolation made a script's *globals* its own. It did not make the API tables its own,
    /// because `input.is_pressed = f` is not a global write — it is a field write on an object
    /// every script holds a reference to. Measured before the fix: script A replaced
    /// `input.is_pressed`, and script B called A's version.
    ///
    /// What closes it is a proxy (see `api_table`), and specifically not a bare `__newindex`:
    /// that metamethod fires only for keys the table does not already have, and every key worth
    /// clobbering is one it has.
    #[test]
    fn a_script_cannot_rewrite_the_api_for_everyone_else() {
        let dir = std::env::temp_dir().join(format!("gizmo_api_ro_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = dir.join("a_vandal.lua");
        let b = dir.join("b_victim.lua");
        std::fs::write(
            &a,
            "function on_update(c)\n  input.is_pressed = function(k) return 'CLOBBERED' end\nend\n",
        )
        .unwrap();
        std::fs::write(
            &b,
            "function on_update(c)\n  print('sees=' .. tostring(input.is_pressed('w')))\nend\n",
        )
        .unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        engine.load_script(a.to_str().unwrap()).unwrap();
        engine.load_script(b.to_str().unwrap()).unwrap();

        // The vandal's own frame fails — loudly, with the reason — and the victim's does not.
        let err = engine.update(&World::new(), &Input::default(), 0.016).unwrap_err();
        assert!(err.contains("read-only"), "expected a read-only refusal, got: {err}");

        let log = engine.log_queue.lock().unwrap().clone();
        assert!(
            log.iter().any(|(_, m)| m.contains("sees=false")),
            "the neighbour saw a rewritten API: {log:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A parameterised query the engine could not have precomputed, answered while the script is
    /// calling.
    ///
    /// This is the item the audit recorded as blocked. Its reasoning was right about
    /// `Lua::create_function` — with mlua's `send` feature that wants `Fn(..) + Send + 'static`,
    /// and `&World` is neither — and wrong about the conclusion, because `Scope::create_function`
    /// carries no such bound: `F: Fn(..) + 'scope`. A scoped closure may borrow the world, and the
    /// borrow ends when the scope does, which is the frame.
    ///
    /// "Ground height at (x, z)" is the audit's own example, and it is the right shape of example:
    /// there is no snapshot that answers it, because the engine does not know which (x, z) the
    /// script will ask about until it asks.
    #[test]
    fn a_script_can_ask_a_question_the_engine_did_not_precompute() {
        use gizmo_physics_rigid::world::PhysicsWorld;

        let dir = std::env::temp_dir().join(format!("gizmo_probe_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("probe.lua");
        std::fs::write(
            &path,
            "function on_update(c)\n             \x20 print('on_slab=' .. tostring(physics.ground_at(0.0, 0.0)))\n             \x20 print('off_slab=' .. tostring(physics.ground_at(500.0, 500.0)))\n             end\n",
        )
        .unwrap();

        // A floor slab whose top sits at y = 2.
        use gizmo_math::Vec3;
        use gizmo_physics_core::{BodyHandle, Collider, Transform};
        use gizmo_physics_rigid::{RigidBody, Velocity};

        let mut world = World::new();
        let mut pw = PhysicsWorld::new();
        pw.add_body(
            BodyHandle::from_id(0),
            RigidBody::new_static(),
            Transform::new(Vec3::new(0.0, 0.0, 0.0)),
            Velocity::default(),
            Collider::box_collider(Vec3::new(50.0, 2.0, 50.0)),
        );
        world.insert_resource(pw);

        let mut engine = ScriptEngine::new().unwrap();
        engine.load_script(path.to_str().unwrap()).unwrap();
        engine.update(&world, &Input::default(), 0.016).unwrap();

        let log = engine.log_queue.lock().unwrap().clone();
        let line = |k: &str| {
            log.iter()
                .find_map(|(_, m)| m.strip_prefix(k).map(str::to_string))
                .unwrap_or_else(|| panic!("no `{k}` line in {log:?}"))
        };
        let on_slab: f32 = line("on_slab=").parse().expect("a height over the slab");
        assert!((on_slab - 2.0).abs() < 0.01, "expected the slab top at 2.0, got {on_slab}");
        assert_eq!(line("off_slab="), "nil", "no floor there must read as nil, not as zero");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// …and the borrow does not outlive the frame: the name is gone once the scope closes, so a
    /// script that saved it cannot call into a world that is no longer there.
    #[test]
    fn the_call_time_query_is_not_available_outside_the_frame() {
        let lua = Lua::new();
        crate::api_physics::register_physics_api(&lua, Arc::new(CommandQueue::new())).unwrap();
        let world = World::new();

        crate::api_physics::with_call_time_queries(&lua, &world, || {
            let present: bool = lua.load("return physics.ground_at ~= nil").eval()?;
            assert!(present, "the query must exist while the frame is running");
            Ok(())
        })
        .unwrap();

        let present: bool = lua.load("return physics.ground_at ~= nil").eval().unwrap();
        assert!(!present, "the query must be gone once the frame is over");
    }

    /// A script that never returns must lose its frame, not the process.
    ///
    /// `while true do end` in a Lua VM the host has no timeout on is unrecoverable: the call never
    /// returns, so the frame never ends, so the window never redraws and never processes the
    /// close event either. There is no signal to catch and no watchdog thread that could help —
    /// only the VM can interrupt itself, which is what the instruction hook is for.
    #[test]
    fn an_infinite_loop_ends_the_call_instead_of_the_process() {
        let dir = std::env::temp_dir().join(format!("gizmo_budget_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("runaway.lua");
        std::fs::write(&path, "function on_update(ctx)\n  while true do end\nend\n").unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        // Small enough to trip in milliseconds; the default is a runaway guard, not a stopwatch.
        engine.set_instruction_budget(200_000);
        engine.load_script(path.to_str().unwrap()).unwrap();

        let world = World::new();
        let input = Input::default();
        let started = std::time::Instant::now();
        let err = engine.update(&world, &input, 0.016).unwrap_err();
        let took = started.elapsed();

        assert!(err.contains("instruction budget"), "unexpected error: {err}");
        assert!(took.as_secs() < 5, "the guard took {took:?} — that is a hang with extra steps");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The budget is per call, so the runaway script loses its own frame and the next one still
    /// runs — the same isolation the error handling already gives a script that throws.
    #[test]
    fn a_runaway_script_does_not_spend_another_scripts_budget() {
        let dir = std::env::temp_dir().join(format!("gizmo_budget2_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // `a_` sorts before `b_`, and the script map is ordered by path, so the runaway runs first.
        let runaway = dir.join("a_runaway.lua");
        let neighbour = dir.join("b_neighbour.lua");
        std::fs::write(&runaway, "function on_update(ctx)\n  while true do end\nend\n").unwrap();
        // Observable through the log queue rather than a new accessor: `print` already routes
        // into it, so the test needs no API the engine would not otherwise have.
        std::fs::write(&neighbour, "function on_update(ctx)\n  print('neighbour ran')\nend\n")
            .unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        engine.set_instruction_budget(200_000);
        engine.load_script(runaway.to_str().unwrap()).unwrap();
        engine.load_script(neighbour.to_str().unwrap()).unwrap();

        let world = World::new();
        let input = Input::default();
        let err = engine.update(&world, &input, 0.016).unwrap_err();
        assert!(err.contains("instruction budget"), "unexpected error: {err}");

        let logged = engine
            .log_queue
            .lock()
            .unwrap()
            .iter()
            .any(|(_, m)| m.contains("neighbour ran"));
        assert!(logged, "the second script never got its turn");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A script that allocates without bound hits a Lua error, not the OOM killer.
    #[test]
    fn runaway_allocation_fails_as_a_lua_error() {
        let dir = std::env::temp_dir().join(format!("gizmo_mem_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("hungry.lua");
        std::fs::write(
            &path,
            "function on_update(ctx)\n  local t = {}\n  while true do t[#t+1] = string.rep('x', 1024) end\nend\n",
        )
        .unwrap();

        let mut engine = ScriptEngine::new().unwrap();
        engine.set_memory_limit(4 * 1024 * 1024).unwrap();
        // Generous, so the memory ceiling is what stops it rather than the instruction budget.
        engine.set_instruction_budget(500_000_000);
        engine.load_script(path.to_str().unwrap()).unwrap();

        let err = engine.update(&World::new(), &Input::default(), 0.016).unwrap_err();
        assert!(
            err.to_lowercase().contains("memory"),
            "expected a memory error, got: {err}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }
    use super::*;
    use gizmo_math::{Quat, Vec3};
    use gizmo_physics_core::{Collider, ColliderShape, Transform};
    use gizmo_physics_rigid::components::{RigidBody, Velocity};

    /// Paralel test koşumlarında çakışmayan benzersiz geçici script yolu üretir.
    fn unique_temp(tag: &str) -> String {
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir()
            .join(format!("gizmo_scripting_{tag}_{n}_{nanos}.lua"))
            .to_string_lossy()
            .into_owned()
    }

    /// A top-level `on_update` in a loaded script must fire every frame. It's written
    /// into the script's isolated env, so the old code that read `on_update` from
    /// `_G` never found it and the hook was a silent no-op.
    #[test]
    fn on_update_hook_fires_from_script_env() {
        let mut engine = ScriptEngine::new().unwrap();
        let world = World::new();
        let input = gizmo_core::input::Input::default();

        let path = std::env::temp_dir()
            .join("gizmo_on_update_test.lua")
            .to_string_lossy()
            .into_owned();
        std::fs::write(&path, "function on_update(ctx)\n  entity.spawn(\"bullet\", 0, 0, 0)\nend\n")
            .unwrap();
        engine.load_script(&path).expect("load_script");

        let before = engine.command_queue().len();
        engine.update(&world, &input, 1.0 / 60.0).expect("update");
        let after = engine.command_queue().len();
        let _ = std::fs::remove_file(&path);

        assert!(
            after > before,
            "on_update must run and queue a spawn command (before={before}, after={after})"
        );
    }

    /// Regression: RigidBody var ama Velocity yoksa ApplyForce sessizce
    /// kaybolmamalı; Velocity oluşturulup ivme uygulanmalı.
    #[test]
    fn apply_force_creates_velocity_when_missing() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();

        let entity = world.spawn();
        world.add_component(entity, RigidBody::new(2.0, false));
        // Kasıtlı olarak Velocity EKLENMEDİ.
        assert!(world.borrow::<Velocity>().get(entity.id()).is_none());

        engine
            .command_queue()
            .push(ScriptCommand::ApplyForce(entity.id(), Vec3::new(4.0, 0.0, 0.0)));

        let dt = 0.5_f32;
        engine.flush_commands(&mut world, dt);

        let vels = world.borrow::<Velocity>();
        let v = vels
            .get(entity.id())
            .expect("Velocity ApplyForce tarafından oluşturulmalıydı");
        // accel = force/mass = 4/2 = 2; dv = accel*dt = 2*0.5 = 1.0
        assert!((v.linear.x - 1.0).abs() < 1e-5, "x hızı yanlış: {}", v.linear.x);
    }

    /// Regression: RigidBody var ama Velocity yoksa ApplyImpulse sessizce
    /// kaybolmamalı; Velocity oluşturulup delta-v uygulanmalı.
    #[test]
    fn apply_impulse_creates_velocity_when_missing() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();

        let entity = world.spawn();
        world.add_component(entity, RigidBody::new(2.0, false));
        assert!(world.borrow::<Velocity>().get(entity.id()).is_none());

        engine
            .command_queue()
            .push(ScriptCommand::ApplyImpulse(entity.id(), Vec3::new(6.0, 0.0, 0.0)));

        engine.flush_commands(&mut world, 0.016);

        let vels = world.borrow::<Velocity>();
        let v = vels
            .get(entity.id())
            .expect("Velocity ApplyImpulse tarafından oluşturulmalıydı");
        // dv = impulse/mass = 6/2 = 3.0 (dt'den bağımsız)
        assert!((v.linear.x - 3.0).abs() < 1e-5, "x hızı yanlış: {}", v.linear.x);
    }

    /// Transform yazma komutları (SetPosition/SetScale/SetRotation) mevcut bir
    /// Transform'a uygulanmalı.
    #[test]
    fn transform_commands_apply_to_component() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        world.add_component(e, Transform::new(Vec3::ZERO));
        let id = e.id();

        engine.command_queue().push(ScriptCommand::SetPosition(id, Vec3::new(1.0, 2.0, 3.0)));
        engine.command_queue().push(ScriptCommand::SetScale(id, Vec3::new(2.0, 4.0, 8.0)));
        engine.command_queue().push(ScriptCommand::SetRotation(id, Quat::from_xyzw(1.0, 0.0, 0.0, 0.0)));
        engine.flush_commands(&mut world, 0.016);

        let transforms = world.borrow::<Transform>();
        let t = transforms.get(id).unwrap();
        assert_eq!(t.position, Vec3::new(1.0, 2.0, 3.0));
        assert_eq!(t.scale, Vec3::new(2.0, 4.0, 8.0));
        assert!((t.rotation.x - 1.0).abs() < 1e-6 && t.rotation.w.abs() < 1e-6);
    }

    /// SetVelocity/SetAngularVelocity mevcut Velocity'nin linear/angular alanlarını ayarlamalı.
    #[test]
    fn velocity_commands_apply_to_component() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        world.add_component(e, Velocity::new(Vec3::ZERO));
        let id = e.id();

        engine.command_queue().push(ScriptCommand::SetVelocity(id, Vec3::new(3.0, 0.0, -2.0)));
        engine.command_queue().push(ScriptCommand::SetAngularVelocity(id, Vec3::new(0.0, 1.0, 0.0)));
        engine.flush_commands(&mut world, 0.016);

        let vels = world.borrow::<Velocity>();
        let v = vels.get(id).unwrap();
        assert_eq!(v.linear, Vec3::new(3.0, 0.0, -2.0));
        assert_eq!(v.angular, Vec3::new(0.0, 1.0, 0.0));
    }

    /// Kütlesi sıfır (statik) bir gövdeye kuvvet uygulanınca Velocity OLUŞTURULMAMALI —
    /// `mass > 0.0` koruması sonsuz ivmeyi engeller.
    #[test]
    fn apply_force_on_zero_mass_creates_no_velocity() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        world.add_component(e, RigidBody::new(0.0, false));
        let id = e.id();

        engine.command_queue().push(ScriptCommand::ApplyForce(id, Vec3::new(100.0, 0.0, 0.0)));
        engine.flush_commands(&mut world, 0.016);

        assert!(
            world.borrow::<Velocity>().get(id).is_none(),
            "sıfır kütle için Velocity oluşturulmamalı"
        );
    }

    /// Aynı flush içinde birden çok kuvvet birikimli (superposition) uygulanmalı.
    #[test]
    fn multiple_forces_accumulate_in_one_flush() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        world.add_component(e, RigidBody::new(2.0, false));
        world.add_component(e, Velocity::new(Vec3::ZERO));
        let id = e.id();

        engine.command_queue().push(ScriptCommand::ApplyForce(id, Vec3::new(4.0, 0.0, 0.0)));
        engine.command_queue().push(ScriptCommand::ApplyForce(id, Vec3::new(0.0, 6.0, 0.0)));
        engine.flush_commands(&mut world, 0.5);

        let vels = world.borrow::<Velocity>();
        let v = vels.get(id).unwrap();
        // dv = (F/m)*dt : x = 4/2*0.5 = 1.0 ; y = 6/2*0.5 = 1.5
        assert!((v.linear.x - 1.0).abs() < 1e-5, "x: {}", v.linear.x);
        assert!((v.linear.y - 1.5).abs() < 1e-5, "y: {}", v.linear.y);
    }

    /// AddRigidBody hareket edebilmesi için beraberinde bir Velocity de oluşturmalı.
    #[test]
    fn add_rigidbody_also_creates_velocity() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        let id = e.id();

        engine.command_queue().push(ScriptCommand::AddRigidBody { id, mass: 3.0, use_gravity: true });
        engine.flush_commands(&mut world, 0.016);

        let rbs = world.borrow::<RigidBody>();
        assert!((rbs.get(id).unwrap().mass - 3.0).abs() < 1e-6);
        drop(rbs);
        assert!(
            world.borrow::<Velocity>().get(id).is_some(),
            "AddRigidBody Velocity de eklemeli"
        );
    }

    /// AddBoxCollider/AddSphereCollider doğru şekilli Collider bileşenleri oluşturmalı.
    #[test]
    fn colliders_are_created_with_correct_shape() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e_box = world.spawn();
        let e_sphere = world.spawn();
        let (bid, sid) = (e_box.id(), e_sphere.id());

        engine.command_queue().push(ScriptCommand::AddBoxCollider { id: bid, hx: 1.0, hy: 2.0, hz: 3.0 });
        engine.command_queue().push(ScriptCommand::AddSphereCollider { id: sid, radius: 4.0 });
        engine.flush_commands(&mut world, 0.016);

        let cols = world.borrow::<Collider>();
        match &cols.get(bid).unwrap().shape {
            ColliderShape::Box(b) => assert_eq!(b.half_extents, Vec3::new(1.0, 2.0, 3.0)),
            other => panic!("beklenen Box, gelen {other:?}"),
        }
        match &cols.get(sid).unwrap().shape {
            ColliderShape::Sphere(s) => assert!((s.radius - 4.0).abs() < 1e-6),
            other => panic!("beklenen Sphere, gelen {other:?}"),
        }
    }

    /// SpawnEntity: isimli, Transform'lu bir entity oluşturmalı ve log kuyruğuna kayıt düşmeli.
    #[test]
    fn spawn_entity_creates_named_transform_and_logs() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();

        let logs_before = engine.log_queue.lock().unwrap().len();
        engine
            .command_queue()
            .push(ScriptCommand::SpawnEntity { name: "hero".into(), position: Vec3::new(5.0, 6.0, 7.0) });
        engine.flush_commands(&mut world, 0.016);

        // İsimli entity'yi bul.
        let names = world.borrow::<gizmo_core::EntityName>();
        let found = names.iter().filter_map(|(eid, _)| names.get(eid).map(|n| (eid, n.0.clone())))
            .find(|(_, name)| name == "hero");
        let (eid, _) = found.expect("'hero' isimli entity oluşmalıydı");
        drop(names);

        let transforms = world.borrow::<Transform>();
        assert_eq!(transforms.get(eid).unwrap().position, Vec3::new(5.0, 6.0, 7.0));
        drop(transforms);

        assert!(
            engine.log_queue.lock().unwrap().len() > logs_before,
            "spawn log kuyruğuna kayıt düşmeliydi"
        );
    }

    /// DestroyEntity var olan bir entity'yi despawn etmeli (artık canlı olmamalı).
    #[test]
    fn destroy_entity_removes_it() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        let id = e.id();
        assert!(world.entity(id).is_some());

        engine.command_queue().push(ScriptCommand::DestroyEntity(id));
        engine.flush_commands(&mut world, 0.016);

        assert!(world.entity(id).is_none(), "entity despawn edilmeliydi");
    }

    /// SetEntityName mevcut EntityName'i yeniden adlandırmalı.
    #[test]
    fn set_entity_name_renames() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        world.add_component(e, gizmo_core::EntityName::new("old"));
        let id = e.id();

        engine.command_queue().push(ScriptCommand::SetEntityName(id, "new".into()));
        engine.flush_commands(&mut world, 0.016);

        let names = world.borrow::<gizmo_core::EntityName>();
        assert_eq!(names.get(id).unwrap().0, "new");
    }

    /// AddNavAgent + SetAiTarget hedefi ayarlamalı; ClearAiTarget hedefi (yalnız yolu değil) temizlemeli.
    #[test]
    fn nav_agent_target_set_then_cleared() {
        use gizmo_ai::components::NavAgent;
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        let e = world.spawn();
        let id = e.id();

        engine.command_queue().push(ScriptCommand::AddNavAgent(id));
        engine.command_queue().push(ScriptCommand::SetAiTarget(id, Vec3::new(9.0, 0.0, 0.0)));
        engine.flush_commands(&mut world, 0.016);
        {
            let agents = world.borrow::<NavAgent>();
            assert_eq!(agents.get(id).unwrap().target, Some(Vec3::new(9.0, 0.0, 0.0)));
        }

        engine.command_queue().push(ScriptCommand::ClearAiTarget(id));
        engine.flush_commands(&mut world, 0.016);
        {
            let agents = world.borrow::<NavAgent>();
            assert_eq!(agents.get(id).unwrap().target, None, "hedef temizlenmeliydi");
        }
    }

    /// Uygulanmayan her komut çağırana geri döndürülmeli — sessizce yutulmamalı.
    ///
    /// **Bu test eskiden kusuru sabitliyordu.** Adı `..._but_consumes_savescene_and_vehicle` idi ve
    /// `SaveScene` ile araç komutlarının *dönmemesini* iddia ediyordu. Oysa onları yutan kol,
    /// yorumunda "bunlar zaten unhandled'a düşecek" diyordu — düşemezlerdi, çünkü kolun kendisi
    /// onları tüketiyordu. Lua tarafında canlı fonksiyonları olan bir komutun hiçbir iz bırakmadan
    /// kaybolması, bir script yazarının teşhis edemeyeceği tek şeydir. Artık iddia niyet: bu crate
    /// uygulayamadığı komutu ev sahibine verir.
    #[test]
    fn flush_returns_everything_it_cannot_apply_itself() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();

        let cq = engine.command_queue();
        cq.push(ScriptCommand::PlaySound("boom".into()));
        cq.push(ScriptCommand::PlaySound3D("bird".into(), Vec3::ZERO));
        cq.push(ScriptCommand::StopSound("music".into()));
        cq.push(ScriptCommand::LoadScene("level.scene".into()));
        cq.push(ScriptCommand::SaveScene("slot.scene".into()));
        cq.push(ScriptCommand::SetVehicleBrake(1, 500.0));

        let unhandled = engine.flush_commands(&mut world, 0.016);

        assert_eq!(unhandled.len(), 6, "ses(3) + LoadScene + SaveScene + araç(1) — hepsi dönmeli");
        assert!(unhandled.iter().any(|c| matches!(c, ScriptCommand::PlaySound(n) if n == "boom")));
        assert!(unhandled.iter().any(|c| matches!(c, ScriptCommand::PlaySound3D(n, _) if n == "bird")));
        assert!(unhandled.iter().any(|c| matches!(c, ScriptCommand::StopSound(n) if n == "music")));
        assert!(unhandled.iter().any(|c| matches!(c, ScriptCommand::LoadScene(n) if n == "level.scene")));
        assert!(
            unhandled.iter().any(|c| matches!(c, ScriptCommand::SaveScene(n) if n == "slot.scene")),
            "SaveScene sessizce yutulmamalı"
        );
        assert!(
            unhandled.iter().any(|c| matches!(c, ScriptCommand::SetVehicleBrake(1, _))),
            "araç komutları sessizce yutulmamalı — bu crate onları uygulayamıyor, ev sahibi uygular"
        );
    }

    /// Scriptler her koşuda aynı sırada çalışmalı.
    ///
    /// `loaded_scripts` bir `std::collections::HashMap` idi, ve `RandomState` proses başına
    /// tohumlanır — yani `update`'in scriptleri çalıştırma sırası koşudan koşuya değişiyordu. Aynı
    /// varlığa dokunan iki script çeliştiğinde sonucu ekleme sırası belirler, ve bu motorun manşet
    /// sözleşmesi aynı-platform bit-birebir tekrar oynatma. Sıra artık scriptlerin yollarının bir
    /// özelliği, ayırıcının değil.
    #[test]
    fn scripts_run_in_a_stable_order() {
        let mut engine = ScriptEngine::new().unwrap();
        let dir = std::env::temp_dir();
        // Loaded in an order that is not the sorted one, so a map that preserved insertion order
        // would also fail this.
        let mut written = Vec::new();
        for stem in ["zebra", "alpha", "midori", "beta"] {
            let path = dir
                .join(format!("gizmo_order_{stem}.lua"))
                .to_string_lossy()
                .into_owned();
            std::fs::write(&path, "function on_update(ctx) end\n").unwrap();
            engine.load_script(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
            written.push(path);
        }

        let order: Vec<String> = engine.loaded_scripts.keys().cloned().collect();
        let mut sorted = order.clone();
        sorted.sort();
        assert_eq!(
            order, sorted,
            "çalışma sırası yola göre sabit olmalı — bir HashMap'te bu proses başına değişirdi"
        );

        for path in written {
            let _ = std::fs::remove_file(path);
        }
    }

    /// flush_commands kuyruğu tüketmeli (drain): çağrı sonrası kuyruk boş olmalı.
    #[test]
    fn flush_drains_the_queue() {
        let engine = ScriptEngine::new().unwrap();
        let mut world = World::new();
        engine.command_queue().push(ScriptCommand::StartRace);
        engine.command_queue().push(ScriptCommand::HideDialogue);
        assert_eq!(engine.command_queue().len(), 2);

        engine.flush_commands(&mut world, 0.016);
        assert!(engine.command_queue().is_empty(), "flush kuyruğu boşaltmalı");
    }

    /// Script::new her zaman initialized=false ile başlar (on_init henüz çağrılmadı).
    #[test]
    fn script_new_starts_uninitialized() {
        let s = Script::new("scripts/player.lua");
        assert_eq!(s.file_path, "scripts/player.lua");
        assert!(!s.initialized);
    }

    /// Script serde round-trip: `initialized` alanı `#[serde(default, skip)]` olduğundan
    /// serileştirmede yer almaz ve deserialize sonrası daima false olur — böylece sahne
    /// yüklendiğinde on_init yeniden çalışır. file_path korunmalı.
    /// A script's `properties = { … }` declaration is what the editor lists.
    ///
    /// Read back out of the script's own environment, which is where a bare assignment lands.
    /// Non-scalar entries are dropped rather than guessed at: a nested table is the script's own
    /// business and has no inspector row.
    #[test]
    fn declared_properties_are_read_from_the_script() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("declared_props");
        std::fs::write(
            &path,
            r#"
properties = {
    open_speed = 2.4,
    locked = false,
    label = "gate",
    nested = { nope = 1 },
}
"#,
        )
        .unwrap();
        engine.load_script(&path).unwrap();

        let declared = engine.declared_properties(&path);
        assert_eq!(declared.get("open_speed"), Some(&ScriptValue::Num(2.4)));
        assert_eq!(declared.get("locked"), Some(&ScriptValue::Bool(false)));
        assert_eq!(declared.get("label"), Some(&ScriptValue::Text("gate".into())));
        assert!(
            !declared.contains_key("nested"),
            "a table is not an inspector row and must not be guessed at"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// A script with no declaration yields nothing, rather than erroring.
    #[test]
    fn a_script_without_properties_declares_none() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("no_props");
        std::fs::write(&path, "function on_entity_update(id, dt, props) end\n").unwrap();
        engine.load_script(&path).unwrap();
        assert!(engine.declared_properties(&path).is_empty());
        let _ = std::fs::remove_file(&path);
    }

    /// The per-entity values reach the script, and two entities running the same file see their
    /// own.
    ///
    /// This is the whole reason the values live on the component: scripts are loaded per PATH, so
    /// both entities below share one Lua environment. If the properties lived in that environment
    /// the second call would overwrite the first.
    #[test]
    fn each_entity_sees_its_own_property_values() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("per_entity_props");
        std::fs::write(
            &path,
            r#"
seen = {}
function on_entity_update(id, dt, props)
    seen[id] = props.open_speed
end
"#,
        )
        .unwrap();
        engine.load_script(&path).unwrap();

        let mut a = std::collections::BTreeMap::new();
        a.insert("open_speed".to_string(), ScriptValue::Num(1.5));
        let mut b = std::collections::BTreeMap::new();
        b.insert("open_speed".to_string(), ScriptValue::Num(9.25));

        engine.update_entity(1, &path, 0.016, &a).unwrap();
        engine.update_entity(2, &path, 0.016, &b).unwrap();

        let seen_1 = engine.eval_number(&path, "seen[1]").expect("entity 1 value");
        let seen_2 = engine.eval_number(&path, "seen[2]").expect("entity 2 value");
        assert_eq!(seen_1, 1.5);
        assert_eq!(
            seen_2, 9.25,
            "the second entity saw the first one's value — the properties are being shared"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// **Every** stored value reaches the script — declared or not, right type or not.
    ///
    /// `update_entity` takes the component's whole `properties` map and the studio hands it
    /// `script.properties.clone()`, so nothing between the scene file and Lua filters it. That is
    /// the contract, and it is a reasonable one — a scene may carry per-entity data a script reads
    /// without declaring.
    ///
    /// It is pinned here because the editor once claimed the opposite. `ScriptValue::kind`'s note
    /// said an override whose kind differs from the declaration "is ignored rather than coerced",
    /// and the inspector duly filtered such an override out of its *display* — while the script
    /// went on receiving it. The inspector showed the declared default and the script ran on the
    /// stale value. Whatever the editor draws has to agree with this test, not the other way
    /// round.
    #[test]
    fn every_stored_property_reaches_the_script_declared_or_not() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("undeclared_props");
        std::fs::write(
            &path,
            r#"
properties = { open_speed = 2.4, locked = false }
seen_speed = nil
seen_locked_is_string = nil
seen_undeclared = nil
function on_entity_update(id, dt, props)
    seen_speed = props.open_speed
    seen_locked_is_string = (type(props.locked) == "string") and 1 or 0
    seen_undeclared = props.nobody_declared_me
end
"#,
        )
        .unwrap();
        engine.load_script(&path).unwrap();

        // The declaration says `locked` is a bool and knows nothing about `nobody_declared_me`.
        let declared = engine.declared_properties(&path);
        assert_eq!(declared.get("locked").map(|v| v.kind()), Some("bool"));
        assert!(!declared.contains_key("nobody_declared_me"));

        let mut stored = std::collections::BTreeMap::new();
        stored.insert("open_speed".to_string(), ScriptValue::Num(7.5));
        // A stale override: the script now declares this as a bool.
        stored.insert("locked".to_string(), ScriptValue::Text("yes".to_string()));
        // And a key the script never declared at all.
        stored.insert("nobody_declared_me".to_string(), ScriptValue::Num(42.0));

        engine.update_entity(1, &path, 0.016, &stored).unwrap();

        assert_eq!(engine.eval_number(&path, "seen_speed"), Some(7.5));
        assert_eq!(
            engine.eval_number(&path, "seen_locked_is_string"),
            Some(1.0),
            "the type-mismatched override is handed to the script verbatim — it is NOT ignored"
        );
        assert_eq!(
            engine.eval_number(&path, "seen_undeclared"),
            Some(42.0),
            "an undeclared key reaches the script too, so the editor must not pretend it is absent"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn script_serde_roundtrip_resets_initialized() {
        let mut s = Script::new("a.lua");
        s.initialized = true;

        let json = serde_json::to_string(&s).unwrap();
        assert!(!json.contains("initialized"), "skip'li alan JSON'da olmamalı: {json}");

        let back: Script = serde_json::from_str(&json).unwrap();
        assert_eq!(back.file_path, "a.lua");
        assert!(!back.initialized, "deserialize sonrası initialized=false olmalı");
    }

    /// Güvenlik: motor tehlikeli global'leri (os/io/require/dofile/loadfile/package/
    /// debug/load/loadstring) devre dışı bırakmalı.
    #[test]
    fn sandbox_disables_dangerous_globals() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("sandbox");
        std::fs::write(
            &path,
            r#"
            assert(os == nil, "os kapatılmalı")
            assert(io == nil, "io kapatılmalı")
            assert(require == nil, "require kapatılmalı")
            assert(dofile == nil, "dofile kapatılmalı")
            assert(loadfile == nil, "loadfile kapatılmalı")
            assert(package == nil, "package kapatılmalı")
            assert(debug == nil, "debug kapatılmalı")
            assert(load == nil, "load kapatılmalı")
            assert(loadstring == nil, "loadstring kapatılmalı")
            "#,
        )
        .unwrap();
        let res = engine.load_script(&path);
        let _ = std::fs::remove_file(&path);
        res.expect("sandbox assert'leri geçmeli (global'ler nil olmalı)");
    }

    /// Motorun kaydettiği Lua matematik yardımcıları (vec3_*, clamp, lerp) doğru çalışmalı.
    #[test]
    fn lua_math_helpers_are_correct() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("mathhelpers");
        std::fs::write(
            &path,
            r#"
            assert(math.abs(vec3_length(vec3(3,4,0)) - 5.0) < 1e-5, "length 3-4-5")
            local c = vec3_cross(vec3(1,0,0), vec3(0,1,0))
            assert(c.x == 0 and c.y == 0 and c.z == 1, "x cross y = z")
            assert(clamp(5, 0, 3) == 3, "clamp üst sınır")
            assert(clamp(-1, 0, 3) == 0, "clamp alt sınır")
            assert(clamp(2, 0, 3) == 2, "clamp aralık içi")
            assert(lerp(0, 10, 0.5) == 5, "lerp orta")
            local n = vec3_normalize(vec3(0,0,0))
            assert(n.x == 0 and n.y == 0 and n.z == 0, "sıfır vektör normalize => sıfır")
            assert(math.abs(vec3_distance(vec3(0,0,0), vec3(0,3,4)) - 5.0) < 1e-5, "distance")
            local d = vec3_dot(vec3(1,2,3), vec3(4,5,6))
            assert(d == 32, "dot 1*4+2*5+3*6=32")
            "#,
        )
        .unwrap();
        let res = engine.load_script(&path);
        let _ = std::fs::remove_file(&path);
        res.expect("matematik yardımcı assert'leri geçmeli");
    }

    /// Hata yolu: var olmayan bir script yüklenince açıklayıcı bir hata dönmeli (panik değil).
    #[test]
    fn load_missing_file_returns_error() {
        let mut engine = ScriptEngine::new().unwrap();
        let err = engine
            .load_script("/nonexistent/gizmo/definitely_missing_5f2a.lua")
            .unwrap_err();
        assert!(err.contains("okunamadı"), "okuma hatası mesajı beklenir, gelen: {err}");
    }

    /// Hata yolu: yüklenmemiş bir script için run_entity_update 'not loaded' hatası vermeli.
    #[test]
    fn run_entity_update_on_unloaded_script_errors() {
        let mut engine = ScriptEngine::new().unwrap();
        let ctx = ScriptContext::default();
        let err = engine
            .run_entity_update("never_loaded.lua", "on_entity_update", &ctx)
            .unwrap_err();
        assert!(err.contains("not loaded"), "mesaj: {err}");
    }

    /// run_entity_update ctx'i (pozisyon + dt) Lua'ya geçirmeli ve dönen position tablosunu
    /// ScriptResult.new_position olarak çıkarmalı. Var olmayan fonksiyon default döndürmeli.
    #[test]
    fn run_entity_update_marshals_position_and_extracts_result() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("marshal_pos");
        std::fs::write(
            &path,
            "function mv(ctx)\n  return { position = { x = ctx.position.x + ctx.dt, y = ctx.position.y, z = ctx.position.z } }\nend\n",
        )
        .unwrap();
        engine.load_script(&path).unwrap();

        let ctx = ScriptContext {
            entity_id: 42,
            dt: 0.5,
            position: [10.0, -1.0, 2.0],
            ..Default::default()
        };

        let result = engine.run_entity_update(&path, "mv", &ctx).unwrap();
        assert_eq!(result.new_position, Some([10.5, -1.0, 2.0]));
        assert_eq!(result.new_velocity, None, "script velocity döndürmedi");

        // Var olmayan fonksiyon → default (her ikisi None).
        let empty = engine.run_entity_update(&path, "yok_boyle_fn", &ctx).unwrap();
        assert_eq!(empty.new_position, None);
        assert_eq!(empty.new_velocity, None);

        let _ = std::fs::remove_file(&path);
    }

    /// run_entity_update girdi (input) bayraklarını Lua ctx.input'a geçirmeli; script
    /// bunlara göre velocity döndürebilmeli.
    #[test]
    fn run_entity_update_marshals_input_flags() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("marshal_input");
        std::fs::write(
            &path,
            "function ctl(ctx)\n  local vx = 0\n  if ctx.input.d then vx = 1 end\n  if ctx.input.a then vx = vx - 1 end\n  return { velocity = { x = vx, y = 0, z = 0 } }\nend\n",
        )
        .unwrap();
        engine.load_script(&path).unwrap();

        let mut ctx = ScriptContext {
            key_d: true, // sağa
            ..Default::default()
        };
        let r = engine.run_entity_update(&path, "ctl", &ctx).unwrap();
        assert_eq!(r.new_velocity, Some([1.0, 0.0, 0.0]));

        ctx.key_d = false;
        ctx.key_a = true; // sola
        let r2 = engine.run_entity_update(&path, "ctl", &ctx).unwrap();
        assert_eq!(r2.new_velocity, Some([-1.0, 0.0, 0.0]));

        let _ = std::fs::remove_file(&path);
    }

    /// has_function yalnız yüklü script'te tanımlı fonksiyonlar için true dönmeli.
    #[test]
    fn has_function_detects_defined_and_missing() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("hasfn");
        std::fs::write(&path, "function on_update(ctx) end\n").unwrap();
        engine.load_script(&path).unwrap();

        assert!(engine.has_function(&path, "on_update"));
        assert!(!engine.has_function(&path, "on_missing"));
        assert!(!engine.has_function("unloaded.lua", "on_update"));

        let _ = std::fs::remove_file(&path);
    }

    /// reload_if_changed: içerik değişmediyse false (yeniden yükleme yok), değişince true;
    /// sonra tekrar değişmezse yine false — hot-reload durum makinesi.
    #[test]
    fn reload_if_changed_detects_content_change() {
        let mut engine = ScriptEngine::new().unwrap();
        let path = unique_temp("reload");
        std::fs::write(&path, "function on_update(ctx) end\n").unwrap();
        engine.load_script(&path).unwrap();

        assert!(!engine.reload_if_changed(&path).unwrap(), "değişmemişken false");

        std::fs::write(&path, "function on_update(ctx) end\n-- değişti\n").unwrap();
        assert!(engine.reload_if_changed(&path).unwrap(), "değişince true");

        assert!(!engine.reload_if_changed(&path).unwrap(), "tekrar değişmemişken false");

        let _ = std::fs::remove_file(&path);
    }
}