carla 0.14.1

Rust client library for Carla simulator
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
use super::{
    Actor, ActorBase, ActorBlueprint, ActorBuilder, ActorList, ActorVec, BlueprintLibrary,
    BoundingBoxList, DebugHelper, EnvironmentObjectList, LabelledPointList, Landmark, LightManager,
    Map, Waypoint, WorldSnapshot,
};
#[cfg(carla_0100)]
use crate::rpc::{MaterialParameter, TextureColor, TextureFloatColor};
use crate::{
    error::{OperationError, Result, ffi::with_ffi_error},
    geom::{Location, Transform, Vector3D},
    road::JuncId,
    rpc::{
        ActorId, AttachmentType, EpisodeSettings, LabelledPoint, MapLayer, VehicleLightStateList,
        WeatherParameters,
    },
    utils::CxxVectorExt,
};
use autocxx::prelude::*;
use carla_sys::carla_rust::{
    client::{FfiActor, FfiWorld, FfiWorldSnapshot},
    geom::FfiVector3D,
};
use cxx::{CxxVector, UniquePtr, let_cxx_string};
use derivative::Derivative;
use static_assertions::assert_impl_all;
use std::{mem, ptr, time::Duration};

use autocxx::c_void;

const DEFAULT_TICK_TIMEOUT: Duration = Duration::from_secs(60);

/// The world contains the map and assets of a simulation.
///
/// [`World`] is the main interface for interacting with the simulation. It provides:
/// - Access to the simulation [`Map`] and environment
/// - Actor spawning and management
/// - Weather and lighting control
/// - Simulation settings (synchronous mode, fixed time step, etc.)
/// - Traffic light management
/// - World snapshots for state inspection
///
/// Corresponds to [`carla.World`] in the Python API.
#[cfg_attr(carla_version_0916, doc = "")]
#[cfg_attr(
    carla_version_0916,
    doc = " [`carla.World`]: https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World"
)]
#[cfg_attr(carla_version_0915, doc = "")]
#[cfg_attr(
    carla_version_0915,
    doc = " [`carla.World`]: https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World"
)]
#[cfg_attr(carla_version_0914, doc = "")]
#[cfg_attr(
    carla_version_0914,
    doc = " [`carla.World`]: https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World"
)]
///
/// # Thread Safety
///
/// [`World`] implements [`Send`] and [`Sync`] and can be cloned cheaply (internally
/// reference-counted).
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use carla::client::Client;
///
/// let client = Client::connect("localhost", 2000, None)?;
/// let mut world = client.world()?;
///
/// // Get simulation info
/// println!("World ID: {}", world.id()?);
/// let map = world.map()?;
/// println!("Map: {}", map.name());
///
/// // Spawn an actor
/// let bp_lib = world.blueprint_library()?;
/// let vehicle_bp = bp_lib.filter("vehicle.tesla.model3").get(0).unwrap();
/// let spawn_points = map.recommended_spawn_points();
/// if let Some(spawn_point) = spawn_points.get(0) {
///     let actor = world.spawn_actor(&vehicle_bp, &spawn_point)?;
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Derivative)]
#[derivative(Debug)]
#[repr(transparent)]
pub struct World {
    #[derivative(Debug = "ignore")]
    pub(crate) inner: UniquePtr<FfiWorld>,
}

