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