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