impl World {
    /// Returns the unique ID of this world/episode.
    ///
    /// The ID changes whenever the world is reloaded or a new map is loaded.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.id](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.id)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.id](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.id)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.id](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.id)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn id(&self) -> Result<u64> {
        with_ffi_error("World::id", |e| self.inner.GetId(e))
    }

    /// Returns the map associated with this world.
    ///
    /// The map contains the road network, spawn points, and navigation information.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_map](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_map)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_map](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_map)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_map](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_map)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn map(&self) -> crate::Result<Map> {
        let ptr = with_ffi_error("map", |e| self.inner.GetMap(e))?;
        Ok(unsafe { Map::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns the light manager for controlling street lights and vehicle lights.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_lightmanager](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_lightmanager)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_lightmanager](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_lightmanager)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_lightmanager](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_lightmanager)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn light_manager(&self) -> crate::Result<LightManager> {
        let ptr = with_ffi_error("light_manager", |e| self.inner.GetLightManager(e))?;
        Ok(unsafe { LightManager::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Loads a map layer (e.g., buildings, props, roads).
    ///
    /// Use this to dynamically load/unload parts of the map for performance.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.load_map_layer](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.load_map_layer)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.load_map_layer](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.load_map_layer)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.load_map_layer](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.load_map_layer)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn load_level_layer(&self, map_layers: MapLayer) -> crate::Result<()> {
        with_ffi_error("load_level_layer", |e| {
            self.inner.LoadLevelLayer(map_layers as u16, e)
        })
    }

    /// Unloads a map layer.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.unload_map_layer](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.unload_map_layer)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.unload_map_layer](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.unload_map_layer)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.unload_map_layer](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.unload_map_layer)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn unload_level_layer(&self, map_layers: MapLayer) -> crate::Result<()> {
        with_ffi_error("unload_level_layer", |e| {
            self.inner.UnloadLevelLayer(map_layers as u16, e)
        })
    }

    /// Returns the blueprint library containing all available actor blueprints.
    ///
    /// Blueprints are templates for spawning actors (vehicles, sensors, pedestrians, etc.).
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_blueprint_library](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_blueprint_library)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_blueprint_library](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_blueprint_library)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_blueprint_library](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_blueprint_library)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::client::Client;
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let world = client.world()?;
    /// let bp_lib = world.blueprint_library()?;
    ///
    /// // Find all vehicle blueprints
    /// let vehicles = bp_lib.filter("vehicle.*");
    /// println!("Found {} vehicle types", vehicles.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn blueprint_library(&self) -> crate::Result<BlueprintLibrary> {
        let ptr = with_ffi_error("blueprint_library", |e| self.inner.GetBlueprintLibrary(e))?;
        Ok(unsafe { BlueprintLibrary::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns the light state of all vehicles in the world.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_vehicles_light_states](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_vehicles_light_states)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_vehicles_light_states](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_vehicles_light_states)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_vehicles_light_states](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_vehicles_light_states)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn vehicle_light_states(&self) -> crate::Result<VehicleLightStateList> {
        let ptr = with_ffi_error("vehicle_light_states", |e| {
            self.inner.GetVehiclesLightStates(e)
        })?;
        Ok(unsafe { VehicleLightStateList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns a random navigable location (on roads/sidewalks).
    ///
    /// Useful for spawning actors at random valid positions.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_random_location_from_navigation](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_random_location_from_navigation)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_random_location_from_navigation](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_random_location_from_navigation)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_random_location_from_navigation](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_random_location_from_navigation)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn random_location_from_navigation(&self) -> crate::Result<Location> {
        let ptr = with_ffi_error("random_location_from_navigation", |e| {
            self.inner.GetRandomLocationFromNavigation(e)
        })?;
        Ok(Location::from_ffi(ptr.as_ref().unwrap().clone()))
    }

    /// Returns the spectator actor (the free-flying camera).
    ///
    /// Move the spectator to change the view in the CARLA window.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_spectator](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_spectator)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_spectator](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_spectator)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_spectator](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_spectator)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn spectator(&self) -> crate::Result<Actor> {
        let ptr = with_ffi_error("spectator", |e| self.inner.GetSpectator(e))?;
        Ok(unsafe { Actor::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns the current simulation settings.
    ///
    /// Settings include synchronous mode, fixed time step, rendering options, etc.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_settings](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_settings)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_settings](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_settings)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_settings](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_settings)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn settings(&self) -> crate::Result<EpisodeSettings> {
        let ptr = with_ffi_error("settings", |e| self.inner.GetSettings(e))?;
        Ok(EpisodeSettings::from_cxx(&ptr))
    }

    /// Returns a snapshot of the current world state.
    ///
    /// Snapshots contain actor transforms, velocities, and simulation timestamp.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_snapshot](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_snapshot)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_snapshot](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_snapshot)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_snapshot](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_snapshot)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn snapshot(&self) -> crate::Result<WorldSnapshot> {
        let ptr = with_ffi_error("snapshot", |e| self.inner.GetSnapshot(e))?;
        Ok(unsafe { WorldSnapshot::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns names of all environment objects in the world.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_names_of_all_objects](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_names_of_all_objects)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_names_of_all_objects](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_names_of_all_objects)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_names_of_all_objects](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_names_of_all_objects)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn names_of_all_objects(&self) -> crate::Result<Vec<String>> {
        let names = with_ffi_error("names_of_all_objects", |e| {
            self.inner.GetNamesOfAllObjects(e)
        })?;
        Ok(names.iter().map(|s| s.to_string()).collect())
    }

    /// Finds an actor by its ID.
    ///
    /// Returns `None` if the actor doesn't exist or has been destroyed.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_actor](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_actor)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_actor](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_actor)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_actor](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_actor)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn actor(&self, actor_id: ActorId) -> crate::Result<Option<Actor>> {
        let ptr = with_ffi_error("actor", |e| self.inner.GetActor(actor_id, e))?;
        Ok(Actor::from_cxx(ptr))
    }

    /// Returns a list of all actors currently in the world.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::client::Client;
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let world = client.world()?;
    /// let actors = world.actors()?;
    /// println!("Total actors: {}", actors.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn actors(&self) -> crate::Result<ActorList> {
        let ptr = with_ffi_error("actors", |e| self.inner.GetActors(e))?;
        Ok(unsafe { ActorList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns a list of actors matching the given IDs.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_actors](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_actors)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn actors_by_ids(&self, ids: &[ActorId]) -> crate::Result<ActorList> {
        let mut vec = CxxVector::new_typed();
        ids.iter().cloned().for_each(|id| {
            vec.pin_mut().push(id);
        });

        let ptr = with_ffi_error("actors_by_ids", |e| self.inner.GetActorsByIds(&vec, e))?;
        Ok(unsafe { ActorList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns traffic lights affecting a waypoint within a certain distance.
    ///
    /// # Arguments
    /// * `waypoint` - The waypoint to check from
    /// * `distance` - Maximum distance to search for traffic lights
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_traffic_lights_from_waypoint](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_traffic_lights_from_waypoint)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_traffic_lights_from_waypoint](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_traffic_lights_from_waypoint)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_traffic_lights_from_waypoint](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_traffic_lights_from_waypoint)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn traffic_lights_from_waypoint(
        &self,
        waypoint: &Waypoint,
        distance: f64,
    ) -> crate::Result<ActorVec> {
        let ptr = with_ffi_error("traffic_lights_from_waypoint", |e| {
            self.inner
                .GetTrafficLightsFromWaypoint(&waypoint.inner, distance, e)
        })?;
        Ok(unsafe { ActorVec::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns all traffic lights in a junction.
    ///
    /// # Arguments
    /// * `junc_id` - Junction ID to query
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_traffic_lights_in_junction](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_traffic_lights_in_junction)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_traffic_lights_in_junction](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_traffic_lights_in_junction)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_traffic_lights_in_junction](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_traffic_lights_in_junction)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn traffic_lights_in_junction(&self, junc_id: JuncId) -> crate::Result<ActorVec> {
        let ptr = with_ffi_error("traffic_lights_in_junction", |e| {
            self.inner.GetTrafficLightsInJunction(junc_id.into(), e)
        })?;
        Ok(unsafe { ActorVec::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Applies new simulation settings.
    ///
    /// Use this to change synchronous mode, time step, rendering options, etc.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.apply_settings](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.apply_settings)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.apply_settings](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.apply_settings)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.apply_settings](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.apply_settings)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Arguments
    ///
    /// * `settings` - The new settings to apply
    /// * `timeout` - Maximum time to wait for the operation
    ///
    /// # Returns
    ///
    /// The frame number when the settings were applied.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::client::Client;
    /// use std::time::Duration;
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let mut world = client.world()?;
    ///
    /// let mut settings = world.settings()?;
    /// settings.synchronous_mode = true;
    /// settings.fixed_delta_seconds = Some(0.05);
    /// world.apply_settings(&settings, Duration::from_secs(2))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn apply_settings(
        &mut self,
        settings: &EpisodeSettings,
        timeout: Duration,
    ) -> crate::Result<u64> {
        let ffi_settings = settings.to_cxx();
        let millis = timeout.as_millis() as usize;
        with_ffi_error("apply_settings", |e| {
            self.inner.pin_mut().ApplySettings(&ffi_settings, millis, e)
        })
    }

    /// Spawns an actor in the world.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.spawn_actor](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.spawn_actor)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.spawn_actor](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.spawn_actor)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.spawn_actor](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.spawn_actor)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Arguments
    ///
    /// * `blueprint` - The actor blueprint (from [`blueprint_library()`](Self::blueprint_library))
    /// * `transform` - Initial position and rotation
    ///
    /// # Returns
    ///
    /// The spawned [`Actor`], or an error if spawning failed (e.g., collision with
    /// another object).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::client::{ActorBase, Client};
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let mut world = client.world()?;
    ///
    /// let bp_lib = world.blueprint_library()?;
    /// let vehicle_bp = bp_lib.filter("vehicle.tesla.model3").get(0).unwrap();
    ///
    /// let spawn_points = world.map()?.recommended_spawn_points();
    /// if let Some(spawn_point) = spawn_points.get(0) {
    ///     match world.spawn_actor(&vehicle_bp, &spawn_point) {
    ///         Ok(actor) => println!("Spawned actor {}", actor.id()),
    ///         Err(e) => eprintln!("Failed to spawn: {}", e),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn spawn_actor(
        &mut self,
        blueprint: &ActorBlueprint,
        transform: &Transform,
    ) -> Result<Actor> {
        self.spawn_actor_opt::<Actor, _>(blueprint, transform, None, None)
    }

    /// Spawns an actor with optional parent attachment.
    ///
    /// **Important**: In synchronous mode, the actor's spawn is queued but not processed until
    /// the next tick. You must call [`wait_for_tick()`](Self::wait_for_tick) or [`tick()`](Self::tick)
    /// after spawning to ensure the actor is actually created in the simulation before querying
    /// its properties (position, etc.).
    ///
    /// # Arguments
    ///
    /// * `blueprint` - The actor blueprint
    /// * `transform` - Initial position and rotation (relative to parent if attached)
    /// * `parent` - Optional parent actor to attach to
    /// * `attachment_type` - How to attach to parent (Rigid, SpringArm, etc.)
    ///
    /// # Examples
    ///
    /// Attaching a camera to a vehicle:
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::{
    ///     client::Client,
    ///     geom::{Location, Rotation, Transform},
    ///     rpc::AttachmentType,
    /// };
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let mut world = client.world()?;
    /// # let bp_lib = world.blueprint_library()?;
    /// # let vehicle_bp = bp_lib.filter("vehicle.*").get(0).unwrap();
    /// # let spawn_points = world.map()?.recommended_spawn_points();
    /// # let vehicle_actor = world.spawn_actor(&vehicle_bp, &spawn_points.get(0).unwrap())?;
    /// # let vehicle: carla::client::Vehicle = vehicle_actor.try_into().unwrap();
    ///
    /// // Spawn camera attached to vehicle
    /// let camera_bp = bp_lib.filter("sensor.camera.rgb").get(0).unwrap();
    /// let camera_transform = Transform {
    ///     location: Location::new(0.0, 0.0, 2.0),
    ///     rotation: Rotation::default(),
    /// };
    ///
    /// let camera = world.spawn_actor_opt(
    ///     &camera_bp,
    ///     &camera_transform,
    ///     Some(&vehicle),
    ///     AttachmentType::Rigid,
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn spawn_actor_opt<A, T>(
        &mut self,
        blueprint: &ActorBlueprint,
        transform: &Transform,
        parent: Option<&A>,
        attachment_type: T,
    ) -> Result<Actor>
    where
        A: ActorBase,
        T: Into<Option<AttachmentType>>,
    {
        let parent = parent.map(|parent| parent.cxx_actor());
        let attachment_type = attachment_type.into().unwrap_or(AttachmentType::Rigid);

        unsafe {
            let parent_ptr: *mut FfiActor = parent
                .as_ref()
                .and_then(|parent| parent.as_ref())
                .map(|ref_| ref_ as *const _ as *mut _)
                .unwrap_or(ptr::null_mut());
            let ffi_transform = transform.clone();
            #[cfg(carla_version_0916)]
            let actor = {
                use cxx::let_cxx_string;
                let_cxx_string!(socket_name = "");
                with_ffi_error("World::try_spawn_actor", |e| {
                    self.inner.pin_mut().TrySpawnActor(
                        &blueprint.inner,
                        ffi_transform.as_ffi(),
                        parent_ptr,
                        attachment_type,
                        &socket_name,
                        e,
                    )
                })?
            };
            #[cfg(not(carla_version_0916))]
            let actor = with_ffi_error("World::try_spawn_actor", |e| {
                self.inner.pin_mut().TrySpawnActor(
                    &blueprint.inner,
                    ffi_transform.as_ffi(),
                    parent_ptr,
                    attachment_type,
                    e,
                )
            })?;
            Actor::from_cxx(actor).ok_or_else(|| {
                OperationError::SpawnFailed {
                    blueprint: blueprint.id().to_string(),
                    transform: format!("{:?}", transform),
                    reason: "Spawn returned null (likely collision or invalid location)"
                        .to_string(),
                    source: None,
                }
                .into()
            })
        }
    }

    /// Spawns an actor attached to a parent actor (convenience method).
    ///
    /// This is a convenience wrapper around [`spawn_actor_opt`](Self::spawn_actor_opt) that
    /// makes the API clearer when you specifically want to attach an actor to a parent.
    ///
    /// # Arguments
    ///
    /// * `blueprint` - The actor blueprint
    /// * `transform` - Initial position and rotation (relative to parent)
    /// * `parent` - Parent actor to attach to
    /// * `attachment_type` - How to attach to parent (defaults to [`AttachmentType::Rigid`] if not specified)
    ///
    /// # Examples
    ///
    /// Attaching a camera sensor to a vehicle:
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::{
    ///     client::Client,
    ///     geom::{Location, Rotation, Transform},
    ///     rpc::AttachmentType,
    /// };
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let mut world = client.world()?;
    /// let bp_lib = world.blueprint_library()?;
    ///
    /// // Spawn a vehicle
    /// let vehicle_bp = bp_lib.filter("vehicle.tesla.model3").get(0).unwrap();
    /// let spawn_points = world.map()?.recommended_spawn_points();
    /// let vehicle = world.spawn_actor(&vehicle_bp, &spawn_points.get(0).unwrap())?;
    ///
    /// // Attach a camera to the vehicle's roof
    /// let camera_bp = bp_lib.find("sensor.camera.rgb").unwrap();
    /// let camera_transform = Transform {
    ///     location: Location::new(0.0, 0.0, 2.5), // 2.5m above vehicle center
    ///     rotation: Rotation::default(),
    /// };
    ///
    /// let camera = world.spawn_actor_attached(
    ///     &camera_bp,
    ///     &camera_transform,
    ///     &vehicle,
    ///     AttachmentType::Rigid, // Camera moves rigidly with vehicle
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See also: [`spawn_actor_opt`](Self::spawn_actor_opt) for spawning with optional parent
    pub fn spawn_actor_attached<A, T>(
        &mut self,
        blueprint: &ActorBlueprint,
        transform: &Transform,
        parent: &A,
        attachment_type: T,
    ) -> Result<Actor>
    where
        A: ActorBase,
        T: Into<Option<AttachmentType>>,
    {
        self.spawn_actor_opt(blueprint, transform, Some(parent), attachment_type)
    }

    /// Waits for the next simulation tick and returns the world snapshot.
    ///
    /// In synchronous mode, the server waits for this call before advancing the simulation.
    /// In asynchronous mode, this returns when the next tick completes.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.wait_for_tick](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.wait_for_tick)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.wait_for_tick](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.wait_for_tick)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.wait_for_tick](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.wait_for_tick)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Errors
    ///
    /// Returns an error if the operation times out (default: 60 seconds).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::client::Client;
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let world = client.world()?;
    ///
    /// // Wait for next tick
    /// let snapshot = world.wait_for_tick()?;
    /// println!("Frame: {}", snapshot.frame());
    /// # Ok(())
    /// # }
    /// ```
    pub fn wait_for_tick(&self) -> Result<WorldSnapshot> {
        self.wait_for_tick_or_timeout(DEFAULT_TICK_TIMEOUT)?
            .ok_or_else(|| {
                crate::error::ConnectionError::Timeout {
                    operation: "wait_for_tick".to_string(),
                    duration: DEFAULT_TICK_TIMEOUT,
                    source: None,
                }
                .into()
            })
    }

    /// Creates an actor builder for convenient actor spawning with attribute configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - Blueprint ID (e.g., "vehicle.tesla.model3")
    pub fn actor_builder(&mut self, key: &str) -> Result<ActorBuilder<'_>> {
        ActorBuilder::new(self, key)
    }

    /// Waits for the next tick with a custom timeout.
    ///
    /// Returns `Ok(None)` if the timeout expires (expected behavior).
    /// Returns `Err` if the server is disconnected or another error occurs.
    pub fn wait_for_tick_or_timeout(&self, timeout: Duration) -> Result<Option<WorldSnapshot>> {
        with_ffi_error("wait_for_tick", |error| {
            let ptr = self.inner.WaitForTick(timeout.as_millis() as usize, error);
            WorldSnapshot::from_cxx(ptr)
        })
    }

    /// Advances the simulation by one tick (synchronous mode only).
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum time to wait for the tick
    ///
    /// # Returns
    ///
    /// The frame number after the tick.
    pub fn tick_or_timeout(&mut self, timeout: Duration) -> crate::Result<u64> {
        let millis = timeout.as_millis() as usize;
        with_ffi_error("tick", |e| self.inner.pin_mut().Tick(millis, e))
    }

    /// Advances the simulation by one tick (synchronous mode only).
    ///
    /// Uses the default timeout of 60 seconds.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.tick](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.tick)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.tick](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.tick)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.tick](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.tick)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn tick(&mut self) -> crate::Result<u64> {
        self.tick_or_timeout(DEFAULT_TICK_TIMEOUT)
    }

    /// Sets the percentage of pedestrians that will cross roads.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.set_pedestrians_cross_factor](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.set_pedestrians_cross_factor)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.set_pedestrians_cross_factor](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.set_pedestrians_cross_factor)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.set_pedestrians_cross_factor](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.set_pedestrians_cross_factor)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Arguments
    ///
    /// * `percentage` - Value from 0.0 to 1.0 (0% to 100%)
    pub fn set_pedestrians_cross_factor(&mut self, percentage: f32) -> crate::Result<()> {
        with_ffi_error("set_pedestrians_cross_factor", |e| {
            self.inner
                .pin_mut()
                .SetPedestriansCrossFactor(percentage, e)
        })
    }

    /// Sets the random seed for pedestrian behavior.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.set_pedestrians_seed](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.set_pedestrians_seed)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.set_pedestrians_seed](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.set_pedestrians_seed)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.set_pedestrians_seed](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.set_pedestrians_seed)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn set_pedestrians_seed(&mut self, seed: usize) -> crate::Result<()> {
        let seed = c_uint(seed as std::os::raw::c_uint);
        with_ffi_error("set_pedestrians_seed", |e| {
            self.inner.pin_mut().SetPedestriansSeed(seed, e)
        })
    }

    /// Returns the traffic sign actor at the given landmark location.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_traffic_sign](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_traffic_sign)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_traffic_sign](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_traffic_sign)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_traffic_sign](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_traffic_sign)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn traffic_sign_at(&self, landmark: &Landmark) -> crate::Result<Option<Actor>> {
        // SAFETY: Landmark.inner is guaranteed non-null (see landmark.rs from_cxx())
        let ptr = with_ffi_error("traffic_sign_at", |e| {
            self.inner
                .GetTrafficSign(unsafe { landmark.inner.as_ref().unwrap_unchecked() }, e)
        })?;
        Ok(Actor::from_cxx(ptr))
    }

    /// Returns the traffic light actor at the given landmark location.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_traffic_light](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_traffic_light)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_traffic_light](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_traffic_light)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_traffic_light](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_traffic_light)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn traffic_light_at(&self, landmark: &Landmark) -> crate::Result<Option<Actor>> {
        // SAFETY: Landmark.inner is guaranteed non-null (see landmark.rs from_cxx())
        let ptr = with_ffi_error("traffic_light_at", |e| {
            self.inner
                .GetTrafficLight(unsafe { landmark.inner.as_ref().unwrap_unchecked() }, e)
        })?;
        Ok(Actor::from_cxx(ptr))
    }

    /// Returns the traffic light actor with the given OpenDRIVE sign ID.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_traffic_light_from_opendrive](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_traffic_light_from_opendrive)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_traffic_light_from_opendrive](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_traffic_light_from_opendrive)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_traffic_light_from_opendrive](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_traffic_light_from_opendrive)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn traffic_light_from_open_drive(&self, sign_id: &str) -> crate::Result<Option<Actor>> {
        let_cxx_string!(sign_id = sign_id);
        let ptr = with_ffi_error("traffic_light_from_open_drive", |e| {
            self.inner.GetTrafficLightFromOpenDRIVE(&sign_id, e)
        })?;
        Ok(Actor::from_cxx(ptr))
    }

    /// Freezes or unfreezes all traffic lights in the world.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.freeze_all_traffic_lights](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.freeze_all_traffic_lights)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.freeze_all_traffic_lights](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.freeze_all_traffic_lights)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.freeze_all_traffic_lights](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.freeze_all_traffic_lights)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn freeze_all_traffic_lights(&mut self, frozen: bool) -> crate::Result<()> {
        with_ffi_error("freeze_all_traffic_lights", |e| {
            self.inner.pin_mut().FreezeAllTrafficLights(frozen, e)
        })
    }

    /// Resets all traffic lights to their initial state.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.reset_all_traffic_lights](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.reset_all_traffic_lights)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.reset_all_traffic_lights](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.reset_all_traffic_lights)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.reset_all_traffic_lights](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.reset_all_traffic_lights)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn reset_all_traffic_lights(&mut self) -> crate::Result<()> {
        with_ffi_error("reset_all_traffic_lights", |e| {
            self.inner.pin_mut().ResetAllTrafficLights(e)
        })
    }

    /// Returns bounding boxes for environment objects matching the queried tag.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_level_bbs](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_level_bbs)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_level_bbs](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_level_bbs)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_level_bbs](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_level_bbs)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn level_bounding_boxes(&self, queried_tag: u8) -> crate::Result<BoundingBoxList> {
        let ptr = with_ffi_error("level_bounding_boxes", |e| {
            self.inner.GetLevelBBs(queried_tag, e)
        })?;
        Ok(unsafe { BoundingBoxList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Returns the current weather parameters.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_weather](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_weather)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_weather](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_weather)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_weather](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_weather)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn weather(&self) -> crate::Result<WeatherParameters> {
        with_ffi_error("weather", |e| self.inner.GetWeather(e))
    }

    /// Sets the weather parameters (sun, clouds, precipitation, fog, etc.).
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.set_weather](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.set_weather)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.set_weather](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.set_weather)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.set_weather](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.set_weather)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use carla::{client::Client, rpc::WeatherParameters};
    ///
    /// let client = Client::connect("localhost", 2000, None)?;
    /// let mut world = client.world()?;
    ///
    /// let mut weather = world.weather()?;
    /// weather.cloudiness = 80.0;
    /// weather.precipitation = 50.0;
    /// world.set_weather(&weather)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_weather(&mut self, weather: &WeatherParameters) -> crate::Result<()> {
        with_ffi_error("set_weather", |e| {
            self.inner.pin_mut().SetWeather(weather, e)
        })
    }

    /// Returns whether weather simulation is enabled.
    ///
    /// **Available in CARLA 0.10.0+**
    #[cfg(carla_0100)]
    pub fn is_weather_enabled(&self) -> crate::Result<bool> {
        with_ffi_error("is_weather_enabled", |e| self.inner.IsWeatherEnabled(e))
    }

    /// Returns environment objects matching the queried tag.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.get_environment_objects](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.get_environment_objects)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.get_environment_objects](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.get_environment_objects)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.get_environment_objects](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.get_environment_objects)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn environment_objects(&self, queried_tag: u8) -> crate::Result<EnvironmentObjectList> {
        let ptr = with_ffi_error("environment_objects", |e| {
            self.inner.GetEnvironmentObjects(queried_tag, e)
        })?;
        Ok(unsafe { EnvironmentObjectList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Enables or disables environment objects by their IDs.
    #[cfg_attr(
        carla_version_0916,
        doc = " See [carla.World.enable_environment_objects](https://carla.readthedocs.io/en/0.9.16/python_api/#carla.World.enable_environment_objects)"
    )]
    #[cfg_attr(
        carla_version_0915,
        doc = " See [carla.World.enable_environment_objects](https://carla.readthedocs.io/en/0.9.15/python_api/#carla.World.enable_environment_objects)"
    )]
    #[cfg_attr(
        carla_version_0914,
        doc = " See [carla.World.enable_environment_objects](https://carla.readthedocs.io/en/0.9.14/python_api/#carla.World.enable_environment_objects)"
    )]
    #[cfg_attr(
        any(carla_version_0916, carla_version_0915, carla_version_0914),
        doc = " in the Python API."
    )]
    pub fn enable_environment_objects(&self, ids: &[u64], enable: bool) -> crate::Result<()> {
        let ptr = ids.as_ptr();
        let len = ids.len();
        with_ffi_error("enable_environment_objects", |e| unsafe {
            self.inner.EnableEnvironmentObjects(ptr, len, enable, e)
        })
    }

    pub fn project_point(
        &self,
        location: &Location,
        direction: &Vector3D,
        search_distance: f32,
    ) -> crate::Result<Option<LabelledPoint>> {
        // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
        let cpp_dir = unsafe {
            std::mem::transmute::<FfiVector3D, carla_sys::carla::geom::Vector3D>(
                direction.into_ffi(),
            )
        };
        let ptr = with_ffi_error("project_point", |e| {
            self.inner
                .ProjectPoint(location.into_ffi(), cpp_dir, search_distance, e)
        })?;

        if ptr.is_null() {
            Ok(None)
        } else {
            Ok(Some((*ptr).clone()))
        }
    }

    pub fn ground_projection(
        &self,
        location: &Location,
        search_distance: f32,
    ) -> crate::Result<Option<LabelledPoint>> {
        let ptr = with_ffi_error("ground_projection", |e| {
            self.inner
                .GroundProjection(location.into_ffi(), search_distance, e)
        })?;

        if ptr.is_null() {
            Ok(None)
        } else {
            Ok(Some((*ptr).clone()))
        }
    }

    pub fn cast_ray(&self, start: &Location, end: &Location) -> crate::Result<LabelledPointList> {
        let ptr = with_ffi_error("cast_ray", |e| {
            self.inner.CastRay(start.into_ffi(), end.into_ffi(), e)
        })?;
        Ok(unsafe { LabelledPointList::from_cxx(ptr).unwrap_unchecked() })
    }

    /// Creates a debug helper for drawing visualization primitives.
    ///
    /// Returns a [`DebugHelper`] that can be used to draw points, lines, boxes, arrows,
    /// and text in the simulation for debugging and visualization purposes.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use carla::client::Client;
    /// # use carla::geom::Location;
    /// # use carla::rpc::Color;
    /// #
    /// # let mut client = Client::connect("localhost", 2000, None).unwrap();
    /// # let mut world = client.world();
    /// let mut debug = world.debug();
    ///
    /// // Draw a red point at the origin
    /// debug.draw_point(Location::new(0.0, 0.0, 0.0), 0.5, Color::RED, 5.0, false);
    /// ```
    pub fn debug(&mut self) -> crate::Result<DebugHelper> {
        let ptr = with_ffi_error("debug", |e| self.inner.pin_mut().MakeDebugHelper(e))?;
        Ok(DebugHelper { inner: ptr })
    }

    /// Applies a color texture to a single object by name.
    ///
    /// **Available in CARLA 0.10.0+**
    #[cfg(carla_0100)]
    pub fn apply_color_texture_to_object(
        &mut self,
        object_name: &str,
        parameter: MaterialParameter,
        texture: &TextureColor,
    ) -> crate::Result<()> {
        let_cxx_string!(name = object_name);
        with_ffi_error("apply_color_texture_to_object", |e| {
            self.inner.pin_mut().ApplyColorTextureToObject(
                &name,
                parameter.as_u8(),
                &texture.inner,
                e,
            )
        })
    }

    /// Applies a float color texture to a single object by name.
    ///
    /// **Available in CARLA 0.10.0+**
    #[cfg(carla_0100)]
    pub fn apply_float_color_texture_to_object(
        &mut self,
        object_name: &str,
        parameter: MaterialParameter,
        texture: &TextureFloatColor,
    ) -> crate::Result<()> {
        let_cxx_string!(name = object_name);
        with_ffi_error("apply_float_color_texture_to_object", |e| {
            self.inner.pin_mut().ApplyFloatColorTextureToObject(
                &name,
                parameter.as_u8(),
                &texture.inner,
                e,
            )
        })
    }

    /// Applies a full set of textures (diffuse, emissive, normal, AO/roughness/metallic/emissive)
    /// to a single object by name.
    ///
    /// **Available in CARLA 0.10.0+**
    #[cfg(carla_0100)]
    pub fn apply_textures_to_object(
        &mut self,
        object_name: &str,
        diffuse: &TextureColor,
        emissive: &TextureFloatColor,
        normal: &TextureFloatColor,
        ao_roughness_metallic_emissive: &TextureFloatColor,
    ) -> crate::Result<()> {
        let_cxx_string!(name = object_name);
        with_ffi_error("apply_textures_to_object", |e| {
            self.inner.pin_mut().ApplyTexturesToObject(
                &name,
                &diffuse.inner,
                &emissive.inner,
                &normal.inner,
                &ao_roughness_metallic_emissive.inner,
                e,
            )
        })
    }

    /// Registers a callback to be called on every world tick.
    ///
    /// The callback receives a [`WorldSnapshot`] capturing the state of all
    /// actors at that tick.
    ///
    /// Returns an [`OnTickId`] that can be passed to [`remove_on_tick`](Self::remove_on_tick)
    /// to unregister the callback.
    pub fn on_tick<F>(&mut self, mut callback: F) -> crate::Result<OnTickId>
    where
        F: FnMut(WorldSnapshot) + Send + 'static,
    {
        with_ffi_error("on_tick", |e| unsafe {
            let fn_ptr = {
                let fn_ = move |ptr: UniquePtr<FfiWorldSnapshot>| {
                    if let Some(snapshot) = WorldSnapshot::from_cxx(ptr) {
                        (callback)(snapshot);
                    }
                };
                let fn_: Box<OnTickCb> = Box::new(fn_);
                let fn_ = Box::new(fn_);
                let fn_: *mut Box<OnTickCb> = Box::into_raw(fn_);
                fn_ as *mut c_void
            };

            let caller_ptr = on_tick_caller as *mut c_void;
            let deleter_ptr = on_tick_deleter as *mut c_void;

            OnTickId(
                self.inner
                    .pin_mut()
                    .OnTick(caller_ptr, fn_ptr, deleter_ptr, e),
            )
        })
    }

    /// Removes a previously registered on-tick callback.
    ///
    /// # Arguments
    ///
    /// * `id` - The [`OnTickId`] returned by [`on_tick`](Self::on_tick)
    pub fn remove_on_tick(&mut self, id: OnTickId) -> crate::Result<()> {
        with_ffi_error("remove_on_tick", |e| {
            self.inner.pin_mut().RemoveOnTick(id.0, e);
        })
    }

    pub(crate) fn from_cxx(ptr: UniquePtr<FfiWorld>) -> Option<World> {
        if ptr.is_null() {
            None
        } else {
            Some(Self { inner: ptr })
        }
    }
}

