]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/rrtbase.cc
Fix index computation, type
[hubacji1/iamcar.git] / base / rrtbase.cc
1 /*
2 This file is part of I am car.
3
4 I am car is free 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 <cmath>
20 #include <omp.h>
21 #include <queue>
22 #include "bcar.h"
23 #include "rrtbase.h"
24
25 #if USE_GL > 0
26 // OpenGL
27 #include <GL/gl.h>
28 #include <GL/glu.h>
29 #include <SDL2/SDL.h>
30 #endif
31
32 // RRT
33 #include "sample.h"
34 #include "cost.h"
35 #include "steer.h"
36 #include "nn.h"
37 #include "nv.h"
38
39 #if USE_GL > 0
40 extern SDL_Window* gw;
41 extern SDL_GLContext gc;
42 #endif
43
44 Cell::Cell()
45 {
46         pthread_mutex_init(&this->m_, NULL);
47 }
48
49 bool Cell::changed()
50 {
51         pthread_mutex_lock(&this->m_);
52         bool ret = this->changed_;
53         pthread_mutex_unlock(&this->m_);
54         return ret;
55 }
56
57 std::vector<RRTNode *> Cell::nodes()
58 {
59         pthread_mutex_lock(&this->m_);
60         std::vector<RRTNode *> ret(this->nodes_);
61         pthread_mutex_unlock(&this->m_);
62         return ret;
63 }
64
65 void Cell::add_node(RRTNode *n)
66 {
67         pthread_mutex_lock(&this->m_);
68         this->nodes_.push_back(n);
69         this->changed_ = true;
70         pthread_mutex_unlock(&this->m_);
71 }
72
73 RRTBase::~RRTBase()
74 {
75 // Fix heap-use-after-free error when T3 planner is used. If only T2 is used,
76 // please uncommend the following code:
77 //
78         for (auto n: this->nodes_)
79                 if (n != this->root_)
80                         delete n;
81         for (auto n: this->dnodes_)
82                 if (n != this->root_ && n != this->goal_)
83                         delete n;
84         for (auto s: this->samples_)
85                 if (s != this->goal_)
86                         delete s;
87         for (auto edges: this->rlog_)
88                 for (auto e: edges)
89                         delete e;
90         delete this->root_;
91         delete this->goal_;
92 }
93
94 RRTBase::RRTBase()
95         : root_(new RRTNode())
96         , goal_(new RRTNode())
97         , gen_(std::random_device{}())
98         , ndx_(HMAX - HMIN, (HMAX - HMIN) / 4)
99         , ndy_(VMAX - VMIN, (VMAX - VMIN) / 4)
100         , ndh_(0, M_PI * 2 / 4)
101 {
102         this->nodes_.reserve(NOFNODES);
103         this->nodes_.push_back(this->root_);
104         this->add_iy(this->root_);
105         this->add_ixy(this->root_);
106 }
107
108 RRTBase::RRTBase(RRTNode *init, RRTNode *goal)
109         : root_(init)
110         , goal_(goal)
111         , gen_(std::random_device{}())
112         , ndx_(HMIN + (HMAX - HMIN) / 2, (HMAX - HMIN) / 4)
113         , ndy_(VMIN + (VMAX - VMIN) / 2, (VMAX - VMIN) / 4)
114         , ndh_(0, M_PI * 2 / 4)
115 {
116         this->nodes_.reserve(NOFNODES);
117         this->nodes_.push_back(init);
118         this->add_iy(init);
119         this->add_ixy(init);
120 }
121
122 // getter
123 RRTNode *RRTBase::root()
124 {
125         return this->root_;
126 }
127
128 RRTNode *RRTBase::goal()
129 {
130         return this->goal_;
131 }
132
133 std::vector<RRTNode *> &RRTBase::goals()
134 {
135         return this->goals_;
136 }
137
138 std::vector<RRTNode *> &RRTBase::nodes()
139 {
140         return this->nodes_;
141 }
142
143 std::vector<RRTNode *> &RRTBase::dnodes()
144 {
145         return this->dnodes_;
146 }
147
148 std::queue<RRTNode *> &RRTBase::firsts()
149 {
150         return this->firsts_;
151 }
152
153 PolygonObstacle &RRTBase::frame()
154 {
155         return this->frame_;
156 }
157
158 std::vector<RRTNode *> &RRTBase::samples()
159 {
160         return this->samples_;
161 }
162
163 std::vector<CircleObstacle> *RRTBase::co()
164 {
165         return this->cobstacles_;
166 }
167
168 std::vector<SegmentObstacle> *RRTBase::so()
169 {
170         return this->sobstacles_;
171 }
172
173 std::vector<float> &RRTBase::clog()
174 {
175         return this->clog_;
176 }
177
178 std::vector<float> &RRTBase::nlog()
179 {
180         return this->nlog_;
181 }
182
183 std::vector<std::vector<RRTEdge *>> &RRTBase::rlog()
184 {
185         return this->rlog_;
186 }
187
188 std::vector<float> &RRTBase::slog()
189 {
190         return this->slog_;
191 }
192
193 std::vector<std::vector<RRTNode *>> &RRTBase::tlog()
194 {
195         return this->tlog_;
196 }
197
198 std::vector<RRTNode *> &RRTBase::slot_cusp()
199 {
200         return this->slot_cusp_;
201 }
202
203 bool RRTBase::goal_found()
204 {
205         return this->goal_found_;
206 }
207
208 float RRTBase::elapsed()
209 {
210         std::chrono::duration<float> dt;
211         dt = std::chrono::duration_cast<std::chrono::duration<float>>(
212                         this->tend_ - this->tstart_);
213         return dt.count();
214 }
215
216 std::vector<RRTNode *> RRTBase::traj_cusp()
217 {
218         std::vector<RRTNode *> tmp_cusps;
219         for (auto n: this->tlog().back()) {
220                 if (sgn(n->s()) == 0) {
221                         tmp_cusps.push_back(n);
222                 } else if (n->parent() &&
223                                 sgn(n->s()) != sgn(n->parent()->s())) {
224                         tmp_cusps.push_back(n);
225                         tmp_cusps.push_back(n->parent());
226                 }
227         }
228         std::vector<RRTNode *> cusps;
229         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
230                 if (tmp_cusps[i] != tmp_cusps[(i + 1) % tmp_cusps.size()])
231                         cusps.push_back(tmp_cusps[i]);
232         }
233         return cusps;
234 }
235
236 // setter
237 void RRTBase::root(RRTNode *node)
238 {
239         this->root_ = node;
240 }
241
242 void RRTBase::goal(RRTNode *node)
243 {
244         this->goal_ = node;
245 }
246
247 void RRTBase::goals(std::vector<RRTNode *> g)
248 {
249         this->goals_ = g;
250         std::reverse(this->goals_.begin(), this->goals_.end());
251         RRTNode *pn = this->goals_.front();
252         for (auto n: this->goals_) {
253                 if (n != pn) {
254                         pn->add_child(n, this->cost(pn ,n));
255                         pn = n;
256                 }
257         }
258 }
259
260 bool RRTBase::logr(RRTNode *root)
261 {
262         std::vector<RRTEdge *> e; // Edges to log
263         std::vector<RRTNode *> s; // DFS stack
264         std::vector<RRTNode *> r; // reset visited_
265         RRTNode *tmp;
266         s.push_back(root);
267         while (s.size() > 0) {
268                 tmp = s.back();
269                 s.pop_back();
270                 if (!tmp->visit()) {
271                         r.push_back(tmp);
272                         for (auto ch: tmp->children()) {
273                                 s.push_back(ch);
274                                 e.push_back(new RRTEdge(tmp, ch));
275                         }
276                 }
277         }
278         for (auto n: r)
279                 n->visit(false);
280         this->rlog_.push_back(e);
281         return true;
282 }
283
284 float RRTBase::ocost(RRTNode *n)
285 {
286         float dist = 9999;
287         for (auto o: *this->cobstacles_)
288                 if (o.dist_to(n) < dist)
289                         dist = o.dist_to(n);
290         for (auto o: *this->sobstacles_)
291                 if (o.dist_to(n) < dist)
292                         dist = o.dist_to(n);
293         return n->ocost(dist);
294 }
295
296 bool RRTBase::tlog(std::vector<RRTNode *> t)
297 {
298         if (t.size() > 0) {
299                 this->slog_.push_back(this->elapsed());
300                 this->clog_.push_back(t.front()->ccost() - t.back()->ccost());
301                 this->nlog_.push_back(this->nodes_.size());
302                 this->tlog_.push_back(t);
303                 return true;
304         } else {
305                 return false;
306         }
307 }
308
309 void RRTBase::tstart()
310 {
311         this->tstart_ = std::chrono::high_resolution_clock::now();
312 }
313
314 void RRTBase::tend()
315 {
316         this->tend_ = std::chrono::high_resolution_clock::now();
317 }
318
319 bool RRTBase::link_obstacles(
320                 std::vector<CircleObstacle> *cobstacles,
321                 std::vector<SegmentObstacle> *sobstacles)
322 {
323         this->cobstacles_ = cobstacles;
324         this->sobstacles_ = sobstacles;
325         if (!this->cobstacles_ || !this->sobstacles_) {
326                 return false;
327         }
328         return true;
329 }
330
331 bool RRTBase::add_iy(RRTNode *n)
332 {
333         int i = this->YI(n);
334         if (i < 0)
335                 i = 0;
336         if (i >= IYSIZE)
337                 i = IYSIZE - 1;
338         this->iy_[i].push_back(n);
339         return true;
340 }
341
342 bool RRTBase::add_ixy(RRTNode *n)
343 {
344         int ix = this->XI(n);
345         if (ix < 0)
346                 ix = 0;
347         if (ix >= IXSIZE)
348                 ix = IXSIZE - 1;
349         int iy = this->YI(n);
350         if (iy < 0)
351                 iy = 0;
352         if (iy >= IYSIZE)
353                 iy = IYSIZE - 1;
354         this->ixy_[ix][iy].add_node(n);
355         return true;
356 }
357
358 bool RRTBase::goal_found(bool f)
359 {
360         this->goal_found_ = f;
361         return f;
362 }
363
364 void RRTBase::slot_cusp(std::vector<RRTNode *> sc)
365 {
366         for (unsigned int i = 0; i < sc.size() - 1; i++)
367                 sc[i]->add_child(sc[i + 1], this->cost(sc[i], sc[i + 1]));
368         sc[0]->parent(this->goal());
369         this->slot_cusp_ = sc;
370 }
371
372 // other
373 bool RRTBase::glplot()
374 {
375 #if USE_GL > 0
376         glClear(GL_COLOR_BUFFER_BIT);
377         glLineWidth(1);
378         glPointSize(1);
379         // Plot obstacles
380         glBegin(GL_LINES);
381         for (auto o: *this->sobstacles_) {
382                 glColor3f(0, 0, 0);
383                 glVertex2f(GLVERTEX(o.init()));
384                 glVertex2f(GLVERTEX(o.goal()));
385         }
386         glEnd();
387         // Plot root, goal
388         glPointSize(8);
389         glBegin(GL_POINTS);
390         glColor3f(1, 0, 0);
391         glVertex2f(GLVERTEX(this->root_));
392         glVertex2f(GLVERTEX(this->goal_));
393         glEnd();
394         // Plot last sample
395         if (this->samples_.size() > 0) {
396                 glPointSize(8);
397                 glBegin(GL_POINTS);
398                 glColor3f(0, 1, 0);
399                 glVertex2f(GLVERTEX(this->samples_.back()));
400                 glEnd();
401         }
402         // Plot nodes (position, orientation
403         std::vector<RRTNode *> s; // DFS stack
404         std::vector<RRTNode *> r; // reset visited_
405         RRTNode *tmp;
406         glBegin(GL_LINES);
407         s.push_back(this->root_);
408         while (s.size() > 0) {
409                 tmp = s.back();
410                 s.pop_back();
411                 if (!tmp->visit()) {
412                         r.push_back(tmp);
413                         for (auto ch: tmp->children()) {
414                                 s.push_back(ch);
415                                 glColor3f(0.5, 0.5, 0.5);
416                                 BicycleCar bc(tmp->x(), tmp->y(), tmp->h());
417                                 glVertex2f(
418                                         bc.lfx() * GLPLWSCALE,
419                                         bc.lfy() * GLPLHSCALE
420                                 );
421                                 glVertex2f(
422                                         bc.lrx() * GLPLWSCALE,
423                                         bc.lry() * GLPLHSCALE
424                                 );
425                                 glVertex2f(
426                                         bc.lrx() * GLPLWSCALE,
427                                         bc.lry() * GLPLHSCALE
428                                 );
429                                 glVertex2f(
430                                         bc.rrx() * GLPLWSCALE,
431                                         bc.rry() * GLPLHSCALE
432                                 );
433                                 glVertex2f(
434                                         bc.rrx() * GLPLWSCALE,
435                                         bc.rry() * GLPLHSCALE
436                                 );
437                                 glVertex2f(
438                                         bc.rfx() * GLPLWSCALE,
439                                         bc.rfy() * GLPLHSCALE
440                                 );
441                         }
442                 }
443         }
444         glEnd();
445         // Plot nodes
446         glBegin(GL_LINES);
447         s.push_back(this->root_);
448         while (s.size() > 0) {
449                 tmp = s.back();
450                 s.pop_back();
451                 if (!tmp->visit()) {
452                         r.push_back(tmp);
453                         for (auto ch: tmp->children()) {
454                                 s.push_back(ch);
455                                 glColor3f(0.5, 0.5, 0.5);
456                                 glVertex2f(GLVERTEX(tmp));
457                                 glVertex2f(GLVERTEX(ch));
458                         }
459                 }
460         }
461         glEnd();
462         // Plot nodes (from goal)
463         glBegin(GL_LINES);
464         s.push_back(this->goal_);
465         while (s.size() > 0) {
466                 tmp = s.back();
467                 s.pop_back();
468                 if (!tmp->visit()) {
469                         r.push_back(tmp);
470                         for (auto ch: tmp->children()) {
471                                 s.push_back(ch);
472                                 glColor3f(0.5, 0.5, 0.5);
473                                 glVertex2f(GLVERTEX(tmp));
474                                 glVertex2f(GLVERTEX(ch));
475                         }
476                 }
477         }
478         glEnd();
479         std::vector<RRTNode *> cusps;
480         // Plot last trajectory
481         if (this->tlog().size() > 0) {
482                 glLineWidth(2);
483                 glBegin(GL_LINES);
484                 for (auto n: this->tlog().back()) {
485                         if (n->parent()) {
486                                 glColor3f(0, 0, 1);
487                                 glVertex2f(GLVERTEX(n));
488                                 glVertex2f(GLVERTEX(n->parent()));
489                                 if (sgn(n->s()) != sgn(n->parent()->s()))
490                                         cusps.push_back(n);
491                         }
492                 }
493                 glEnd();
494         }
495         // Plot cusps
496         glPointSize(8);
497         glBegin(GL_POINTS);
498         for (auto n: cusps) {
499                 glColor3f(0, 0, 1);
500                 glVertex2f(GLVERTEX(n));
501         }
502         glEnd();
503         SDL_GL_SwapWindow(gw);
504         for (auto n: r)
505                 n->visit(false);
506 #endif
507         return true;
508 }
509
510 bool RRTBase::goal_found(
511                 RRTNode *node,
512                 float (*cost)(RRTNode *, RRTNode* ))
513 {
514         if (GOAL_IS_NEAR(node, this->goal_)) {
515                 if (this->goal_found_) {
516                         if (node->ccost() + this->cost(node, this->goal_) <
517                                         this->goal_->ccost()) {
518                                 RRTNode *op; // old parent
519                                 float oc; // old cumulative cost
520                                 float od; // old direct cost
521                                 op = this->goal_->parent();
522                                 oc = this->goal_->ccost();
523                                 od = this->goal_->dcost();
524                                 node->add_child(this->goal_,
525                                                 this->cost(node, this->goal_));
526                                 if (this->collide(node, this->goal_)) {
527                                         node->children().pop_back();
528                                         this->goal_->parent(op);
529                                         this->goal_->ccost(oc);
530                                         this->goal_->dcost(od);
531                                 } else {
532                                         op->rem_child(this->goal_);
533                                         return true;
534                                 }
535                         } else {
536                                 return false;
537                         }
538                 } else {
539                         node->add_child(
540                                         this->goal_,
541                                         this->cost(node, this->goal_));
542                         if (this->collide(node, this->goal_)) {
543                                 node->children().pop_back();
544                                 this->goal_->remove_parent();
545                                 return false;
546                         }
547                         this->goal_found_ = true;
548                         // Update ccost of goal's parents
549                         if (this->goals().size() > 0) {
550                                 RRTNode *ch = this->goals().back();
551                                 RRTNode *pn = this->goals().back()->parent();
552                                 while (pn) {
553                                         pn->ccost(
554                                                 ch->ccost()
555                                                 - this->cost(pn, ch)
556                                         );
557                                         ch = pn;
558                                         pn = pn->parent();
559                                 }
560                         }
561                         return true;
562                 }
563         }
564         return false;
565 }
566
567 bool RRTBase::goal_found(
568         RRTNode *node,
569         RRTNode *goal
570 )
571 {
572         if (GOAL_IS_NEAR(node, goal)) {
573                 if (this->goal_found_) {
574                         if (
575                                 goal->ccost() != -1
576                                 && node->ccost() + this->cost(node, goal)
577                                 < goal->ccost()
578                         ) {
579                                 RRTNode *op; // old parent
580                                 float oc; // old cumulative cost
581                                 float od; // old direct cost
582                                 op = goal->parent();
583                                 oc = goal->ccost();
584                                 od = goal->dcost();
585                                 node->add_child(goal,
586                                                 this->cost(node, goal));
587                                 if (this->collide(node, goal)) {
588                                         node->children().pop_back();
589                                         goal->parent(op);
590                                         goal->ccost(oc);
591                                         goal->dcost(od);
592                                 } else {
593                                         op->rem_child(goal);
594                                         return true;
595                                 }
596                         } else {
597                                 return false;
598                         }
599                 } else {
600                         node->add_child(
601                                 goal,
602                                 this->cost(node, goal)
603                         );
604                         if (this->collide(node, goal)) {
605                                 node->children().pop_back();
606                                 goal->remove_parent();
607                                 return false;
608                         }
609                         this->goal_found_ = true;
610                         // Update ccost of goal's children
611                         goal->update_ccost();
612                         // Update ccost of goals
613                         for (auto g: this->goals()) {
614                                 if (g == goal)
615                                         break;
616                                 g->ccost(-1);
617                         }
618                         return true;
619                 }
620         }
621         return false;
622 }
623
624 bool RRTBase::collide(RRTNode *init, RRTNode *goal)
625 {
626         std::vector<RRTEdge *> edges;
627         RRTNode *tmp = goal;
628         volatile bool col = false;
629         unsigned int i;
630         while (tmp != init) {
631                 BicycleCar bc(tmp->x(), tmp->y(), tmp->h());
632                 std::vector<RRTEdge *> bcframe = bc.frame();
633                 #pragma omp parallel for reduction(|: col)
634                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
635                         if ((*this->cobstacles_)[i].collide(tmp)) {
636                                 col = true;
637                         }
638                         for (auto &e: bcframe) {
639                                 if ((*this->cobstacles_)[i].collide(e)) {
640                                         col = true;
641                                 }
642                         }
643                 }
644                 if (col) {
645                         for (auto e: bcframe) {
646                                 delete e->init();
647                                 delete e->goal();
648                                 delete e;
649                         }
650                         for (auto e: edges) {
651                                 delete e;
652                         }
653                         return true;
654                 }
655                 #pragma omp parallel for reduction(|: col)
656                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
657                         for (auto &e: bcframe) {
658                                 if ((*this->sobstacles_)[i].collide(e)) {
659                                         col = true;
660                                 }
661                         }
662                 }
663                 if (col) {
664                         for (auto e: bcframe) {
665                                 delete e->init();
666                                 delete e->goal();
667                                 delete e;
668                         }
669                         for (auto e: edges) {
670                                 delete e;
671                         }
672                         return true;
673                 }
674                 if (!tmp->parent()) {
675                         break;
676                 }
677                 edges.push_back(new RRTEdge(tmp, tmp->parent()));
678                 tmp = tmp->parent();
679                 for (auto e: bcframe) {
680                         delete e->init();
681                         delete e->goal();
682                         delete e;
683                 }
684         }
685         for (auto &e: edges) {
686                 #pragma omp parallel for reduction(|: col)
687                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
688                         if ((*this->cobstacles_)[i].collide(e)) {
689                                 col = true;
690                         }
691                 }
692                 if (col) {
693                         for (auto e: edges) {
694                                 delete e;
695                         }
696                         return true;
697                 }
698                 #pragma omp parallel for reduction(|: col)
699                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
700                         if ((*this->sobstacles_)[i].collide(e)) {
701                                 col = true;
702                         }
703                 }
704                 if (col) {
705                         for (auto e: edges) {
706                                 delete e;
707                         }
708                         return true;
709                 }
710         }
711         for (auto e: edges) {
712                 delete e;
713         }
714         return false;
715 }
716
717 class RRTNodeDijkstra {
718         public:
719                 RRTNodeDijkstra(int i):
720                         ni(i),
721                         pi(0),
722                         c(9999),
723                         v(false)
724                 {};
725                 RRTNodeDijkstra(int i, float c):
726                         ni(i),
727                         pi(0),
728                         c(c),
729                         v(false)
730                 {};
731                 RRTNodeDijkstra(int i, int p, float c):
732                         ni(i),
733                         pi(p),
734                         c(c),
735                         v(false)
736                 {};
737                 unsigned int ni;
738                 unsigned int pi;
739                 float c;
740                 bool v;
741                 bool vi()
742                 {
743                         if (this->v)
744                                 return true;
745                         this->v = true;
746                         return false;
747                 };
748 };
749
750 class RRTNodeDijkstraComparator {
751         public:
752                 int operator() (
753                                 const RRTNodeDijkstra& n1,
754                                 const RRTNodeDijkstra& n2)
755                 {
756                         return n1.c > n2.c;
757                 }
758 };
759
760 bool RRTBase::optp_dijkstra(
761                 std::vector<RRTNode *> &cusps,
762                 std::vector<int> &npi)
763 {
764         std::vector<RRTNodeDijkstra> dnodes;
765         for (unsigned int i = 0; i < cusps.size(); i++)
766                 if (i > 0)
767                         dnodes.push_back(RRTNodeDijkstra(
768                                                 i,
769                                                 i - 1,
770                                                 cusps[i]->ccost()));
771                 else
772                         dnodes.push_back(RRTNodeDijkstra(
773                                                 i,
774                                                 cusps[i]->ccost()));
775         dnodes[0].vi();
776         std::priority_queue<
777                 RRTNodeDijkstra,
778                 std::vector<RRTNodeDijkstra>,
779                 RRTNodeDijkstraComparator> pq;
780         RRTNodeDijkstra tmp = dnodes[0];
781         pq.push(tmp);
782         float ch_cost = 9999;
783         std::vector<RRTNode *> steered;
784         while (!pq.empty()) {
785                 tmp = pq.top();
786                 pq.pop();
787                 for (unsigned int i = tmp.ni + 1; i < cusps.size(); i++) {
788                         ch_cost = dnodes[tmp.ni].c +
789                                 this->cost(cusps[tmp.ni], cusps[i]);
790                         steered = this->steer(cusps[tmp.ni], cusps[i]);
791                         if (steered.size() <= 0)
792                                 break;
793                         for (unsigned int j = 0; j < steered.size() - 1; j++)
794                                 steered[j]->add_child(steered[j + 1], 1);
795                         if (this->collide(
796                                         steered[0],
797                                         steered[steered.size() - 1])) {
798                                 for (auto n: steered)
799                                         delete n;
800                                 continue;
801                         }
802                         if (ch_cost < dnodes[i].c) {
803                                 dnodes[i].c = ch_cost;
804                                 dnodes[i].pi = tmp.ni;
805                                 if (!dnodes[i].vi())
806                                         pq.push(dnodes[i]);
807                         }
808                         for (auto n: steered)
809                                 delete n;
810                 }
811         }
812         unsigned int tmpi = 0;
813         for (auto n: dnodes) {
814                 if (n.v && n.ni > tmpi)
815                         tmpi = n.ni;
816         }
817         while (tmpi > 0) {
818                 npi.push_back(tmpi);
819                 tmpi = dnodes[tmpi].pi;
820         }
821         npi.push_back(tmpi);
822         std::reverse(npi.begin(), npi.end());
823         return true;
824 }
825
826 bool RRTBase::optp_rrp(
827                 std::vector<RRTNode *> &cusps,
828                 std::vector<int> &npi)
829 {
830         std::vector<RRTNode *> steered;
831         std::vector<int> candidates;
832         RRTNode *x_j = nullptr;
833         RRTNode *x_i = nullptr;
834         int j = cusps.size() - 1;
835         int i_min = 0;
836         float c_min = 0;
837         float cost = 0;
838         float dx = 0;
839         float dy = 0;
840         float ed = 0;
841         float th_i = 0;
842         float th_j = 0;
843         while (j > 0) {
844                 npi.push_back(j);
845                 steered.clear();
846                 candidates.clear();
847                 x_j = cusps[j];
848                 for (int i = 0; i < j; i++) {
849                         steered = this->steer(cusps[i], x_j);
850                         for (unsigned int k = 0; k < steered.size() - 1; k++)
851                                 steered[k]->add_child(steered[k + 1], 1);
852                         if (!this->collide(
853                                         steered[0],
854                                         steered[steered.size() - 1]))
855                                 candidates.push_back(i);
856                 }
857                 if (candidates.size() <= 0)
858                         return false;
859                 i_min = candidates[0];
860                 x_i = cusps[i_min];
861                 c_min = 9999;
862                 for (auto c: candidates) {
863                         x_i = cusps[c];
864                         dx = x_j->x() - x_i->x();
865                         dy = x_j->y() - x_i->y();
866                         ed = EDIST(x_i, x_j);
867                         th_i = (cos(x_i->h()) * dx + sin(x_i->h()) * dy) / ed;
868                         th_j = (cos(x_j->h()) * dx + sin(x_j->h()) * dy) / ed;
869                         cost = th_i + th_j;
870                         if (cost < c_min) {
871                                 i_min = c;
872                                 c_min = cost;
873                         }
874                 }
875                 j = i_min;
876
877         }
878         npi.push_back(j);
879         std::reverse(npi.begin(), npi.end());
880         return true;
881 }
882
883 bool RRTBase::optp_smart(
884                 std::vector<RRTNode *> &cusps,
885                 std::vector<int> &npi)
886 {
887         std::vector<RRTNode *> steered;
888         int li = cusps.size() - 1;
889         int ai = li - 1;
890         npi.push_back(li);
891         while (ai > 1) {
892                 steered = this->steer(cusps[ai - 1], cusps[li]);
893                 for (unsigned int j = 0; j < steered.size() - 1; j++)
894                         steered[j]->add_child(steered[j + 1], 1);
895                 if (this->collide(steered[0], steered[steered.size() - 1])) {
896                         npi.push_back(ai);
897                         li = ai;
898                 }
899                 ai--;
900                 for (auto n: steered)
901                         delete n;
902         }
903         npi.push_back(0);
904         std::reverse(npi.begin(), npi.end());
905         return true;
906 }
907
908 bool RRTBase::opt_path()
909 {
910         if (this->tlog().size() == 0)
911                 return false;
912         float oc = this->tlog().back().front()->ccost();
913         std::vector<RRTNode *> tmp_cusps;
914         for (auto n: this->tlog().back()) {
915                 if (sgn(n->s()) == 0) {
916                         tmp_cusps.push_back(n);
917                 } else if (n->parent() &&
918                                 sgn(n->s()) != sgn(n->parent()->s())) {
919                         tmp_cusps.push_back(n);
920                         tmp_cusps.push_back(n->parent());
921                 }
922                 //tmp_cusps.push_back(n);
923         }
924         if (tmp_cusps.size() < 2)
925                 return false;
926         std::vector<RRTNode *> cusps;
927         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
928                 if (!IS_NEAR(
929                         tmp_cusps[i],
930                         tmp_cusps[(i + 1) % tmp_cusps.size()]
931                 ))
932                         cusps.push_back(tmp_cusps[i]);
933         }
934         std::reverse(cusps.begin(), cusps.end());
935         std::vector<int> npi; // new path indexes
936         if (!this->optp_dijkstra(cusps, npi))
937                 return false;
938         RRTNode *pn = cusps[npi[0]];
939         RRTNode *tmp = nullptr;
940         bool en_add = true;
941         for (unsigned int i = 0; i < npi.size() - 1; i++) {
942                 pn = cusps[npi[i]];
943                 for (auto ns: this->steer(cusps[npi[i]], cusps[npi[i + 1]])) {
944                         if (!en_add) {
945                                 delete ns;
946                         } else if (IS_NEAR(cusps[npi[i]], ns)) {
947                                 tmp = ns;
948                                 while (tmp && tmp != cusps[npi[i]]) {
949                                         pn = tmp->parent();
950                                         delete tmp;
951                                         tmp = pn;
952                                 }
953                                 pn = cusps[npi[i]];
954                         } else if (IS_NEAR(ns, cusps[npi[i + 1]])) {
955                                 delete ns;
956                                 cusps[npi[i + 1]]->parent()->rem_child(
957                                                 cusps[npi[i + 1]]);
958                                 pn->add_child(
959                                         cusps[npi[i + 1]],
960                                         this->cost(pn, cusps[npi[i + 1]]));
961                                 en_add = false;
962                         } else if (IS_NEAR(pn, ns)) {
963                                 delete ns;
964                         } else {
965                                 this->nodes().push_back(ns);
966                                 this->add_iy(ns);
967                                 this->add_ixy(ns);
968                                 pn->add_child(ns, this->cost(pn, ns));
969                                 pn = ns;
970                         }
971                 }
972         }
973         this->root()->update_ccost();
974         if (this->tlog().back().front()->ccost() < oc)
975                 return true;
976         return false;
977 }
978
979 bool RRTBase::rebase(RRTNode *nr)
980 {
981         if (!nr || this->goal_ == nr || this->root_ == nr)
982                 return false;
983         std::vector<RRTNode *> s; // DFS stack
984         RRTNode *tmp;
985         unsigned int i = 0;
986         unsigned int to_del = 0;
987         int iy = 0;
988         s.push_back(this->root_);
989         while (s.size() > 0) {
990                 tmp = s.back();
991                 s.pop_back();
992                 for (auto ch: tmp->children()) {
993                         if (ch != nr)
994                                 s.push_back(ch);
995                 }
996                 to_del = this->nodes_.size();
997                 #pragma omp parallel for reduction(min: to_del)
998                 for (i = 0; i < this->nodes_.size(); i++) {
999                         if (this->nodes_[i] == tmp)
1000                                 to_del = i;
1001                 }
1002                 if (to_del < this->nodes_.size())
1003                         this->nodes_.erase(this->nodes_.begin() + to_del);
1004                 iy = this->YI(tmp);
1005                 to_del = this->iy_[iy].size();
1006                 #pragma omp parallel  for reduction(min: to_del)
1007                 for (i = 0; i < this->iy_[iy].size(); i++) {
1008                         if (this->iy_[iy][i] == tmp)
1009                                 to_del = i;
1010                 }
1011                 if (to_del < this->iy_[iy].size())
1012                         this->iy_[iy].erase(this->iy_[iy].begin() + to_del);
1013                 this->dnodes().push_back(tmp);
1014         }
1015         this->root_ = nr;
1016         this->root_->remove_parent();
1017         return true;
1018 }
1019
1020 std::vector<RRTNode *> RRTBase::findt()
1021 {
1022         return this->findt(this->goal_);
1023 }
1024
1025 std::vector<RRTNode *> RRTBase::findt(RRTNode *n)
1026 {
1027         std::vector<RRTNode *> nodes;
1028         if (!n || !n->parent())
1029                 return nodes;
1030         while (n) {
1031                 nodes.push_back(n);
1032                 n = n->parent();
1033         }
1034         return nodes;
1035 }
1036
1037 int RRTBase::XI(RRTNode *n)
1038 {
1039         float step = (this->HMAX - this->HMIN) / IXSIZE;
1040         float index = (int) (floor(n->x() - this->HMIN) / step);
1041         return index;
1042 }
1043
1044 int RRTBase::YI(RRTNode *n)
1045 {
1046         float step = (this->VMAX - this->VMIN) / IYSIZE;
1047         float index = (int) (floor(n->y() - this->VMIN) / step);
1048         return index;
1049 }
1050
1051 // RRT Framework
1052 void RRTBase::setSamplingInfo(SamplingInfo si)
1053 {
1054         this->ndx_ = std::normal_distribution<float>(si.x0, si.x);
1055         this->ndy_ = std::normal_distribution<float>(si.y0, si.y);
1056         this->ndh_ = std::normal_distribution<float>(si.h0, si.h);
1057 }
1058
1059 RRTNode *RRTBase::sample()
1060 {
1061         float x = this->ndx_(this->gen_);
1062         float y = this->ndy_(this->gen_);
1063         float h = this->ndh_(this->gen_);
1064         return new RRTNode(x, y, h);
1065 }
1066
1067 float RRTBase::cost(RRTNode *init, RRTNode *goal)
1068 {
1069         return co2(init, goal);
1070 }
1071
1072 RRTNode *RRTBase::nn(RRTNode *rs)
1073 {
1074         int iy = this->YI(rs);
1075         struct mcnn nn;
1076         nn.nn = nullptr;
1077         nn.mc = 9999;
1078         unsigned int i = 0; // vector step
1079         unsigned int j = 0; // array step
1080         int iyj = 0;
1081         while (nn.mc > j * IYSTEP) {
1082                 iyj = (int) (iy + j);
1083                 if (iyj >= IYSIZE)
1084                         iyj = IYSIZE - 1;
1085                 #pragma omp parallel for reduction(minn: nn)
1086                 for (i = 0; i < this->iy_[iyj].size(); i++) {
1087                         if (EDIST(this->iy_[iyj][i], rs) < nn.mc) {
1088                                 nn.mc = EDIST(this->iy_[iyj][i], rs);
1089                                 nn.nn = this->iy_[iyj][i];
1090                         }
1091                 }
1092                 if (j > 0) {
1093                         iyj = (int) (iy - j);
1094                         if (iyj < 0)
1095                                 iyj = 0;
1096                         #pragma omp parallel for reduction(minn: nn)
1097                         for (i = 0; i < this->iy_[iyj].size(); i++) {
1098                                 if (EDIST(this->iy_[iyj][i], rs) < nn.mc) {
1099                                         nn.mc = EDIST(this->iy_[iyj][i], rs);
1100                                         nn.nn = this->iy_[iyj][i];
1101                                 }
1102                         }
1103                 }
1104                 j++;
1105         }
1106         return nn.nn;
1107 }
1108
1109 std::vector<RRTNode *> RRTBase::nv(RRTNode *node, float dist)
1110 {
1111         std::vector<RRTNode *> nvs;
1112         unsigned int iy = this->YI(node);
1113         unsigned int iy_dist = floor(dist / IYSTEP) + 1;
1114         unsigned int i = 0; // vector index
1115         unsigned int j = 0; // array index
1116         unsigned int jmin = 0; // minimal j index
1117         unsigned int jmax = 0; // maximal j index
1118         jmin = iy - iy_dist;
1119         jmin = (jmin > 0) ? jmin : 0;
1120         jmax = iy + iy_dist + 1;
1121         jmax = (jmax < IYSIZE) ? jmax : IYSIZE;
1122         #pragma omp parallel for reduction(merge: nvs)
1123         for (j = jmin; j < jmax; j++) {
1124                 #pragma omp parallel for reduction(merge: nvs)
1125                 for (i = 0; i < this->iy_[j].size(); i++) {
1126                         if (this->cost(this->iy_[j][i], node) < dist) {
1127                                 nvs.push_back(this->iy_[j][i]);
1128                         }
1129                 }
1130         }
1131         return nvs;
1132 }
1133
1134 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal)
1135 {
1136         return st3(init, goal);
1137 }
1138
1139 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal, float step)
1140 {
1141         return st3(init, goal, step);
1142 }