]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
Use slot sampling info when slot in scenario
[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         if (
162                 jvi["slot"] != Json::nullValue &&
163                 jvi["slot"]["polygon"] != Json::nullValue
164         ) {
165                 for (auto xy: jvi["slot"]["polygon"]) {
166                         ps.slot().add_bnode(new RRTNode(
167                                 xy[0].asFloat(),
168                                 xy[1].asFloat()
169                         ));
170                 }
171         }
172         if (ps.slot().bnodes().size() > 0) {
173                 ps.setAll();
174                 p.samplingInfo_ = ps.getSamplingInfo();
175         }
176 #ifdef USE_SLOTPLANNER
177         TSTART();
178         if (ps.slot().bnodes().size() > 0)
179                 ps.fipr(ps.getFP());
180         TEND();
181         jvo["ppse"] = ELAPSED;
182         TPRINT("ParallelSlot");
183 #endif
184         if (ps.cusp().size() > 0) {
185                 p.goal(ps.cusp().front().front());
186                 p.slot_cusp(ps.cusp().front()); // use first found solution
187                 jvo["midd"][0] = p.goal()->x();
188                 jvo["midd"][1] = p.goal()->y();
189                 jvo["midd"][2] = p.goal()->h();
190                 jvo["goal"][0] = p.slot_cusp().back()->x();
191                 jvo["goal"][1] = p.slot_cusp().back()->y();
192                 jvo["goal"][2] = p.slot_cusp().back()->h();
193         } else {
194                 jvo["goal"][0] = p.goal()->x();
195                 jvo["goal"][1] = p.goal()->y();
196                 jvo["goal"][2] = p.goal()->h();
197         }
198         TSTART();
199 #ifdef USE_LOADF
200         std::vector<RRTNode *> steered;
201         for (auto jn: jvi["traj"][0]) {
202                 steered.push_back(new RRTNode(
203                                         jn[0].asFloat(),
204                                         jn[1].asFloat(),
205                                         jn[2].asFloat(),
206                                         jn[3].asFloat(),
207                                         jn[4].asFloat()));
208         }
209         std::reverse(steered.begin(), steered.end());
210         RRTNode *pn = p.root();
211         for (auto n: steered) {
212                 if (IS_NEAR(pn, n))
213                         continue;
214                 pn->add_child(n, p.cost(pn, n));
215                 pn = n;
216                 p.glplot();
217         }
218         pn->add_child(p.goal(), p.cost(pn, p.goal()));
219         p.goal_found(true);
220         p.tlog(p.findt());
221         if (p.opt_path()) {
222                 p.tlog(p.findt());
223                 p.glplot();
224         }
225         p.glplot();
226         sleep(2);
227 #elif defined USE_INTERRUPT
228         signal(SIGINT, hint);
229         signal(SIGTERM, hint);
230         p.tstart();
231         while (run_planner) {
232                 p.next();
233                 p.tend();
234                 if (p.opt_path())
235                         p.tlog(p.findt());
236                 p.glplot();
237         }
238 #elif defined USE_TMAX
239         p.tstart();
240         p.tend();
241         while (!p.goal_found() && p.elapsed() < TMAX) {
242                 p.next();
243                 p.tend();
244                 if (p.opt_path()) {
245                         if (ps.cusp().size() > 0)
246                                 p.tlog(p.findt(p.slot_cusp().back()));
247                         else
248                                 p.tlog(p.findt());
249                 }
250         }
251 #elif defined USE_PTHREAD
252         bool gf = false;
253         RRTNode *ron = nullptr;
254         RRTNode *gon = nullptr;
255         float mc = 9999;
256         pthread_t rt; // root thread
257         pthread_t gt; // goal thread
258         pthread_t ct; // connect thread
259
260         struct next_arg ra;
261         ra.gf = &gf;
262         ra.p = &p.p_root_;
263
264         struct next_arg ga;
265         ga.gf = &gf;
266         ga.p = &p.p_goal_;
267
268         p.tstart();
269         p.p_root_.tstart();
270         p.p_goal_.tstart();
271         pthread_create(&rt, NULL, &next_run, (void *) &ra);
272         pthread_create(&gt, NULL, &next_run, (void *) &ga);
273         int tol = 0;
274         int ndl = 0;
275         bool ndone = true;
276         while (!gf && p.elapsed() < TMAX &&
277                         p.p_root_.nodes().size() < NOFNODES &&
278                         p.p_goal_.nodes().size() < NOFNODES) {
279                 // overlap trees
280                 ndone = true;
281                 for (int i = 0; i < IXSIZE; i++) {
282                 for (int j = 0; j < IYSIZE; j++) {
283                         if (p.p_root_.ixy_[i][j].changed() &&
284                                         p.p_goal_.ixy_[i][j].changed()) {
285 ndone = false;
286 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
287 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
288         if (rn->ccost() + gn->ccost() < mc &&
289                         IS_NEAR(rn, gn)) {
290                 gf = true;
291                 p.goal_found(true);
292                 ron = rn;
293                 gon = gn;
294                 mc = rn->ccost() + gn->ccost();
295         }
296 }}
297                         }
298                         tol++;
299                         if (ndone)
300                                 ndl++;
301                         p.tend();
302                         if (p.elapsed() >= TMAX)
303                                 goto escapeloop;
304                 }}
305                 // end of overlap trees
306                 p.tend();
307         }
308 escapeloop:
309         pthread_join(rt, NULL);
310         pthread_join(gt, NULL);
311         float nodo = ((float) ndl / (float) tol);
312         std::cerr << "nothing done is " << 100.0 * nodo;
313         std::cerr << "%" << std::endl;
314         //std::cerr << "rgf is " << p.p_root_.goal_found() << std::endl;
315         //std::cerr << "ggf is " << p.p_goal_.goal_found() << std::endl;
316         //std::cerr << "cgf is " << p.goal_found() << std::endl;
317         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
318                 ron = p.p_root_.goal()->parent();
319                 gon = p.p_root_.goal();
320                 mc = p.p_root_.goal()->ccost();
321         }
322         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
323                 ron = p.p_goal_.goal();
324                 gon = p.p_goal_.goal()->parent();
325                 mc = p.p_goal_.goal()->ccost();
326         }
327         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
328         p.root()->ccost(0);
329         p.goal()->children().clear();
330         // connect trees
331         if (gf) {
332         while (gon != p.goal()) {
333                 p.p_root_.nodes().push_back(new RRTNode(
334                                 gon->x(),
335                                 gon->y(),
336                                 gon->h()));
337                 ron->add_child(
338                                 p.p_root_.nodes().back(),
339                                 p.p_root_.cost(
340                                                 ron,
341                                                 p.p_root_.nodes().back()));
342                 ron = p.p_root_.nodes().back();
343                 gon = gon->parent();
344         }
345         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
346         }
347         // end of connect trees
348         if (gf)
349                 p.tlog(p.findt());
350         if (p.opt_path())
351                 p.tlog(p.findt());
352 #endif
353         TEND();
354         TPRINT("RRT");
355         jvo["rrte"] = ELAPSED;
356 #ifdef JSONLOGEDGES
357         p.logr(p.root());
358 #endif
359
360         // statistics to error output
361         std::cerr << "TELAPSED is " << TELAPSED << std::endl;
362         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
363         std::cerr << "Goal found is " << p.goal_found() << std::endl;
364         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
365         std::cerr << "#samples is " << p.samples().size() << std::endl;
366         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
367         std::cerr << "trajectories costs:" << std::endl;
368         for (j = 0; j < p.clog().size(); j++)
369                 std::cerr << "- " << p.clog()[j] << std::endl;
370         std::cerr << "RRT #nodes:" << std::endl;
371         for (j = 0; j < p.nlog().size(); j++)
372                 std::cerr << "- " << p.nlog()[j] << std::endl;
373         std::cerr << "trajectories seconds:" << std::endl;
374         for (j = 0; j < p.slog().size(); j++)
375                 std::cerr << "- " << p.slog()[j] << std::endl;
376         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
377         std::cerr << std::endl;
378         for (auto edges: p.rlog())
379                 std::cerr << "- " << edges.size() << std::endl;
380
381         // JSON output
382         jvo["elap"] = TELAPSED;
383 #ifdef USE_PTHREAD
384         jvo["nodo"][0] = nodo;
385 #endif
386         // log cost
387         for (j = 0; j < p.clog().size(); j++)
388                 jvo["cost"][j] = p.clog()[j];
389         // log #nodes
390         for (j = 0; j < p.nlog().size(); j++)
391                 jvo["node"][j] = p.nlog()[j];
392         // log seconds
393         for (j = 0; j < p.slog().size(); j++)
394                 jvo["secs"][j] = p.slog()[j];
395         // log traj
396         i = 0;
397         j = 0;
398         for (auto traj: p.tlog()) {
399                 i = 0;
400                 for (auto n: traj) {
401                         jvo["traj"][j][i][0] = n->x();
402                         jvo["traj"][j][i][1] = n->y();
403                         jvo["traj"][j][i][2] = n->h();
404                         jvo["traj"][j][i][3] = n->t();
405                         jvo["traj"][j][i][4] = n->s();
406                         i++;
407                 }
408                 j++;
409         }
410 #ifdef JSONLOGEDGES
411         i = 0;
412         j = 0;
413         for (auto edges: p.rlog()) {
414                 j = 0;
415                 for (auto e: edges) {
416                         jvo["edge"][i][j][0][0] = e->init()->x();
417                         jvo["edge"][i][j][0][1] = e->init()->y();
418                         jvo["edge"][i][j][0][2] = e->init()->h();
419                         jvo["edge"][i][j][1][0] = e->goal()->x();
420                         jvo["edge"][i][j][1][1] = e->goal()->y();
421                         jvo["edge"][i][j][1][2] = e->goal()->h();
422                         j++;
423                 }
424                 i++;
425         }
426 #endif
427 #ifdef JSONLOGSAMPLES
428         i = 0;
429         j = 0;
430         for (auto s: p.samples()) {
431                 jvo["samp"][j][0] = s->x();
432                 jvo["samp"][j][1] = s->y();
433                 jvo["samp"][j][2] = s->h();
434                 j++;
435         }
436 #endif
437         // print output
438         std::cout << jvo << std::endl;
439
440 #if USE_GL > 0
441         SDL_DestroyWindow(gw);
442         SDL_Quit();
443 #endif
444
445         // free mem
446         for (auto o: so) {
447                 delete o.init();
448                 delete o.goal();
449         }
450         return 0;
451 }
452
453 #if USE_GL > 0
454 bool init()
455 {
456         if (SDL_Init(SDL_INIT_VIDEO) < 0) {
457                 std::cerr << "SDL could not initialize! SDL_Error: ";
458                 std::cerr << SDL_GetError();
459                 std::cerr << std::endl;
460                 return false;
461         }
462         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
463         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
464         gw = SDL_CreateWindow(
465                         "I am car",
466                         SDL_WINDOWPOS_UNDEFINED,
467                         SDL_WINDOWPOS_UNDEFINED,
468                         SCREEN_WIDTH,
469                         SCREEN_HEIGHT,
470                         SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
471         if (gw == NULL) {
472                 std::cerr << "Window could not be created! SDL_Error: ";
473                 std::cerr << SDL_GetError();
474                 std::cerr << std::endl;
475                 return false;
476         }
477         gc = SDL_GL_CreateContext(gw);
478         if (gc == NULL) {
479                 std::cerr << "OpenGL context couldn't be created! SDL Error: ";
480                 std::cerr << SDL_GetError();
481                 std::cerr << std::endl;
482                 return false;
483         }
484         if (SDL_GL_SetSwapInterval(1) < 0) {
485                 std::cerr << "Warning: Unable to set VSync! SDL Error: ";
486                 std::cerr << SDL_GetError();
487                 std::cerr << std::endl;
488                 return false;
489         }
490         if (!initGL()) {
491                 std::cerr << "Unable to initialize OpenGL!";
492                 std::cerr << std::endl;
493                 return false;
494         }
495         return true;
496 }
497
498 bool initGL()
499 {
500         GLenum error = GL_NO_ERROR;
501         glMatrixMode(GL_PROJECTION);
502         glLoadIdentity();
503         error = glGetError();
504         if (error != GL_NO_ERROR) {
505                 std::cerr << "Error initializing OpenGL! ";
506                 std::cerr << gluErrorString(error);
507                 std::cerr << std::endl;
508                 return false;
509         }
510         glMatrixMode(GL_MODELVIEW);
511         glLoadIdentity();
512         error = glGetError();
513         if (error != GL_NO_ERROR) {
514                 std::cerr << "Error initializing OpenGL! ";
515                 std::cerr << gluErrorString(error);
516                 std::cerr << std::endl;
517                 return false;
518         }
519         glClearColor(1, 1, 1, 1);
520         error = glGetError();
521         if (error != GL_NO_ERROR) {
522                 std::cerr << "Error initializing OpenGL! ";
523                 std::cerr << gluErrorString(error);
524                 std::cerr << std::endl;
525                 return false;
526         }
527         return true;
528 }
529 #endif