impl Clone for World {
    fn clone(&self) -> Self {
        let ptr =
            with_ffi_error("World::clone", |e| self.inner.clone(e)).expect("World::clone failed");
        unsafe { Self::from_cxx(ptr).unwrap_unchecked() }
    }
}

/// Identifier for an on-tick callback, returned by [`World::on_tick`].
///
/// Pass this to [`World::remove_on_tick`] to unregister the callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OnTickId(usize);

type OnTickCb = dyn FnMut(UniquePtr<FfiWorldSnapshot>) + Send + 'static;

unsafe extern "C" fn on_tick_caller(fn_: *mut c_void, arg: *mut FfiWorldSnapshot) {
    if fn_.is_null() || arg.is_null() {
        eprintln!(
            "ERROR: Null pointer in on_tick callback - fn_: {:p}, arg: {:p}",
            fn_, arg
        );
        return;
    }

    let fn_ = fn_ as *mut Box<OnTickCb>;
    unsafe {
        // Take ownership of the heap-allocated FfiWorldSnapshot from C++
        let snapshot = UniquePtr::from_raw(arg);
        (*fn_)(snapshot);
    }
}

unsafe extern "C" fn on_tick_deleter(fn_: *mut c_void) {
    if fn_.is_null() {
        eprintln!("ERROR: Null pointer in on_tick deleter");
        return;
    }

    let fn_ = fn_ as *mut Box<OnTickCb>;
    let fn_: Box<Box<OnTickCb>> = unsafe { Box::from_raw(fn_) };
    mem::drop(fn_);
}

assert_impl_all!(World: Sync, Send);