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