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