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