]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
Fix missing USE_GL macro usage
[hubacji1/iamcar.git] / base / main.cc
1 /*
2 This file is part of I am car.
3
4 I am car is nree software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 I am car is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with I am car. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <algorithm>
19 #include <chrono>
20 #include <iostream>
21 #include <jsoncpp/json/json.h>
22 #include <pthread.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include "compile.h"
26 #include "obstacle.h"
27 #include "rrtplanner.h"
28 #include "slotplanner.h"
29
30 #if USE_GL > 0
31 // OpenGL
32 #include <GL/gl.h>
33 #include <GL/glu.h>
34 #include <SDL2/SDL.h>
35 #endif
36
37 // debug
38 //#define JSONLOGEDGES
39 //#define JSONLOGSAMPLES
40
41 #if USE_GL > 0
42         #define USE_INTERRUPT
43 #else
44         // choose
45         //#define USE_INTERRUPT
46         // or
47         #define USE_TMAX
48         // or
49         //#define USE_LOADF
50         // or
51         //#define USE_PTHREAD
52 #endif
53
54 // enable
55 //#define USE_SLOTPLANNER
56
57 std::chrono::high_resolution_clock::time_point TSTART_;
58 std::chrono::high_resolution_clock::time_point TEND_;
59 float TELAPSED = 0;
60 float ELAPSED = 0;
61 void TSTART() {TSTART_ = std::chrono::high_resolution_clock::now();}
62 void TEND() {
63         std::chrono::duration<float> DT_;
64         TEND_ = std::chrono::high_resolution_clock::now();
65         DT_ = std::chrono::duration_cast<std::chrono::duration<float>>(
66                 TEND_ - TSTART_
67         );
68         TELAPSED += DT_.count();
69         ELAPSED = DT_.count();
70 }
71 void TPRINT(const char *what) {
72         std::chrono::duration<float> DT_;
73         DT_ = std::chrono::duration_cast<std::chrono::duration<float>>(
74                 TEND_ - TSTART_
75         );
76         std::cerr << what << ": " << DT_.count() << std::endl;
77 }
78
79 bool run_planner = true;
80
81 #if USE_GL > 0
82 SDL_Window* gw = NULL;
83 SDL_GLContext gc;
84
85 bool init();
86 bool initGL();
87 #endif
88
89 void hint(int)
90 {
91         run_planner = false;
92 }
93
94 #ifdef USE_PTHREAD
95 struct next_arg {
96         bool *gf;
97         T2 *p;
98 };
99
100 void *next_run(void *arg)
101 {
102         struct next_arg *na = (struct next_arg *) arg;
103         T2 *lp = (T2 *) na->p;
104         bool *gf = na->gf;
105         while (!*gf && lp->elapsed() < TMAX) {
106                 if (lp->next())
107                         *gf = true;
108                 lp->tend();
109         }
110         pthread_exit(NULL);
111         return NULL;
112 }
113 #endif
114
115 int main()
116 {
117 #if USE_GL > 0
118         init();
119 #endif
120
121         Json::Value jvi; // JSON input
122         Json::Value jvo; // JSON output
123         unsigned int i = 0;
124         unsigned int j = 0;
125         std::cin >> jvi;
126         std::string encoding = jvi.get("encoding", "UTF-8" ).asString();
127
128         PLANNER p(
129                         new RRTNode(
130                                 jvi["init"][0].asFloat(),
131                                 jvi["init"][1].asFloat(),
132                                 jvi["init"][2].asFloat()),
133                         new RRTNode(
134                                 jvi["goal"][0].asFloat(),
135                                 jvi["goal"][1].asFloat(),
136                                 jvi["goal"][2].asFloat()));
137         std::vector<CircleObstacle> co;
138         std::vector<SegmentObstacle> so;
139         for (auto o: jvi["obst"]) {
140                 if (o["circle"] != Json::nullValue) {
141                         co.push_back(CircleObstacle(
142                                                 o["circle"][0].asFloat(),
143                                                 o["circle"][1].asFloat(),
144                                                 o["circle"][2].asFloat()));
145                 }
146                 if (o["segment"] != Json::nullValue) {
147                         so.push_back(SegmentObstacle(
148                                 new RRTNode(
149                                         o["segment"][0][0].asFloat(),
150                                         o["segment"][0][1].asFloat(),
151                                         0),
152                                 new RRTNode(
153                                         o["segment"][1][0].asFloat(),
154                                         o["segment"][1][1].asFloat(),
155                                         0)));
156                         p.frame().add_bnode(so.back().init());
157                 }
158         }
159         p.link_obstacles(&co, &so);
160         p.ocost(p.root());
161         p.ocost(p.goal());
162
163         ParallelSlot ps = ParallelSlot();
164 #ifdef USE_SLOTPLANNER
165         TSTART();
166         for (auto xy: jvi["slot"]["polygon"]) {
167                 ps.slot().add_bnode(new RRTNode(
168                         xy[0].asFloat(),
169                         xy[1].asFloat()
170                 ));
171         }
172         ps.setAll();
173         p.samplingInfo_ = ps.getSamplingInfo();
174         if (ps.slot().bnodes().size() > 0)
175                 ps.fipr(ps.getFP());
176         TEND();
177         jvo["ppse"] = ELAPSED;
178         TPRINT("ParallelSlot");
179 #endif
180         if (ps.cusp().size() > 0) {
181                 p.goal(ps.cusp().front().front());
182                 p.slot_cusp(ps.cusp().front()); // use first found solution
183                 jvo["midd"][0] = p.goal()->x();
184                 jvo["midd"][1] = p.goal()->y();
185                 jvo["midd"][2] = p.goal()->h();
186                 jvo["goal"][0] = p.slot_cusp().back()->x();
187                 jvo["goal"][1] = p.slot_cusp().back()->y();
188                 jvo["goal"][2] = p.slot_cusp().back()->h();
189         } else {
190                 jvo["goal"][0] = p.goal()->x();
191                 jvo["goal"][1] = p.goal()->y();
192                 jvo["goal"][2] = p.goal()->h();
193         }
194         TSTART();
195 #ifdef USE_LOADF
196         std::vector<RRTNode *> steered;
197         for (auto jn: jvi["traj"][0]) {
198                 steered.push_back(new RRTNode(
199                                         jn[0].asFloat(),
200                                         jn[1].asFloat(),
201                                         jn[2].asFloat(),
202                                         jn[3].asFloat(),
203                                         jn[4].asFloat()));
204         }
205         std::reverse(steered.begin(), steered.end());
206         RRTNode *pn = p.root();
207         for (auto n: steered) {
208                 if (IS_NEAR(pn, n))
209                         continue;
210                 pn->add_child(n, p.cost(pn, n));
211                 pn = n;
212                 p.glplot();
213         }
214         pn->add_child(p.goal(), p.cost(pn, p.goal()));
215         p.goal_found(true);
216         p.tlog(p.findt());
217         if (p.opt_path()) {
218                 p.tlog(p.findt());
219                 p.glplot();
220         }
221         p.glplot();
222         sleep(2);
223 #elif defined USE_INTERRUPT
224         signal(SIGINT, hint);
225         signal(SIGTERM, hint);
226         p.tstart();
227         while (run_planner) {
228                 p.next();
229                 p.tend();
230                 if (p.opt_path())
231                         p.tlog(p.findt());
232                 p.glplot();
233         }
234 #elif defined USE_TMAX
235         p.tstart();
236         p.tend();
237         while (!p.goal_found() && p.elapsed() < TMAX) {
238                 p.next();
239                 p.tend();
240                 if (p.opt_path()) {
241                         if (ps.cusp().size() > 0)
242                                 p.tlog(p.findt(p.slot_cusp().back()));
243                         else
244                                 p.tlog(p.findt());
245                 }
246         }
247 #elif defined USE_PTHREAD
248         bool gf = false;
249         RRTNode *ron = nullptr;
250         RRTNode *gon = nullptr;
251         float mc = 9999;
252         pthread_t rt; // root thread
253         pthread_t gt; // goal thread
254         pthread_t ct; // connect thread
255
256         struct next_arg ra;
257         ra.gf = &gf;
258         ra.p = &p.p_root_;
259
260         struct next_arg ga;
261         ga.gf = &gf;
262         ga.p = &p.p_goal_;
263
264         p.tstart();
265         p.p_root_.tstart();
266         p.p_goal_.tstart();
267         pthread_create(&rt, NULL, &next_run, (void *) &ra);
268         pthread_create(&gt, NULL, &next_run, (void *) &ga);
269         int tol = 0;
270         int ndl = 0;
271         bool ndone = true;
272         while (!gf && p.elapsed() < TMAX &&
273                         p.p_root_.nodes().size() < NOFNODES &&
274                         p.p_goal_.nodes().size() < NOFNODES) {
275                 // overlap trees
276                 ndone = true;
277                 for (int i = 0; i < IXSIZE; i++) {
278                 for (int j = 0; j < IYSIZE; j++) {
279                         if (p.p_root_.ixy_[i][j].changed() &&
280                                         p.p_goal_.ixy_[i][j].changed()) {
281 ndone = false;
282 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
283 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
284         if (rn->ccost() + gn->ccost() < mc &&
285                         IS_NEAR(rn, gn)) {
286                 gf = true;
287                 p.goal_found(true);
288                 ron = rn;
289                 gon = gn;
290                 mc = rn->ccost() + gn->ccost();
291         }
292 }}
293                         }
294                         tol++;
295                         if (ndone)
296                                 ndl++;
297                         p.tend();
298                         if (p.elapsed() >= TMAX)
299                                 goto escapeloop;
300                 }}
301                 // end of overlap trees
302                 p.tend();
303         }
304 escapeloop:
305         pthread_join(rt, NULL);
306         pthread_join(gt, NULL);
307         float nodo = ((float) ndl / (float) tol);
308         std::cerr << "nothing done is " << 100.0 * nodo;
309         std::cerr << "%" << std::endl;
310         //std::cerr << "rgf is " << p.p_root_.goal_found() << std::endl;
311         //std::cerr << "ggf is " << p.p_goal_.goal_found() << std::endl;
312         //std::cerr << "cgf is " << p.goal_found() << std::endl;
313         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
314                 ron = p.p_root_.goal()->parent();
315                 gon = p.p_root_.goal();
316                 mc = p.p_root_.goal()->ccost();
317         }
318         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
319                 ron = p.p_goal_.goal();
320                 gon = p.p_goal_.goal()->parent();
321                 mc = p.p_goal_.goal()->ccost();
322         }
323         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
324         p.root()->ccost(0);
325         p.goal()->children().clear();
326         // connect trees
327         if (gf) {
328         while (gon != p.goal()) {
329                 p.p_root_.nodes().push_back(new RRTNode(
330                                 gon->x(),
331                                 gon->y(),
332                                 gon->h()));
333                 ron->add_child(
334                                 p.p_root_.nodes().back(),
335                                 p.p_root_.cost(
336                                                 ron,
337                                                 p.p_root_.nodes().back()));
338                 ron = p.p_root_.nodes().back();
339                 gon = gon->parent();
340         }
341         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
342         }
343         // end of connect trees
344         if (gf)
345                 p.tlog(p.findt());
346         if (p.opt_path())
347                 p.tlog(p.findt());
348 #endif
349         TEND();
350         TPRINT("RRT");
351         jvo["rrte"] = ELAPSED;
352 #ifdef JSONLOGEDGES
353         p.logr(p.root());
354 #endif
355
356         // statistics to error output
357         std::cerr << "TELAPSED is " << TELAPSED << std::endl;
358         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
359         std::cerr << "Goal found is " << p.goal_found() << std::endl;
360         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
361         std::cerr << "#samples is " << p.samples().size() << std::endl;
362         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
363         std::cerr << "trajectories costs:" << std::endl;
364         for (j = 0; j < p.clog().size(); j++)
365                 std::cerr << "- " << p.clog()[j] << std::endl;
366         std::cerr << "RRT #nodes:" << std::endl;
367         for (j = 0; j < p.nlog().size(); j++)
368                 std::cerr << "- " << p.nlog()[j] << std::endl;
369         std::cerr << "trajectories seconds:" << std::endl;
370         for (j = 0; j < p.slog().size(); j++)
371                 std::cerr << "- " << p.slog()[j] << std::endl;
372         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
373         std::cerr << std::endl;
374         for (auto edges: p.rlog())
375                 std::cerr << "- " << edges.size() << std::endl;
376
377         // JSON output
378         jvo["elap"] = TELAPSED;
379 #ifdef USE_PTHREAD
380         jvo["nodo"][0] = nodo;
381 #endif
382         // log cost
383         for (j = 0; j < p.clog().size(); j++)
384                 jvo["cost"][j] = p.clog()[j];
385         // log #nodes
386         for (j = 0; j < p.nlog().size(); j++)
387                 jvo["node"][j] = p.nlog()[j];
388         // log seconds
389         for (j = 0; j < p.slog().size(); j++)
390                 jvo["secs"][j] = p.slog()[j];
391         // log traj
392         i = 0;
393         j = 0;
394         for (auto traj: p.tlog()) {
395                 i = 0;
396                 for (auto n: traj) {
397                         jvo["traj"][j][i][0] = n->x();
398                         jvo["traj"][j][i][1] = n->y();
399                         jvo["traj"][j][i][2] = n->h();
400                         jvo["traj"][j][i][3] = n->t();
401                         jvo["traj"][j][i][4] = n->s();
402                         i++;
403                 }
404                 j++;
405         }
406 #ifdef JSONLOGEDGES
407         i = 0;
408         j = 0;
409         for (auto edges: p.rlog()) {
410                 j = 0;
411                 for (auto e: edges) {
412                         jvo["edge"][i][j][0][0] = e->init()->x();
413                         jvo["edge"][i][j][0][1] = e->init()->y();
414                         jvo["edge"][i][j][0][2] = e->init()->h();
415                         jvo["edge"][i][j][1][0] = e->goal()->x();
416                         jvo["edge"][i][j][1][1] = e->goal()->y();
417                         jvo["edge"][i][j][1][2] = e->goal()->h();
418                         j++;
419                 }
420                 i++;
421         }
422 #endif
423 #ifdef JSONLOGSAMPLES
424         i = 0;
425         j = 0;
426         for (auto s: p.samples()) {
427                 jvo["samp"][j][0] = s->x();
428                 jvo["samp"][j][1] = s->y();
429                 jvo["samp"][j][2] = s->h();
430                 j++;
431         }
432 #endif
433         // print output
434         std::cout << jvo << std::endl;
435
436 #if USE_GL > 0
437         SDL_DestroyWindow(gw);
438         SDL_Quit();
439 #endif
440
441         // free mem
442         for (auto o: so) {
443                 delete o.init();
444                 delete o.goal();
445         }
446         return 0;
447 }
448
449 #if USE_GL > 0
450 bool init()
451 {
452         if (SDL_Init(SDL_INIT_VIDEO) < 0) {
453                 std::cerr << "SDL could not initialize! SDL_Error: ";
454                 std::cerr << SDL_GetError();
455                 std::cerr << std::endl;
456                 return false;
457         }
458         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
459         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
460         gw = SDL_CreateWindow(
461                         "I am car",
462                         SDL_WINDOWPOS_UNDEFINED,
463                         SDL_WINDOWPOS_UNDEFINED,
464                         SCREEN_WIDTH,
465                         SCREEN_HEIGHT,
466                         SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
467         if (gw == NULL) {
468                 std::cerr << "Window could not be created! SDL_Error: ";
469                 std::cerr << SDL_GetError();
470                 std::cerr << std::endl;
471                 return false;
472         }
473         gc = SDL_GL_CreateContext(gw);
474         if (gc == NULL) {
475                 std::cerr << "OpenGL context couldn't be created! SDL Error: ";
476                 std::cerr << SDL_GetError();
477                 std::cerr << std::endl;
478                 return false;
479         }
480         if (SDL_GL_SetSwapInterval(1) < 0) {
481                 std::cerr << "Warning: Unable to set VSync! SDL Error: ";
482                 std::cerr << SDL_GetError();
483                 std::cerr << std::endl;
484                 return false;
485         }
486         if (!initGL()) {
487                 std::cerr << "Unable to initialize OpenGL!";
488                 std::cerr << std::endl;
489                 return false;
490         }
491         return true;
492 }
493
494 bool initGL()
495 {
496         GLenum error = GL_NO_ERROR;
497         glMatrixMode(GL_PROJECTION);
498         glLoadIdentity();
499         error = glGetError();
500         if (error != GL_NO_ERROR) {
501                 std::cerr << "Error initializing OpenGL! ";
502                 std::cerr << gluErrorString(error);
503                 std::cerr << std::endl;
504                 return false;
505         }
506         glMatrixMode(GL_MODELVIEW);
507         glLoadIdentity();
508         error = glGetError();
509         if (error != GL_NO_ERROR) {
510                 std::cerr << "Error initializing OpenGL! ";
511                 std::cerr << gluErrorString(error);
512                 std::cerr << std::endl;
513                 return false;
514         }
515         glClearColor(1, 1, 1, 1);
516         error = glGetError();
517         if (error != GL_NO_ERROR) {
518                 std::cerr << "Error initializing OpenGL! ";
519                 std::cerr << gluErrorString(error);
520                 std::cerr << std::endl;
521                 return false;
522         }
523         return true;
524 }
525 #endif