-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarlet.hpp
More file actions
1877 lines (1602 loc) · 62.9 KB
/
carlet.hpp
File metadata and controls
1877 lines (1602 loc) · 62.9 KB
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
#include <iostream>
#if 0 // example
#include <ctime>
#define CARLET_IMPLEMENTATION
#include "carlet.hpp"
void naive_plan(const carlet::Veh::SensorData& sensor_data, const carlet::Veh::State& ego_state,
carlet::Veh::Control& ctrl)
{
(void)sensor_data;
(void)ego_state;
ctrl.steer = 0.0f;
ctrl.accel = 1.0f;
}
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
srand(time(NULL));
const auto straight_road{carlet::Road::gen_straight(
Vector3{.x=0.0f, .y=0.0f, .z=0.0f},
Vector3{.x=2000.0f, .y=0.0f, .z=0.0f},
2, 3.7f)};
auto sim{carlet::Simulator::instance()};
sim->map().road_net.push_back(straight_road);
sim->create_ctrl_veh(carlet::veh_model::tesla, 1);
sim->gen_random_vehs(80,
carlet::kmph_to_mps(40.0),
carlet::kmph_to_mps(120.0));
carlet::Veh* v{};
carlet::Veh::Control ctrl{};
while (sim->is_running()) {
if ((v = sim->get_ctrl_veh()) != nullptr) {
naive_plan(v->sensor_data(), v->state(), ctrl);
v->act(ctrl);
}
sim->step(0.02f);
sim->render();
}
return 0;
}
#endif // example
#define CARLET_IMPLEMENTATION
#ifndef CARLET_HPP_
#define CARLET_HPP_
#include <mutex>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <raylib.h>
#define CARLET_DEF_SINGLETON(classname) \
public: \
static inline classname* instance() \
{ \
static classname *instance_ = nullptr; \
static std::once_flag flag; \
if (!instance_) { \
std::call_once(flag, [&](){ \
instance_ = new (std::nothrow) classname(); \
}); \
} \
return instance_; \
} \
private: \
classname(const classname&) = delete; \
classname& operator=(const classname&) = delete; \
classname(const classname&&) = delete; \
classname& operator=(const classname&&) = delete;
namespace carlet {
class Simulator;
struct Veh;
struct Road
{
struct Strip {
Vector3 l; // left line edge
Vector3 r; // right line edge
}; // struct Strip
struct LaneSample {
Vector3 c; // lane center sample point
float width;
}; // struct LaneSample
using Lane = std::vector<LaneSample>;
using Lanelet = std::vector<Strip>;
using RoadEdge = std::vector<Strip>;
std::vector<Lane> lanes;
std::vector<Lanelet> lanelets;
RoadEdge left_edge;
RoadEdge right_edge;
static Road gen_straight(const Vector3& start_position, const Vector3& end_position, int num_lane, float lane_width);
}; // struct Road
using RoadNet = std::vector<Road>;
struct Map
{
RoadNet road_net;
Mesh road_mesh;
Model road_model;
Mesh edge_mesh;
Model edge_model;
Mesh lanelet_mesh;
Model lanelet_model;
}; // struct Map
struct VehModel
{
float wheel_base;
float wheel_radius;
float gc_to_back_axle; // gc: gravity center
float max_eps_angle;
float min_eps_angle;
float eps_to_wheel_angle; // 1 deg wheel_angle => eps_to_wheel_angle eps_angle
float max_accel;
float Cd; // Coefficient of Drag
float mass;
float max_hp; // max horse power
float hp_loss; // hp loss
float gear_friction; // gear friction
Vector3 shape;
}; // struct VehModel
struct Object
{
Object() : Object({.x=0.0f, .y=0.0f, .z=0.0f}) {}
explicit Object(const Vector3& shp);
const int id;
Vector3 shape;
Model model;
Color color;
friend class Simulator;
private:
virtual bool step(float dt) { return true; }
}; // struct Object
struct Veh: public Object
{
struct Obs
{
std::vector<Veh*>& vehs;
Map& map;
}; // struct Obs
struct TorqControl
{
float eps_torq;
float accel;
}; // struct TorqControl
struct AngleControl
{
float eps_angle;
float accel;
}; // struct AngleControl
struct Obstacle
{
Vector3 center;
Vector3 shape;
float heading;
float vel;
}; // struct Obstacle
struct SensorData
{
std::vector<Obstacle> obsts;
std::unordered_map<int, std::vector<Vector3>> lanelets;
}; // struct SensorData
struct Eps
{
float angle; // rad
float spd; // rad/s
float torq; // N/m
}; // struct Eps
struct State
{
double x;
double y;
double z;
double vel;
double accel;
double jerk;
double yaw;
double yaw_rate;
double steer_angle;
Vector3 position() const { return Vector3{.x=static_cast<float>(x),
.y=static_cast<float>(y),
.z=static_cast<float>(z)}; }
double distance(const Vector3& other) const;
double distance(const State& other) const;
static State init_with(float init_x, float init_y, float init_z, float init_vel);
}; // struct State
Veh(float init_vel, const VehModel& model)
: Veh(0.0, 0.0f, init_vel, model, false)
{}
Veh(float init_x, float init_y, float init_vel, const VehModel& model, bool controllable)
: Object(model.shape)
, front_wheel_steer_(0.0f)
, accelerator_ratio_(0.0f)
, brake_ratio_(0.0f)
, state_(State::init_with(init_x, init_y, model.shape.z / 2.0f, init_vel))
, vm(model)
, idm_cruise_vel_(init_vel)
, controllable_(controllable)
, valid_(true)
{}
void act(const TorqControl& control);
void act(const AngleControl& control);
inline const State& state() const { return state_; }
inline const SensorData& sensor_data() const { return sensor_data_; }
inline bool valid() const { return valid_; }
inline const Eps& eps() const { return eps_; }
const VehModel vm;
private:
friend class Simulator;
float front_wheel_steer_;
float accelerator_ratio_;
float brake_ratio_;
Eps eps_;
State state_;
SensorData sensor_data_;
const float idm_cruise_vel_;
const bool controllable_;
bool valid_;
float wheel_torque(float accelerator_ratio) const;
float wheel_friction() const;
float air_resistance() const;
float wheel_rot_spd() const; // r/min
void lat_control(const TorqControl& control);
void lat_control(const AngleControl& control);
void lon_control(float accel);
void dynamic_act(float steer, float accel, float dt);
void idm_act(const AngleControl& control);
bool idm_plan(const Veh::Obs& full_obs, AngleControl& control);
bool idm_reset_position(const Vector3& ref_position, const Simulator* simulator);
bool step(float dt);
}; // struct Veh
class Simulator
{
CARLET_DEF_SINGLETON(Simulator)
public:
~Simulator();
bool is_running();
bool step(float dt);
void render();
int create_ctrl_veh(const VehModel& model, int lane_idx);
void gen_random_vehs(int n, float min_vel, float max_vel);
Veh* get_ctrl_veh(int idx) const;
bool collision_with_any_veh(const Veh* veh) const;
inline Veh::Obs full_obs() { return Veh::Obs{.vehs=vehs_, .map=map_}; }
inline Veh* get_ctrl_veh() const { return get_ctrl_veh(first_ctrl_idx_); };
inline Map& map() { return map_; }
inline const Map& map() const { return map_; }
private:
Simulator();
void map_to_mesh_model();
void update_camera();
void draw_mini_map();
void draw_control_info();
void sensing(Veh* ego, float dt);
void sensing_obsts(Veh* ego);
void sensing_lanelets(Veh* ego);
std::vector<Veh*> vehs_;
Camera3D camera_;
Map map_;
int first_ctrl_idx_;
}; // class Simulator
#define CARLET_PI 3.14159265358979323846
#define CARLET_2_PI 6.283185307179586
#define CARLET_G 9.8 // m/s^2
template<typename T>
struct AlwaysFalse { enum {value = false}; };
template<typename T>
inline constexpr T pow2(T v) { return v * v; }
template<typename T>
inline constexpr T pow3(T v) { return v * v * v; }
template<typename T>
inline constexpr T min(T a, T b) { return a > b ? b : a; }
template<typename T>
inline constexpr T max(T a, T b) { return a > b ? a : b; }
template<typename T>
inline constexpr T abs(T a) { return a > 0 ? a : -a; }
template<typename T>
inline constexpr T clamp(T v, T low, T high) { return v > high ? high : (v < low ? low : v); }
template<typename T>
inline constexpr T mps_to_kmph(T mps) { return mps * static_cast<T>(3.6); }
template<typename T>
inline constexpr T kmph_to_mps(T kmph) { return kmph / static_cast<T>(3.6); }
template<typename T>
inline constexpr T hp_to_kw(T hp) { return hp * static_cast<T>(0.735); }
template<typename T>
inline constexpr T kw_to_hp(T kw) { return kw * static_cast<T>(1.36); }
template<typename T>
inline constexpr T rad_to_deg(T rad) { return rad / CARLET_PI * 180.0; }
template<typename T>
inline constexpr T deg_to_rad(T deg) { return deg / 180.0 * CARLET_PI; }
template<typename T>
inline float distance(const T& a, const T& b)
{
static_assert(AlwaysFalse<T>::value, "Not supportted");
return 0.0f; // supress compiler warning
}
template<>
inline float distance<Vector3>(const Vector3& a, const Vector3& b)
{
return std::sqrt(pow2(a.x - b.x) + pow2(a.y - b.y) + pow2(a.z - b.z));
}
template<>
inline float distance<Vector2>(const Vector2& a, const Vector2& b)
{
return std::sqrt(pow2(a.x - b.x) + pow2(a.y - b.y));
}
template<>
inline float distance<Veh>(const Veh& a, const Veh& b)
{
return std::sqrt(pow2(a.state().x - b.state().x) +
pow2(a.state().y - b.state().y) +
pow2(a.state().z - b.state().z));
}
template<typename T>
inline constexpr T normalize_heading(T rad)
{
while (rad > CARLET_PI) {
rad -= CARLET_2_PI;
}
while (rad < -CARLET_PI) {
rad += CARLET_2_PI;
}
return rad;
}
namespace veh_model {
extern const VehModel tesla;
}; // namespace veh_model
} // namespace carlet
#ifdef _GLIBCXX_OSTREAM
std::ostream& operator<<(std::ostream& os, const Vector2& vec);
std::ostream& operator<<(std::ostream& os, const Vector3& vec);
std::ostream& operator<<(std::ostream& os, const carlet::Veh::State& state);
#endif // _GLIBCXX_OSTREAM
#endif // CARLET_HPP_
#ifdef CARLET_IMPLEMENTATION
#ifndef CARLET_CPP_
#define CARLET_CPP_
#include <cassert>
#include <rlgl.h>
#include <raymath.h>
#ifdef _GLIBCXX_OSTREAM
# include <iomanip>
#endif // _GLIBCXX_OSTREAM
#ifndef CARLET_EPSf
# include <limits>
# define CARLET_EPSf std::numeric_limits<float>::epsilon()
#endif // CARLET_EPSf
#ifndef CARLET_EPS
# include <limits>
# define CARLET_EPS std::numeric_limits<double>::epsilon()
#endif // CARLET_EPS
#ifndef CARLET_MAX_ID
# define CARLET_MAX_ID 100000
#endif // CARLET_MAX_ID
#ifndef CARLET_TARGET_FPS
# define CARLET_TARGET_FPS 50
#endif // CARLET_TARGET_FPS
#ifndef CARLET_MAX_SENSOR_RANGE
# define CARLET_MAX_SENSOR_RANGE 100.0 // meter
#endif // CARLET_MAX_SENSOR_RANGE
#ifndef CARLET_WIN_WIDTH
# define CARLET_WIN_WIDTH 1000
#endif // CARLET_WIN_WIDTH
#ifndef CARLET_WIN_HEIGHT
# define CARLET_WIN_HEIGHT 600
#endif // CARLET_WIN_HEIGHT
#ifndef CARLET_WIN_TITLE
# define CARLET_WIN_TITLE "Carlet Simulator"
#endif // CARLET_WIN_TITLE
#ifndef CARLET_ROAD_EDGE_WIDTH
# define CARLET_ROAD_EDGE_WIDTH 0.1f // meter, which is 10cm
#endif // CARLET_ROAD_EDGE_WIDTH
#ifndef CARLET_LANELET_WIDTH
# define CARLET_LANELET_WIDTH 0.1f // meter, which is 10cm
#endif // CARLET_LANELET_WIDTH
#ifndef CARLET_MAX_GEN_VEH_TRIES
# define CARLET_MAX_GEN_VEH_TRIES 10
#endif // CARLET_MAX_GEN_VEH_TRIES
#ifndef CARLET_IDM_GEN_MAX_DIST
# define CARLET_IDM_GEN_MAX_DIST 300.0f
#endif // CARLET_IDM_MAX_DIST
#ifndef CARLET_IDM_GEN_MIN_DIST
# define CARLET_IDM_GEN_MIN_DIST 100.0f
#endif // CARLET_IDM_MIN_DIST
#ifndef CARLET_AIR_DENSITY
# define CARLET_AIR_DENSITY 1.293f // kg/m3
#endif // CARLET_AIR_DENSITY
#ifndef CARLET_ROAD_FRICTION_FACTOR
# define CARLET_ROAD_FRICTION_FACTOR 0.6f
#endif // CARLET_ROAD_FRICTION_FACTOR
#define CARLET_ARR_LEN(arr) (sizeof(arr) / sizeof((arr)[0]))
#ifdef _GLIBCXX_OSTREAM
inline std::ostream& operator<<(std::ostream& os, const Vector2& vec)
{
os << "(" << vec.x << ", " << vec.y << ")";
return os;
}
inline std::ostream& operator<<(std::ostream& os, const Vector3& vec)
{
os << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return os;
}
inline std::ostream& operator<<(std::ostream& os, float* vec)
{
os << "(" << vec[0] << ", " << vec[1] << ", " << vec[2] << ")";
return os;
}
inline std::ostream& operator<<(std::ostream& os, const carlet::Veh::State& state)
{
os << std::fixed << std::setprecision(2) << "State {"
<< "x: " << state.x
<< ", y: " << state.y
<< ", z: " << state.z
<< ", vel: " << state.vel << " (" << carlet::mps_to_kmph(state.vel) << ")"
<< ", accel: " << state.accel
<< ", jerk: " << state.jerk
<< ", yaw: " << state.yaw
<< ", yaw_rate: " << state.yaw_rate
<< ", steer_angle: " << state.steer_angle
<< "}";
return os;
}
#endif // _GLIBCXX_OSTREAM
namespace carlet {
struct Vector2i
{
int x;
int y;
};
struct Vector3i
{
int x;
int y;
int z;
};
const Mesh& gen_veh_mesh(const Vector3& shape);
bool find_lane_info(const std::vector<Road::Lane>& lanes, const Vector3& p, float half_veh_width,
int& lane_idx, int& waypoint_idx);
bool check_veh_collision(const Veh* a, const Veh* b);
template<typename T>
inline T rand_ab(T a, T b)
{
assert(b > a);
const auto rv01{static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) + 1.0f)};
return rv01 * (b - a) + a;
}
namespace veh_model {
const VehModel tesla {
.wheel_base = 2.8f, // meter
.wheel_radius = 0.33f, // meter
.gc_to_back_axle = 1.5f, // meter
.max_eps_angle = deg_to_rad(630.0f), // rad
.min_eps_angle = deg_to_rad(-630.0f), // rad
.eps_to_wheel_angle = 14.4,
.max_accel = 5.0f, // m/s^2
.Cd = 0.23f, // Coefficient of Drag
.mass = 1836.0f, // kg
.max_hp = 190.0f, // hp
.hp_loss = 0.17f, // precent of hp
.gear_friction = 400.0f, // gear friction, newton
.shape = Vector3{.x = 4.2f, .y = 1.98f, .z = 1.6f}
}; // tesla
static const VehModel all_veh_models[] {
tesla
};
inline const VehModel& random() {
constexpr auto num_models{CARLET_ARR_LEN(all_veh_models)};
return all_veh_models[rand() % num_models];
}
}; // namespace veh_model
static const Color veh_colors[] {
YELLOW, GOLD, ORANGE, PINK, RED, MAROON,
GREEN, LIME, DARKGREEN, SKYBLUE, BLUE, DARKBLUE,
PURPLE, VIOLET, DARKPURPLE, BEIGE, BROWN, DARKBROWN,
MAGENTA, RAYWHITE
};
inline const Color& random_color()
{
constexpr auto num_colors{CARLET_ARR_LEN(veh_colors)};
return veh_colors[rand() % num_colors];
}
inline const Color& next_color()
{
constexpr auto num_colors{CARLET_ARR_LEN(veh_colors)};
static int i{0};
static std::mutex lock{};
std::lock_guard<std::mutex> guard{lock};
return veh_colors[i++ % num_colors];
}
inline void to_raylib_mesh3(float* vec)
{
const auto x{vec[0]};
const auto y{vec[1]};
const auto z{vec[2]};
vec[0] = -y;
vec[1] = z;
vec[2] = -x;
}
inline Vector3 to_raylib(const Vector3& vec)
{
return Vector3{.x=-vec.y, .y=vec.z, .z=-vec.x};
}
inline int gen_id()
{
static int cnt{0};
static std::mutex lock{};
std::lock_guard<std::mutex> guard{lock};
int result{cnt};
cnt = (cnt + 1) % CARLET_MAX_ID;
return result;
}
template<typename T, size_t N>
struct Intergrator
{
void append(T v)
{
data[idx] = v;
idx = (idx + 1) % N;
}
T sum()
{
T res{};
for (int i = 0; i < N; ++i) res += data[i];
return res;
}
private:
T data[N];
int idx;
}; // struct Intergrator
Object::Object(const Vector3& shp) : id(gen_id()), shape(shp) {}
Veh::State Veh::State::init_with(float init_x, float init_y, float init_z, float init_vel)
{
return State{
.x = init_x,
.y = init_y,
.z = init_z,
.vel = init_vel,
.accel = 0.0f,
.jerk = 0.0f,
.yaw = 0.0f,
.yaw_rate = 0.0f,
.steer_angle = 0.0f,
};
}
Road Road::gen_straight(const Vector3& start_position, const Vector3& end_position, int num_lane, float lane_width)
{
constexpr auto min_lane_width{2.0f}; // meter
constexpr auto sample_length{1.0f}; // meter
constexpr auto half_road_edge_width{CARLET_ROAD_EDGE_WIDTH / 2.0f};
const auto length{Vector3Distance(start_position, end_position)};
assert(length > 0.0f && "Bad road length");
assert(num_lane > 0 && "Bad number of lane");
assert(lane_width > min_lane_width && "Bad lane width");
const auto num_samples{max(static_cast<int>(length / sample_length), 1)};
const auto road_width{num_lane * lane_width};
Road road;
road.left_edge.resize(num_samples);
road.right_edge.resize(num_samples);
if (num_lane >= 2) {
road.lanelets.resize(num_lane - 1);
for (auto& lanelet : road.lanelets) {
lanelet.resize(num_samples);
}
}
road.lanes.resize(road.lanelets.size() + 1);
for (auto& lane: road.lanes) {
lane.resize(num_samples);
}
auto calc_center_line{[&start_position, &end_position, length] (float s, Vector3& center_point) -> void {
center_point.x = (end_position.x - start_position.x) * s / length + start_position.x;
center_point.y = (end_position.y - start_position.y) * s / length + start_position.y;
center_point.z = (end_position.z - start_position.z) * s / length + start_position.z;
}};
Vector3 sample_center_point{};
const auto road_heading{std::atan2(end_position.y - start_position.y, end_position.x - start_position.x)};
const auto cos_road_heading{std::cos(road_heading)};
const auto sin_road_heading{std::sin(road_heading)};
for (int i = 0; i < num_samples; ++i) {
const auto sample_s{sample_length * i};
calc_center_line(sample_s, sample_center_point);
const auto left_edge_offset_r{road_width / 2.0f - half_road_edge_width};
const auto left_edge_offset_l{road_width / 2.0f + half_road_edge_width};
const auto right_edge_offset_r{-road_width / 2.0f - half_road_edge_width};
const auto right_edge_offset_l{-road_width / 2.0f + half_road_edge_width};
road.left_edge.at(i).l.x = sample_center_point.x + left_edge_offset_l * sin_road_heading;
road.left_edge.at(i).l.y = sample_center_point.y + left_edge_offset_l * cos_road_heading;
road.left_edge.at(i).l.z = sample_center_point.z;
road.left_edge.at(i).r.x = sample_center_point.x + left_edge_offset_r * sin_road_heading;
road.left_edge.at(i).r.y = sample_center_point.y + left_edge_offset_r * cos_road_heading;
road.left_edge.at(i).r.z = sample_center_point.z;
road.right_edge.at(i).l.x = sample_center_point.x + right_edge_offset_l * sin_road_heading;
road.right_edge.at(i).l.y = sample_center_point.y + right_edge_offset_l * cos_road_heading;
road.right_edge.at(i).l.z = sample_center_point.z;
road.right_edge.at(i).r.x = sample_center_point.x + right_edge_offset_r * sin_road_heading;
road.right_edge.at(i).r.y = sample_center_point.y + right_edge_offset_r * cos_road_heading;
road.right_edge.at(i).r.z = sample_center_point.z;
if (!road.lanelets.empty()) {
for (size_t j = 0; j < road.lanelets.size(); ++j) {
auto& lanelet{road.lanelets.at(j)};
const auto left_lanelet_offset{-static_cast<int>(j + 1) * lane_width};
lanelet.at(i).l.x = road.left_edge.at(i).l.x + left_lanelet_offset * sin_road_heading;
lanelet.at(i).l.y = road.left_edge.at(i).l.y + left_lanelet_offset * cos_road_heading;
lanelet.at(i).l.z = road.left_edge.at(i).l.z;
const auto right_lanelet_offset{-CARLET_LANELET_WIDTH};
lanelet.at(i).r.x = lanelet.at(i).l.x + right_lanelet_offset * sin_road_heading;
lanelet.at(i).r.y = lanelet.at(i).l.y + right_lanelet_offset * cos_road_heading;
lanelet.at(i).r.z = lanelet.at(i).l.z;
}
for (int j = 0; j <= static_cast<int>(road.lanelets.size()); ++j) {
const auto left_lanelet_idx{j - 1};
const auto right_lanelet_idx{j};
const auto& left_edge_point{left_lanelet_idx < 0
? road.left_edge.at(i).l
: road.lanelets.at(left_lanelet_idx).at(i).l};
const auto& right_edge_point{right_lanelet_idx == road.lanelets.size()
? road.right_edge.at(i).r
: road.lanelets.at(right_lanelet_idx).at(i).r};
road.lanes.at(j).at(i).width = lane_width;
road.lanes.at(j).at(i).c.x = (left_edge_point.x + right_edge_point.x) / 2.0f;
road.lanes.at(j).at(i).c.y = (left_edge_point.y + right_edge_point.y) / 2.0f;
road.lanes.at(j).at(i).c.z = sample_center_point.z;
}
} else {
// single lane road
road.lanes.at(0).at(i).width = lane_width;
road.lanes.at(0).at(i).c.x = sample_center_point.x;
road.lanes.at(0).at(i).c.y = sample_center_point.y;
road.lanes.at(0).at(i).c.z = sample_center_point.z;
}
}
return road;
}
bool Simulator::is_running()
{
return !WindowShouldClose();
}
void Simulator::map_to_mesh_model()
{
static bool mesh_generated{false};
if (mesh_generated) return;
mesh_generated = true;
int num_lanelets{0};
map_.road_mesh.vertexCount = 0;
map_.edge_mesh.vertexCount = 0;
map_.lanelet_mesh.vertexCount = 0;
for (const auto& road : map_.road_net) {
map_.edge_mesh.vertexCount += road.left_edge.size() * 2;
map_.edge_mesh.vertexCount += road.right_edge.size() * 2;
map_.road_mesh.vertexCount += max(road.right_edge.size(), road.left_edge.size()) * 2; // road
for (const auto& lanelet : road.lanelets) {
map_.lanelet_mesh.vertexCount += lanelet.size() * 2;
++num_lanelets;
}
}
map_.road_mesh.triangleCount = map_.road_mesh.vertexCount - 2;
map_.road_mesh.vertices = (float*)RL_CALLOC(3 * map_.road_mesh.vertexCount, sizeof(float)); // Vertex positions
map_.road_mesh.normals = (float*)RL_CALLOC(3 * map_.road_mesh.vertexCount, sizeof(float)); // Normals
map_.road_mesh.indices = (unsigned short*)RL_CALLOC(map_.road_mesh.triangleCount * 3, sizeof(unsigned short)); // Index data
map_.edge_mesh.triangleCount = map_.edge_mesh.vertexCount - (2 * 2);
map_.edge_mesh.vertices = (float*)RL_CALLOC(3 * map_.edge_mesh.vertexCount, sizeof(float)); // Vertex positions
map_.edge_mesh.normals = (float*)RL_CALLOC(3 * map_.edge_mesh.vertexCount, sizeof(float)); // Normals
map_.edge_mesh.indices = (unsigned short*)RL_CALLOC(map_.edge_mesh.triangleCount * 3, sizeof(unsigned short)); // Index data
map_.lanelet_mesh.triangleCount = map_.lanelet_mesh.vertexCount - (2 * num_lanelets);
map_.lanelet_mesh.vertices = (float*)RL_CALLOC(3 * map_.lanelet_mesh.vertexCount, sizeof(float)); // Vertex positions
map_.lanelet_mesh.normals = (float*)RL_CALLOC(3 * map_.lanelet_mesh.vertexCount, sizeof(float)); // Normals
map_.lanelet_mesh.indices = (unsigned short*)RL_CALLOC(map_.lanelet_mesh.triangleCount * 3, sizeof(unsigned short)); // Index data
int v_idx{0};
int t_idx{0};
int num_v_last_line{0};
for (const auto& road : map_.road_net) {
// road
int num_v_this_line{0};
const size_t num_strip{min(road.left_edge.size(), road.right_edge.size())};
for (size_t i = 0; i < num_strip; ++i) {
const auto& left_strip{road.left_edge.at(i)};
const auto& right_strip{road.right_edge.at(i)};
map_.road_mesh.vertices[v_idx * 6 + 0] = left_strip.l.x;
map_.road_mesh.vertices[v_idx * 6 + 1] = left_strip.l.y;
map_.road_mesh.vertices[v_idx * 6 + 2] = left_strip.l.z;
to_raylib_mesh3(map_.road_mesh.vertices + v_idx * 6);
map_.road_mesh.vertices[v_idx * 6 + 3] = right_strip.r.x;
map_.road_mesh.vertices[v_idx * 6 + 4] = right_strip.r.y;
map_.road_mesh.vertices[v_idx * 6 + 5] = right_strip.r.z;
to_raylib_mesh3(map_.road_mesh.vertices + v_idx * 6 + 3);
map_.road_mesh.normals[v_idx * 6 + 0] = 0.0f;
map_.road_mesh.normals[v_idx * 6 + 1] = 1.0f;
map_.road_mesh.normals[v_idx * 6 + 2] = 0.0f;
map_.road_mesh.normals[v_idx * 6 + 3] = 0.0f;
map_.road_mesh.normals[v_idx * 6 + 4] = 1.0f;
map_.road_mesh.normals[v_idx * 6 + 5] = 0.0f;
num_v_this_line += 2;
++v_idx;
}
for (size_t i = 0; i < num_v_this_line - 2; i += 2) {
map_.road_mesh.indices[t_idx * 6 + 0] = i;
map_.road_mesh.indices[t_idx * 6 + 1] = i + 1;
map_.road_mesh.indices[t_idx * 6 + 2] = i + 2;
map_.road_mesh.indices[t_idx * 6 + 3] = i + 1;
map_.road_mesh.indices[t_idx * 6 + 4] = i + 3;
map_.road_mesh.indices[t_idx * 6 + 5] = i + 2;
++t_idx;
}
// left road edge
num_v_this_line = 0;
num_v_last_line = 0;
v_idx = 0;
t_idx = 0;
for (const auto& strip: road.left_edge) {
map_.edge_mesh.vertices[v_idx * 6 + 0] = strip.l.x;
map_.edge_mesh.vertices[v_idx * 6 + 1] = strip.l.y;
map_.edge_mesh.vertices[v_idx * 6 + 2] = strip.l.z;
to_raylib_mesh3(map_.edge_mesh.vertices + v_idx * 6);
map_.edge_mesh.vertices[v_idx * 6 + 3] = strip.r.x;
map_.edge_mesh.vertices[v_idx * 6 + 4] = strip.r.y;
map_.edge_mesh.vertices[v_idx * 6 + 5] = strip.r.z;
to_raylib_mesh3(map_.edge_mesh.vertices + v_idx * 6 + 3);
map_.edge_mesh.normals[v_idx * 6 + 0] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 1] = 1.0f;
map_.edge_mesh.normals[v_idx * 6 + 2] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 3] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 4] = 1.0f;
map_.edge_mesh.normals[v_idx * 6 + 5] = 0.0f;
num_v_this_line += 2;
++v_idx;
}
for (size_t i = 0; i < num_v_this_line - 2; i += 2) {
map_.edge_mesh.indices[t_idx * 6 + 0] = num_v_last_line + i;
map_.edge_mesh.indices[t_idx * 6 + 1] = num_v_last_line + i + 1;
map_.edge_mesh.indices[t_idx * 6 + 2] = num_v_last_line + i + 2;
map_.edge_mesh.indices[t_idx * 6 + 3] = num_v_last_line + i + 1;
map_.edge_mesh.indices[t_idx * 6 + 4] = num_v_last_line + i + 3;
map_.edge_mesh.indices[t_idx * 6 + 5] = num_v_last_line + i + 2;
++t_idx;
}
// right road edge
num_v_this_line = 0;
num_v_last_line = v_idx * 2;
for (const auto& strip: road.right_edge) {
map_.edge_mesh.vertices[v_idx * 6 + 0] = strip.l.x;
map_.edge_mesh.vertices[v_idx * 6 + 1] = strip.l.y;
map_.edge_mesh.vertices[v_idx * 6 + 2] = strip.l.z;
to_raylib_mesh3(map_.edge_mesh.vertices + v_idx * 6);
map_.edge_mesh.vertices[v_idx * 6 + 3] = strip.r.x;
map_.edge_mesh.vertices[v_idx * 6 + 4] = strip.r.y;
map_.edge_mesh.vertices[v_idx * 6 + 5] = strip.r.z;
to_raylib_mesh3(map_.edge_mesh.vertices + v_idx * 6 + 3);
map_.edge_mesh.normals[v_idx * 6 + 0] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 1] = 1.0f;
map_.edge_mesh.normals[v_idx * 6 + 2] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 3] = 0.0f;
map_.edge_mesh.normals[v_idx * 6 + 4] = 1.0f;
map_.edge_mesh.normals[v_idx * 6 + 5] = 0.0f;
++v_idx;
num_v_this_line += 2;
}
for (size_t i = 0; i < num_v_this_line - 2; i += 2) {
map_.edge_mesh.indices[t_idx * 6 + 0] = num_v_last_line + i;
map_.edge_mesh.indices[t_idx * 6 + 1] = num_v_last_line + i + 1;
map_.edge_mesh.indices[t_idx * 6 + 2] = num_v_last_line + i + 2;
map_.edge_mesh.indices[t_idx * 6 + 3] = num_v_last_line + i + 1;
map_.edge_mesh.indices[t_idx * 6 + 4] = num_v_last_line + i + 3;
map_.edge_mesh.indices[t_idx * 6 + 5] = num_v_last_line + i + 2;
++t_idx;
}
v_idx = 0;
t_idx = 0;
for (const auto& lanelet : road.lanelets) {
num_v_this_line = 0;
num_v_last_line = v_idx * 2;
for (const auto& strip: lanelet) {
map_.lanelet_mesh.vertices[v_idx * 6 + 0] = strip.l.x;
map_.lanelet_mesh.vertices[v_idx * 6 + 1] = strip.l.y;
map_.lanelet_mesh.vertices[v_idx * 6 + 2] = strip.l.z;
to_raylib_mesh3(map_.lanelet_mesh.vertices + v_idx * 6);
map_.lanelet_mesh.vertices[v_idx * 6 + 3] = strip.r.x;
map_.lanelet_mesh.vertices[v_idx * 6 + 4] = strip.r.y;
map_.lanelet_mesh.vertices[v_idx * 6 + 5] = strip.r.z;
to_raylib_mesh3(map_.lanelet_mesh.vertices + v_idx * 6 + 3);
map_.lanelet_mesh.normals[v_idx * 6 + 0] = 0.0f;
map_.lanelet_mesh.normals[v_idx * 6 + 1] = 1.0f;
map_.lanelet_mesh.normals[v_idx * 6 + 2] = 0.0f;
map_.lanelet_mesh.normals[v_idx * 6 + 3] = 0.0f;
map_.lanelet_mesh.normals[v_idx * 6 + 4] = 1.0f;
map_.lanelet_mesh.normals[v_idx * 6 + 5] = 0.0f;
++v_idx;
num_v_this_line += 2;
}
for (size_t i = 0; i < num_v_this_line - 2; i += 2) {
map_.lanelet_mesh.indices[t_idx * 6 + 0] = num_v_last_line + i;
map_.lanelet_mesh.indices[t_idx * 6 + 1] = num_v_last_line + i + 1;
map_.lanelet_mesh.indices[t_idx * 6 + 2] = num_v_last_line + i + 2;
map_.lanelet_mesh.indices[t_idx * 6 + 3] = num_v_last_line + i + 1;
map_.lanelet_mesh.indices[t_idx * 6 + 4] = num_v_last_line + i + 3;
map_.lanelet_mesh.indices[t_idx * 6 + 5] = num_v_last_line + i + 2;
++t_idx;
}
}
}
UploadMesh(&map_.road_mesh, false);
UploadMesh(&map_.edge_mesh, false);
UploadMesh(&map_.lanelet_mesh, false);
map_.road_model = LoadModelFromMesh(map_.road_mesh);
map_.edge_model = LoadModelFromMesh(map_.edge_mesh);
map_.lanelet_model = LoadModelFromMesh(map_.lanelet_mesh);
}
Simulator::Simulator()
: first_ctrl_idx_(-1)
{
InitWindow(CARLET_WIN_WIDTH, CARLET_WIN_HEIGHT, CARLET_WIN_TITLE);
SetTargetFPS(CARLET_TARGET_FPS);
camera_.position = {.x=0.0f, .y=5.0f, .z=0.0f};
camera_.target = {.x=0.0f, .y=0.0f, .z=0.0f};
camera_.up = {.x=0.0f, .y=1.0f, .z=0.0f};
camera_.fovy = 45.0f;
camera_.projection = CAMERA_PERSPECTIVE;
}
Simulator::~Simulator()
{
for (auto v: vehs_) {
delete v;
}
vehs_.clear();
}
void Simulator::update_camera()
{
camera_.fovy += GetMouseWheelMove() * -5.0f;
camera_.fovy = clamp(camera_.fovy, 0.0f, 170.0f);
static int last_left_down_x{-1};
static int last_left_down_y{-1};
static int last_right_down_x{-1};
static int last_right_down_y{-1};
static Vector3 camera_pos_offset{camera_.position};
static Vector3 camera_target_offset{camera_.target};
if (!vehs_.empty() && first_ctrl_idx_ >= 0) {
// camera follow this first controllable car
const auto& veh{vehs_.at(first_ctrl_idx_)};
camera_.target.z = camera_target_offset.z - veh->state().x - 80;
camera_.target.x = camera_target_offset.x;
camera_.target.y = camera_target_offset.y;
camera_.position.z = camera_pos_offset.z - veh->state().x + 20;
camera_.position.x = camera_pos_offset.x;
camera_.position.y = camera_pos_offset.y;
} else {
camera_.target.z = camera_target_offset.z;
camera_.target.x = camera_target_offset.x;
camera_.target.y = camera_target_offset.y;
camera_.position.z = camera_pos_offset.z;
camera_.position.x = camera_pos_offset.x;