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