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