]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
Merge branch 'feature/perpendicular-slotplanner'
[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 // OpenGL
30 #include <GL/gl.h>
31 #include <GL/glu.h>
32 #include <SDL2/SDL.h>
33
34 // debug
35 //#define JSONLOGEDGES
36 //#define JSONLOGSAMPLES
37
38 // choose
39 //#define USE_INTERRUPT
40 // or
41 #define USE_TMAX
42 // or
43 //#define USE_LOADF
44 // or
45 //#define USE_PTHREAD
46
47 // enable
48 //#define USE_SLOTPLANNER
49
50 // enable
51 //#define USE_SLOTPLANNER
52
53 #ifdef USE_INTERRUPT
54         #define USE_GL
55 #endif
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 SDL_Window* gw = NULL;
82 SDL_GLContext gc;
83
84 bool init();
85 bool initGL();
86
87 void hint(int)
88 {
89         run_planner = false;
90 }
91
92 #ifdef USE_PTHREAD
93 struct next_arg {
94         bool *gf;
95         T2 *p;
96 };
97
98 void *next_run(void *arg)
99 {
100         struct next_arg *na = (struct next_arg *) arg;
101         T2 *lp = (T2 *) na->p;
102         bool *gf = na->gf;
103         while (!*gf && lp->elapsed() < TMAX) {
104                 if (lp->next())
105                         *gf = true;
106                 lp->tend();
107         }
108         pthread_exit(NULL);
109         return NULL;
110 }
111 #endif
112
113 int main()
114 {
115 #ifdef USE_GL
116         init();
117 #endif
118
119         Json::Value jvi; // JSON input
120         Json::Value jvo; // JSON output
121         unsigned int i = 0;
122         unsigned int j = 0;
123         std::cin >> jvi;
124         std::string encoding = jvi.get("encoding", "UTF-8" ).asString();
125
126         PLANNER p(
127                         new RRTNode(
128                                 jvi["init"][0].asFloat(),
129                                 jvi["init"][1].asFloat(),
130                                 jvi["init"][2].asFloat()),
131                         new RRTNode(
132                                 jvi["goal"][0].asFloat(),
133                                 jvi["goal"][1].asFloat(),
134                                 jvi["goal"][2].asFloat()));
135         std::vector<CircleObstacle> co;
136         std::vector<SegmentObstacle> so;
137         for (auto o: jvi["obst"]) {
138                 if (o["circle"] != Json::nullValue) {
139                         co.push_back(CircleObstacle(
140                                                 o["circle"][0].asFloat(),
141                                                 o["circle"][1].asFloat(),
142                                                 o["circle"][2].asFloat()));
143                 }
144                 if (o["segment"] != Json::nullValue) {
145                         so.push_back(SegmentObstacle(
146                                 new RRTNode(
147                                         o["segment"][0][0].asFloat(),
148                                         o["segment"][0][1].asFloat(),
149                                         0),
150                                 new RRTNode(
151                                         o["segment"][1][0].asFloat(),
152                                         o["segment"][1][1].asFloat(),
153                                         0)));
154                         p.frame().add_bnode(so.back().init());
155                 }
156         }
157         p.link_obstacles(&co, &so);
158         p.ocost(p.root());
159         p.ocost(p.goal());
160
161         ParallelSlot ps = ParallelSlot();
162 #ifdef USE_SLOTPLANNER
163         TSTART();
164         for (auto xy: jvi["slot"]["polygon"]) {
165                 ps.slot().add_bnode(new RRTNode(
166                         xy[0].asFloat(),
167                         xy[1].asFloat()
168                 ));
169         }
170         ps.setAll();
171         p.samplingInfo_ = ps.getSamplingInfo();
172         if (ps.slot().bnodes().size() > 0)
173                 ps.fipr(ps.getFP());
174         TEND();
175         jvo["ppse"] = ELAPSED;
176         TPRINT("ParallelSlot");
177 #endif
178         if (ps.cusp().size() > 0) {
179                 p.goal(ps.cusp().front().front());
180                 p.slot_cusp(ps.cusp().front()); // use first found solution
181                 jvo["midd"][0] = p.goal()->x();
182                 jvo["midd"][1] = p.goal()->y();
183                 jvo["midd"][2] = p.goal()->h();
184                 jvo["goal"][0] = p.slot_cusp().back()->x();
185                 jvo["goal"][1] = p.slot_cusp().back()->y();
186                 jvo["goal"][2] = p.slot_cusp().back()->h();
187         } else {
188                 jvo["goal"][0] = p.goal()->x();
189                 jvo["goal"][1] = p.goal()->y();
190                 jvo["goal"][2] = p.goal()->h();
191         }
192         TSTART();
193 #ifdef USE_LOADF
194         std::vector<RRTNode *> steered;
195         for (auto jn: jvi["traj"][0]) {
196                 steered.push_back(new RRTNode(
197                                         jn[0].asFloat(),
198                                         jn[1].asFloat(),
199                                         jn[2].asFloat(),
200                                         jn[3].asFloat(),
201                                         jn[4].asFloat()));
202         }
203         std::reverse(steered.begin(), steered.end());
204         RRTNode *pn = p.root();
205         for (auto n: steered) {
206                 if (IS_NEAR(pn, n))
207                         continue;
208                 pn->add_child(n, p.cost(pn, n));
209                 pn = n;
210                 p.glplot();
211         }
212         pn->add_child(p.goal(), p.cost(pn, p.goal()));
213         p.goal_found(true);
214         p.tlog(p.findt());
215         if (p.opt_path()) {
216                 p.tlog(p.findt());
217                 p.glplot();
218         }
219         p.glplot();
220         sleep(2);
221 #elif defined USE_INTERRUPT
222         signal(SIGINT, hint);
223         signal(SIGTERM, hint);
224         p.tstart();
225         while (run_planner) {
226                 p.next();
227                 p.tend();
228                 if (p.opt_path())
229                         p.tlog(p.findt());
230                 p.glplot();
231         }
232 #elif defined USE_TMAX
233         p.tstart();
234         p.tend();
235         while (!p.goal_found() && p.elapsed() < TMAX) {
236                 p.next();
237                 p.tend();
238                 if (p.opt_path()) {
239                         if (ps.cusp().size() > 0)
240                                 p.tlog(p.findt(p.slot_cusp().back()));
241                         else
242                                 p.tlog(p.findt());
243                 }
244         }
245 #elif defined USE_PTHREAD
246         bool gf = false;
247         RRTNode *ron = nullptr;
248         RRTNode *gon = nullptr;
249         float mc = 9999;
250         pthread_t rt; // root thread
251         pthread_t gt; // goal thread
252         pthread_t ct; // connect thread
253
254         struct next_arg ra;
255         ra.gf = &gf;
256         ra.p = &p.p_root_;
257
258         struct next_arg ga;
259         ga.gf = &gf;
260         ga.p = &p.p_goal_;
261
262         p.tstart();
263         p.p_root_.tstart();
264         p.p_goal_.tstart();
265         pthread_create(&rt, NULL, &next_run, (void *) &ra);
266         pthread_create(&gt, NULL, &next_run, (void *) &ga);
267         int tol = 0;
268         int ndl = 0;
269         bool ndone = true;
270         while (!gf && p.elapsed() < TMAX &&
271                         p.p_root_.nodes().size() < NOFNODES &&
272                         p.p_goal_.nodes().size() < NOFNODES) {
273                 // overlap trees
274                 ndone = true;
275                 for (int i = 0; i < IXSIZE; i++) {
276                 for (int j = 0; j < IYSIZE; j++) {
277                         if (p.p_root_.ixy_[i][j].changed() &&
278                                         p.p_goal_.ixy_[i][j].changed()) {
279 ndone = false;
280 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
281 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
282         if (rn->ccost() + gn->ccost() < mc &&
283                         IS_NEAR(rn, gn)) {
284                 gf = true;
285                 p.goal_found(true);
286                 ron = rn;
287                 gon = gn;
288                 mc = rn->ccost() + gn->ccost();
289         }
290 }}
291                         }
292                         tol++;
293                         if (ndone)
294                                 ndl++;
295                         p.tend();
296                         if (p.elapsed() >= TMAX)
297                                 goto escapeloop;
298                 }}
299                 // end of overlap trees
300                 p.tend();
301         }
302 escapeloop:
303         pthread_join(rt, NULL);
304         pthread_join(gt, NULL);
305         float nodo = ((float) ndl / (float) tol);
306         std::cerr << "nothing done is " << 100.0 * nodo;
307         std::cerr << "%" << std::endl;
308         //std::cerr << "rgf is " << p.p_root_.goal_found() << std::endl;
309         //std::cerr << "ggf is " << p.p_goal_.goal_found() << std::endl;
310         //std::cerr << "cgf is " << p.goal_found() << std::endl;
311         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
312                 ron = p.p_root_.goal()->parent();
313                 gon = p.p_root_.goal();
314                 mc = p.p_root_.goal()->ccost();
315         }
316         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
317                 ron = p.p_goal_.goal();
318                 gon = p.p_goal_.goal()->parent();
319                 mc = p.p_goal_.goal()->ccost();
320         }
321         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
322         p.root()->ccost(0);
323         p.goal()->children().clear();
324         // connect trees
325         if (gf) {
326         while (gon != p.goal()) {
327                 p.p_root_.nodes().push_back(new RRTNode(
328                                 gon->x(),
329                                 gon->y(),
330                                 gon->h()));
331                 ron->add_child(
332                                 p.p_root_.nodes().back(),
333                                 p.p_root_.cost(
334                                                 ron,
335                                                 p.p_root_.nodes().back()));
336                 ron = p.p_root_.nodes().back();
337                 gon = gon->parent();
338         }
339         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
340         }
341         // end of connect trees
342         if (gf)
343                 p.tlog(p.findt());
344         if (p.opt_path())
345                 p.tlog(p.findt());
346 #endif
347         TEND();
348         TPRINT("RRT");
349         jvo["rrte"] = ELAPSED;
350 #ifdef JSONLOGEDGES
351         p.logr(p.root());
352 #endif
353
354         // statistics to error output
355         std::cerr << "TELAPSED is " << TELAPSED << std::endl;
356         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
357         std::cerr << "Goal found is " << p.goal_found() << std::endl;
358         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
359         std::cerr << "#samples is " << p.samples().size() << std::endl;
360         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
361         std::cerr << "trajectories costs:" << std::endl;
362         for (j = 0; j < p.clog().size(); j++)
363                 std::cerr << "- " << p.clog()[j] << std::endl;
364         std::cerr << "RRT #nodes:" << std::endl;
365         for (j = 0; j < p.nlog().size(); j++)
366                 std::cerr << "- " << p.nlog()[j] << std::endl;
367         std::cerr << "trajectories seconds:" << std::endl;
368         for (j = 0; j < p.slog().size(); j++)
369                 std::cerr << "- " << p.slog()[j] << std::endl;
370         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
371         std::cerr << std::endl;
372         for (auto edges: p.rlog())
373                 std::cerr << "- " << edges.size() << std::endl;
374
375         // JSON output
376         jvo["elap"] = TELAPSED;
377 #ifdef USE_PTHREAD
378         jvo["nodo"][0] = nodo;
379 #endif
380         // log cost
381         for (j = 0; j < p.clog().size(); j++)
382                 jvo["cost"][j] = p.clog()[j];
383         // log #nodes
384         for (j = 0; j < p.nlog().size(); j++)
385                 jvo["node"][j] = p.nlog()[j];
386         // log seconds
387         for (j = 0; j < p.slog().size(); j++)
388                 jvo["secs"][j] = p.slog()[j];
389         // log traj
390         i = 0;
391         j = 0;
392         for (auto traj: p.tlog()) {
393                 i = 0;
394                 for (auto n: traj) {
395                         jvo["traj"][j][i][0] = n->x();
396                         jvo["traj"][j][i][1] = n->y();
397                         jvo["traj"][j][i][2] = n->h();
398                         jvo["traj"][j][i][3] = n->t();
399                         jvo["traj"][j][i][4] = n->s();
400                         i++;
401                 }
402                 j++;
403         }
404 #ifdef JSONLOGEDGES
405         i = 0;
406         j = 0;
407         for (auto edges: p.rlog()) {
408                 j = 0;
409                 for (auto e: edges) {
410                         jvo["edge"][i][j][0][0] = e->init()->x();
411                         jvo["edge"][i][j][0][1] = e->init()->y();
412                         jvo["edge"][i][j][0][2] = e->init()->h();
413                         jvo["edge"][i][j][1][0] = e->goal()->x();
414                         jvo["edge"][i][j][1][1] = e->goal()->y();
415                         jvo["edge"][i][j][1][2] = e->goal()->h();
416                         j++;
417                 }
418                 i++;
419         }
420 #endif
421 #ifdef JSONLOGSAMPLES
422         i = 0;
423         j = 0;
424         for (auto s: p.samples()) {
425                 jvo["samp"][j][0] = s->x();
426                 jvo["samp"][j][1] = s->y();
427                 jvo["samp"][j][2] = s->h();
428                 j++;
429         }
430 #endif
431         // print output
432         std::cout << jvo << std::endl;
433
434 #ifdef USE_GL
435         SDL_DestroyWindow(gw);
436         SDL_Quit();
437 #endif
438
439         // free mem
440         for (auto o: so) {
441                 delete o.init();
442                 delete o.goal();
443         }
444         return 0;
445 }
446
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 }