Building.cpp 68.4 KB
Newer Older
1
/**
Weichen's avatar
Weichen committed
2 3
 * \file        Building.cpp
 * \date        Oct 1, 2014
4 5
 * \version     v0.7
 * \copyright   <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved.
Ulrich Kemloh's avatar
Ulrich Kemloh committed
6
 *
Weichen's avatar
Weichen committed
7
 * \section License
8 9 10
 * This file is part of JuPedSim.
 *
 * JuPedSim is free software: you can redistribute it and/or modify
Weichen's avatar
Weichen committed
11
 * it under the terms of the GNU Lesser General Public License as published by
12 13 14 15 16 17 18 19
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * JuPedSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
Weichen's avatar
Weichen committed
20
 * You should have received a copy of the GNU Lesser General Public License
21 22
 * along with JuPedSim. If not, see <http://www.gnu.org/licenses/>.
 *
Weichen's avatar
Weichen committed
23
 * \section Description
24 25
 *
 *
Weichen's avatar
Weichen committed
26 27
 **/

28
#include <chrono>
Ulrich Kemloh's avatar
Ulrich Kemloh committed
29
#include "Building.h"
GrgrLmml's avatar
GrgrLmml committed
30

Ulrich Kemloh's avatar
Ulrich Kemloh committed
31
#include "../geometry/SubRoom.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
32
#include "../tinyxml/tinyxml.h"
33 34

#ifdef _SIMULATOR
GrgrLmml's avatar
GrgrLmml committed
35 36

#include "GeometryReader.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
37 38
#include "../pedestrian/Pedestrian.h"
#include "../mpi/LCGrid.h"
GrgrLmml's avatar
GrgrLmml committed
39
#include "../IO/GeoFileParser.h"
Mohcine Chraibi's avatar
Mohcine Chraibi committed
40
#include <filesystem>
tobias schroedter's avatar
tobias schroedter committed
41
#include <thread>         // std::thread, std::thread::id, std::this_thread::get_id
Mohcine Chraibi's avatar
Mohcine Chraibi committed
42 43

namespace fs = std::filesystem;
GrgrLmml's avatar
GrgrLmml committed
44

45
#endif
46
//#undef _OPENMP
Ulrich Kemloh's avatar
Ulrich Kemloh committed
47 48

#ifdef _OPENMP
GrgrLmml's avatar
GrgrLmml committed
49

50
#else
Mohcine Chraibi's avatar
Mohcine Chraibi committed
51 52
#define omp_get_thread_num()    0
#define omp_get_max_threads()   1
Ulrich Kemloh's avatar
Ulrich Kemloh committed
53
#endif
54
#define DEBUG 0
Ulrich Kemloh's avatar
Ulrich Kemloh committed
55

56
using namespace std;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
57

58 59
Building::Building()
{
60 61 62 63 64
      _caption = "no_caption";
      _geometryFilename = "";
      _routingEngine = nullptr;
      _linkedCellGrid = nullptr;
      _savePathway = false;
65
}
Ulrich Kemloh's avatar
Ulrich Kemloh committed
66

67
#ifdef _SIMULATOR
GrgrLmml's avatar
GrgrLmml committed
68

Arne Graf's avatar
Arne Graf committed
69
Building::Building(Configuration* configuration, PedDistributor& pedDistributor)
70 71 72 73
:_configuration(configuration),
      _routingEngine(
            configuration->GetRoutingEngine()),
      _caption("no_caption")
Oliver Schmidts's avatar
Oliver Schmidts committed
74
{
75 76
      _savePathway = false;
      _linkedCellGrid = nullptr;
77

GrgrLmml's avatar
GrgrLmml committed
78
#ifdef _JPS_AS_A_SERVICE
79 80 81 82 83
      if (_configuration->GetRunAsService()) {
            std::unique_ptr<GeometryFromProtobufLoader> parser(new GeometryFromProtobufLoader(_configuration));
            parser->LoadBuilding(this);
      }
      else
GrgrLmml's avatar
GrgrLmml committed
84
#endif
85 86 87 88
      {
            std::unique_ptr<GeoFileParser> parser(new GeoFileParser(_configuration));
            parser->LoadBuilding(this);
      }
89

90 91 92 93
      if (!InitGeometry()) {
            Log->Write("ERROR:\t could not initialize the geometry!");
            exit(EXIT_FAILURE);
      }
94

95

96

97 98
      //TODO: check whether traffic info can be loaded before InitGeometry if so call it in LoadBuilding instead and make
      //TODO: LoadTrafficInfo private [gl march '16]
GrgrLmml's avatar
GrgrLmml committed
99

100

101 102 103 104 105
      if (!pedDistributor.Distribute(this)) {
            Log->Write("ERROR:\tcould not distribute the pedestrians\n");
            exit(EXIT_FAILURE);
      }
      InitGrid();
106

107 108 109 110
      if (!_routingEngine->Init(this)) {
            Log->Write("ERROR:\t could not initialize the routers!");
            exit(EXIT_FAILURE);
      }
111

112 113 114 115
      if (!SanityCheck()) {
            Log->Write("ERROR:\t There are sanity errors in the geometry file");
            exit(EXIT_FAILURE);
      }
116

GrgrLmml's avatar
GrgrLmml committed
117
//     SaveGeometry("/home/laemmel/Desktop/geo.xml");
Oliver Schmidts's avatar
Oliver Schmidts committed
118
}
GrgrLmml's avatar
GrgrLmml committed
119

120
#endif
Ulrich Kemloh's avatar
Ulrich Kemloh committed
121

122 123
Building::~Building()
{
124 125 126
      //
      // for (int i = 0; i < GetNumberOfRooms(); i++)
      //    delete _rooms[i];
Ulrich Kemloh's avatar
Ulrich Kemloh committed
127

128
#ifdef _SIMULATOR
129 130 131 132 133
      for (unsigned int p = 0; p<_allPedestians.size(); p++) {
            delete _allPedestians[p];
      }
      _allPedestians.clear();
      delete _linkedCellGrid;
134
#endif
Ulrich Kemloh's avatar
Ulrich Kemloh committed
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
      if (_pathWayStream.is_open())
            _pathWayStream.close();

      for (map<int, Crossing*>::const_iterator iter = _crossings.begin();
           iter!=_crossings.end(); ++iter) {
            delete iter->second;
      }
      for (map<int, Transition*>::const_iterator iter = _transitions.begin();
           iter!=_transitions.end(); ++iter) {
            delete iter->second;
      }
      for (map<int, Hline*>::const_iterator iter = _hLines.begin();
           iter!=_hLines.end(); ++iter) {
            delete iter->second;
      }
      for (map<int, Goal*>::const_iterator iter = _goals.begin();
           iter!=_goals.end(); ++iter) {
            delete iter->second;
      }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
155 156
}

Arne Graf's avatar
Arne Graf committed
157
Configuration* Building::GetConfig() const {
158
      return _configuration;
Arne Graf's avatar
Arne Graf committed
159 160
}

GrgrLmml's avatar
GrgrLmml committed
161 162 163
///************************************************************
// setters
// ************************************************************/
164 165
void Building::SetCaption(const std::string& s)
{
166
      _caption = s;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
167 168 169
}

/*************************************************************
GrgrLmml's avatar
GrgrLmml committed
170
 getters
171
************************************************************/
Ulrich Kemloh's avatar
Ulrich Kemloh committed
172

173 174
string Building::GetCaption() const
{
175
      return _caption;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
176 177
}

178 179
RoutingEngine* Building::GetRoutingEngine() const
{
180
      return _configuration->GetRoutingEngine().get();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
181 182
}

183 184
int Building::GetNumberOfRooms() const
{
185
      return (int) _rooms.size();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
186 187
}

188 189
int Building::GetNumberOfGoals() const
{
190
      return (int) (_transitions.size()+_hLines.size()+_crossings.size());
191 192
}

193
const std::map<int, std::shared_ptr<Room> >& Building::GetAllRooms() const
194
{
195
      return _rooms;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
196 197
}

198 199
Room* Building::GetRoom(int index) const
{
200 201 202 203 204 205 206 207
      //todo: obsolete since the check is done by .at()
      if (_rooms.count(index)==0) {
            Log->Write("ERROR: Wrong 'index' in CBuiling::GetRoom() Room ID: %d size: %d", index, _rooms.size());
            Log->Write("\tControl your rooms ID and make sure they are in the order 0, 1, 2,.. ");
            return nullptr;
      }
      //return _rooms[index];
      return _rooms.at(index).get();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
208 209
}

210 211
LCGrid* Building::GetGrid() const
{
212
      return _linkedCellGrid;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
213 214
}

215 216
void Building::AddRoom(Room* room)
{
217
      _rooms[room->GetID()] = std::shared_ptr<Room>(room);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
218 219
}

220 221
void Building::AddSurroundingRoom()
{
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      Log->Write("INFO: \tAdding the room 'outside' ");
      // first look for the geometry boundaries
      double x_min = FLT_MAX;
      double x_max = -FLT_MAX;
      double y_min = FLT_MAX;
      double y_max = -FLT_MAX;
      //finding the bounding of the grid
      // and collect the pedestrians

      for (auto&& itr_room: _rooms) {
            for (auto&& itr_subroom: itr_room.second->GetAllSubRooms()) {
                  for (auto&& wall:itr_subroom.second->GetAllWalls()) {
                        double x1 = wall.GetPoint1()._x;
                        double y1 = wall.GetPoint1()._y;
                        double x2 = wall.GetPoint2()._x;
                        double y2 = wall.GetPoint2()._y;

                        double xmax = (x1>x2) ? x1 : x2;
                        double xmin = (x1>x2) ? x2 : x1;
                        double ymax = (y1>y2) ? y1 : y2;
                        double ymin = (y1>y2) ? y2 : y1;

                        x_min = (xmin<=x_min) ? xmin : x_min;
                        x_max = (xmax>=x_max) ? xmax : x_max;
                        y_max = (ymax>=y_max) ? ymax : y_max;
                        y_min = (ymin<=y_min) ? ymin : y_min;
                  }
            }
      }

      for (auto&& itr_goal:_goals) {
            for (auto&& wall: itr_goal.second->GetAllWalls()) {
                  double x1 = wall.GetPoint1()._x;
                  double y1 = wall.GetPoint1()._y;
                  double x2 = wall.GetPoint2()._x;
                  double y2 = wall.GetPoint2()._y;

                  double xmax = (x1>x2) ? x1 : x2;
                  double xmin = (x1>x2) ? x2 : x1;
                  double ymax = (y1>y2) ? y1 : y2;
                  double ymin = (y1>y2) ? y2 : y1;

                  x_min = (xmin<=x_min) ? xmin : x_min;
                  x_max = (xmax>=x_max) ? xmax : x_max;
                  y_max = (ymax>=y_max) ? ymax : y_max;
                  y_min = (ymin<=y_min) ? ymin : y_min;
            }
      }
      //make the grid slightly larger.
      x_min = x_min-10.0;
      x_max = x_max+10.0;
      y_min = y_min-10.0;
      y_max = y_max+10.0;

      SubRoom* bigSubroom = new NormalSubRoom();
      bigSubroom->SetRoomID((int) _rooms.size());
      bigSubroom->SetSubRoomID(0); // should be the single subroom
      bigSubroom->AddWall(Wall(Point(x_min, y_min), Point(x_min, y_max)));
      bigSubroom->AddWall(Wall(Point(x_min, y_max), Point(x_max, y_max)));
      bigSubroom->AddWall(Wall(Point(x_max, y_max), Point(x_max, y_min)));
      bigSubroom->AddWall(Wall(Point(x_max, y_min), Point(x_min, y_min)));

      Room* bigRoom = new Room();
      bigRoom->AddSubRoom(bigSubroom);
      bigRoom->SetCaption("outside");
      bigRoom->SetID((int) _rooms.size());
      AddRoom(bigRoom);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
289 290
}

291
bool Building::InitGeometry()
292
{
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
      Log->Write("INFO: \tInit Geometry");
      correct();
      for (auto&& itr_room: _rooms) {
            for (auto&& itr_subroom: itr_room.second->GetAllSubRooms()) {
                  //create a close polyline out of everything
                  vector<Line*> goals = vector<Line*>();

                  //  collect all crossings
                  for (auto&& cros:itr_subroom.second->GetAllCrossings()) {
                        goals.push_back(cros);
                  }
                  //collect all transitions
                  for (auto&& trans:itr_subroom.second->GetAllTransitions()) {
                        goals.push_back(trans);
                  }
                  // initialize the poly
                  if (!itr_subroom.second->ConvertLineToPoly(goals))
                        return false;
                  itr_subroom.second->CalculateArea();

                  //do the same for the obstacles that are closed
                  for (auto&& obst:itr_subroom.second->GetAllObstacles()) {
                        //if (obst->GetClosed() == 1)
                        if (!obst->ConvertLineToPoly())
                              return false;
                  }

                  //here we can create a boost::geometry::model::polygon out of the vector<Point> objects created above
                  itr_subroom.second->CreateBoostPoly();

                  double minElevation = FLT_MAX;
                  double maxElevation = -FLT_MAX;
                  for (auto&& wall:itr_subroom.second->GetAllWalls()) {
                        const Point& P1 = wall.GetPoint1();
                        const Point& P2 = wall.GetPoint2();
                        if (minElevation>itr_subroom.second->GetElevation(P1)) {
                              minElevation = itr_subroom.second->GetElevation(P1);
                        }

                        if (maxElevation<itr_subroom.second->GetElevation(P1)) {
                              maxElevation = itr_subroom.second->GetElevation(P1);
                        }

                        if (minElevation>itr_subroom.second->GetElevation(P2)) {
                              minElevation = itr_subroom.second->GetElevation(P2);
                        }

                        if (maxElevation<itr_subroom.second->GetElevation(P2)) {
                              maxElevation = itr_subroom.second->GetElevation(P2);
                        }
                  }
                  itr_subroom.second->SetMaxElevation(maxElevation);
                  itr_subroom.second->SetMinElevation(minElevation);
            }
      }


      // look and save the neighbor subroom for improving the runtime
      // that information is already present in the crossing/transitions

      for (const auto& cross: _crossings) {
            SubRoom* s1 = cross.second->GetSubRoom1();
            SubRoom* s2 = cross.second->GetSubRoom2();
            if (s1) s1->AddNeighbor(s2);
            if (s2) s2->AddNeighbor(s1);
      }

      for (const auto& trans: _transitions) {
            SubRoom* s1 = trans.second->GetSubRoom1();
            SubRoom* s2 = trans.second->GetSubRoom2();
            if (s1) s1->AddNeighbor(s2);
            if (s2) s2->AddNeighbor(s1);
      }

      InitInsideGoals();
      InitPlatforms();
      //---
      for (auto platform: _platforms)
      {
            std::cout << "\n platform " << platform.first << ", "<< platform.second->id << "\n";
            std::cout <<  "\t rid " << platform.second->rid << "\n";
            auto tracks = platform.second->tracks;
            for(auto track: tracks)
            {
                  std::cout << "\t track " << track.first << "\n";
                  auto walls = track.second;
                  for(auto wall: walls)
                  {
                        std::cout << "\t\t wall: " << wall.GetType() << ". " << wall.GetPoint1().toString() << " | " <<  wall.GetPoint2().toString() << "\n";
                  }
            }

      }
      Log->Write("INFO: \tInit Geometry successful!!!\n");

      // for (auto& transItr : _transitions){
      //      Transition* trans = transItr.second;
      //      std::cout << trans->GetID() << " is open " << trans->IsOpen() << std::endl;
      //      std::cout << trans->GetID() << " is close " << trans->IsClose() << std::endl;
      //      std::cout << trans->GetID() << " is temp_close " << trans->IsTempClose() << std::endl;

      // }


      return true;
}
const std::vector<Wall> Building::GetTrackWalls(Point TrackStart, Point TrackEnd, int & room_id, int & subroom_id) const
{
      bool trackFound = false;
      int track_id = -1;
      int platform_id = -1;
      std::vector<Wall> mytrack;
      for(auto platform: _platforms)
      {
            platform_id = platform.second->id;
            auto tracks = platform.second->tracks;
            for(auto track: tracks)
            {
                  track_id=track.first;
                  int commonPoints = 0;
                  // std::cout << "\t track " << track.first << "\n";
                  auto walls = track.second;
                  for(auto wall: walls)
                  {
                        Point P1 =  wall.GetPoint1();
                        Point P2 =  wall.GetPoint2();
                        //std::cout << "\t\t wall: " << wall.GetType() << ". " << wall.GetPoint1().toString() << " | " <<  wall.GetPoint2().toString() << "\n";
                        if (P1 == TrackStart)
                              commonPoints++;
                        if(P1 == TrackEnd)
                              commonPoints++;
                        if(P2 == TrackStart)
                              commonPoints++;
                        if(P2 == TrackEnd)
                              commonPoints++;
                  }
                  if(commonPoints == 2 )
                  {
                        trackFound = true;
                        break;
                  }
            } // tracks
            if (trackFound) break;
      } // plattforms
      if(trackFound)
      {
            room_id = _platforms.at(platform_id)->rid;
            subroom_id = _platforms.at(platform_id)->sid;
            mytrack = _platforms.at(platform_id)->tracks[track_id];
            // std::cout << "track has walls:  " << mytrack.size() << "\n";
            // std::cout << "platform " << platform_id << " track " << track_id << "\n";
            // std::cout << "room " << room_id << " subroom " << subroom_id << "\n";
      }
      else
      {
            std::cout << "could not find any track! Exit.\n";
            exit(-1);

      }
      return mytrack;
}

const std::vector<std::pair<PointWall, PointWall > > Building::GetIntersectionPoints(const std::vector<Transition> doors, const std::vector<Wall> mytrack) const
{
      const int scaleFactor = 1000; // very long orthogonal walls to train's doors
      std::vector<std::pair<PointWall, PointWall > > pws;
      // every door has two points.
      // for every point -> get pair<P, W>
      // collect pairs of pairs
      for(auto door: doors)
      {
           // std::cout << "================================\n";
           // std::cout << "door: " << door.toString() <<  "\n";
            PointWall pw1, pw2;
            int nintersections = 0;
            auto n = door.NormalVec();
            auto p11 = door.GetPoint1() + n*scaleFactor;
            auto p12 = door.GetPoint1() - n*scaleFactor;
            auto p21 = door.GetPoint2() + n*scaleFactor;
            auto p22 = door.GetPoint2() - n*scaleFactor;
            auto normalWall1 = Wall(p11, p12);
            auto normalWall2 = Wall(p21, p22);
            // std::cout << "normal wall 1: " << normalWall1.toString() << "\n";
            // std::cout << "normal wall 2: " << normalWall2.toString() << "\n";
            for(auto twall: mytrack)
            {

                 Point interPoint1, interPoint2;
                 auto res = normalWall1.IntersectionWith(twall, interPoint1);
                 auto res2 = normalWall2.IntersectionWith(twall, interPoint2);
                 // std::cout << " res " << res << "  res2 " << res2 << "\n";
                 if(res == 1)
                 {
                      if(!twall.NearlyHasEndPoint(interPoint1))
                      {
                           // std::cout << "res  twall " << twall.toString() << "\n";
                           pw1 = std::make_pair(interPoint1, twall);
                           nintersections++;
                           // std::cout << "intersection at :" << interPoint1.toString() << "\n";
                      }
                      else // end point
                      {
                           if(res2 == 0)
                           {

                                // std::cout << "twall " << twall.toString() << "\n";
                                // std::cout << "YY intersection 1 at :" << interPoint1.toString() << "\n";
                                // std::cout << "YY intersection 2 at :" << interPoint2.toString() << "\n";

                           }
                           else{

                                // std::cout << "res  twall " << twall.toString() << "\n";
                                pw1 = std::make_pair(interPoint1, twall);
                                nintersections++;
                                // std::cout << "BB: intersection at :" << interPoint1.toString() << "\n";
                           }
                       }
                  }
                  if(res2 == 1)
                  {
                       if(!twall.NearlyHasEndPoint(interPoint2))
                       {
                            // std::cout << "res2  twall " << twall.toString() << "\n";
                            pw2 = std::make_pair(interPoint2, twall);
                            nintersections++;
                            // std::cout << "intersection at :" << interPoint2.toString() << "\n";
                       }
                       else
                       {
                            if(res == 0)
                            {
                                 // std::cout << "twall " << twall.toString() << "\n";
                                 // std::cout << "XX intersection 1 at :" << interPoint1.toString() << "\n";
                                 // std::cout << "XX intersection 2 at :" << interPoint2.toString() << "\n";
                            }
                            else{
                                 // std::cout << "res2  twall " << twall.toString() << "\n";
                                 pw2 = std::make_pair(interPoint2, twall);
                                 nintersections++;
                                 // std::cout << "CC intersection at :" << interPoint2.toString() << "\n";
                            }
                       }
                  }
                  // std::cout << "door: " << door.toString() << ", intersections: " <<  nintersections << "\n";


            } // tracks
            // std::cout << "door: " << door.toString() << ", intersections: " <<  nintersections << "\n";
            // std::cout << "================================\n";

            if(nintersections == 2)
                  pws.push_back(std::make_pair(pw1, pw2));

            else
            {
                 std::cout << KRED << "Error in GetIntersection. Should be 2 but got  " << nintersections << "\n";
                                                                                                             exit(-1);
            }
      }// doors
      // getc(stdin);

      return pws;
}
// reset changes made by trainTimeTable[id]
bool Building::resetGeometry(std::shared_ptr<TrainTimeTable> tab)
{
     // this function is composed of three copy/pasted blocks.
      int room_id, subroom_id;

      // std::cout << "enter resetGeometry with tab id: " << tab->id << "\n" ;
      // std::cout << "temp Added Walls\n";
      // for(auto id_wall: TempAddedWalls)
      // {
      //      std::cout << "i " << id_wall.first << "\n";
      //      auto walls = id_wall.second;
      //      for(auto wall: walls )
      //           std::cout << wall.toString() << "\n";
      // }
      // std::cout << "temp Removed Walls\n";
      // for(auto id_wall: TempRemovedWalls)
      // {
      //      std::cout << "i " << id_wall.first << "\n";
      //      auto walls = id_wall.second;
      //      for(auto wall: walls )
      //           std::cout << wall.toString() << "\n";
      // }
      // std::cout << "temp Added Doors\n";
      // for(auto id_wall: TempAddedDoors)
      // {
      //      std::cout << "i " << id_wall.first << "\n";
      //      auto walls = id_wall.second;
      //      for(auto wall: walls )
      //           std::cout << wall.toString() << "\n";
      // }
      // getc(stdin);

      // remove temp added walls
      auto tempWalls = TempAddedWalls[tab->id];
      for(auto  it=tempWalls.begin(); it!=tempWalls.end(); )
      {
           auto wall = *it;
           if (it != tempWalls.end())
           {
                tempWalls.erase(it);
           }
           for (auto platform: _platforms)
           {
                // auto tracks =  platform.second->tracks;
                room_id = platform.second->rid;
                subroom_id = platform.second->sid;
                // auto room = this->GetAllRooms().at(room_id);
                SubRoom * subroom = this->GetAllRooms().at(room_id)->GetAllSubRooms().at(subroom_id).get();
                // std::cout << "----\n";
                // for(auto subWall: subroom->GetAllWalls())
                //      std::cout << ">> "<< subWall.toString() << "\n";
                // std::cout << "----\n";
                for(auto subWall: subroom->GetAllWalls())
                {
                     if(subWall == wall)
                     {
                          // if everything goes right, then we should enter this
                          // if. We already erased from tempWalls!
                          subroom->RemoveWall(wall);
                          // std::cout << KGRN << "RESET REMOVE wall " << wall.toString() << "\n" << RESET;
                     }//if
                }//subroom
           }//platforms
      }
      TempAddedWalls[tab->id] = tempWalls;

/*       // add remove walls */
      auto tempRemovedWalls = TempRemovedWalls[tab->id];
      for(auto  it=tempRemovedWalls.begin(); it!=tempRemovedWalls.end(); )
      {
           auto wall = *it;
           if (it != tempRemovedWalls.end())
           {
                tempRemovedWalls.erase(it);
           }
           for (auto platform: _platforms)
           {
                auto tracks =  platform.second->tracks;
                room_id = platform.second->rid;
                subroom_id = platform.second->sid;
                SubRoom * subroom = this->GetAllRooms().at(room_id)->GetAllSubRooms().at(subroom_id).get();
                for (auto track : tracks)
                {
                     auto walls = track.second;
                     for(auto trackWall : walls)
                     {
                          if (trackWall == wall)
                          {
                               subroom->AddWall(wall);
                               // std::cout << KGRN << "ADD BACK wall " << wall.toString() << "\n" << RESET;
                          }
                     }
                }
           }
      }
      TempRemovedWalls[tab->id] = tempRemovedWalls;

/*       // remove added doors */
      auto tempDoors = TempAddedDoors[tab->id];
      for(auto  it=tempDoors.begin(); it!=tempDoors.end(); )
      {
           auto door = *it;
           if (it != tempDoors.end())
           {
                tempDoors.erase(it);
           }
           for (auto platform: _platforms)
           {
                auto tracks =  platform.second->tracks;
                room_id = platform.second->rid;
                subroom_id = platform.second->sid;
                SubRoom * subroom = this->GetAllRooms().at(room_id)->GetAllSubRooms().at(subroom_id).get();
                for(auto subTrans: subroom->GetAllTransitions())
                {
                     if (*subTrans == door)
                     {
                          // Trnasitions are added to subrooms and building!!
                          subroom->RemoveTransition(subTrans);
                          this->RemoveTransition(subTrans);
                          // std::cout << KGRN << "RESET remove door " << door.toString() << "\n" << RESET;
                     }

                }
           }
      }
      TempAddedDoors[tab->id] = tempDoors;
      // std::cout << "leave resetGeometry with tab id: " << tab->id << "\n" ;
      // std::cout << "temp Added Walls: " << TempAddedWalls[tab->id].size() << "\n";
      // std::cout << "temp Removed Walls: " << TempRemovedWalls[tab->id].size()<<  "\n";
      // std::cout << "temp Added Doors: " <<TempAddedDoors[tab->id].size() <<  "\n";
      return true;
}
bool Building::InitPlatforms()
691
{
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
      int num_platform = -1;
      for (auto& roomItr : _rooms)
      {
            Room* room = roomItr.second.get();
            for (auto& subRoomItr : room->GetAllSubRooms())
            {
                  auto subRoom = subRoomItr.second.get();
                  int subroom_id = subRoom->GetSubRoomID();
                  if(subRoom->GetType() != "Platform" ) continue;
                  std::map<int, std::vector<Wall> > tracks;
                  num_platform++;
                  for (auto&& wall:subRoom->GetAllWalls())
                  {
                        if(wall.GetType().find("track") == std::string::npos) continue;
                        // add wall to track
                        std::vector<std::string> strs;
                        boost::split(strs, wall.GetType(), boost::is_any_of("-"),boost::token_compress_on);
                        if(strs.size() <= 1) continue;
                        int n = atoi(strs[1].c_str());
                        /* std::cout << "caption: " << wall.GetCaption().c_str() << " > " << n << "\n"; */
                        /* if(tracks.count[n] == 0) */
                        /* { */
                        tracks[n].push_back(wall);
                        /* } */
                  } //walls
                  std::shared_ptr<Platform> p = std::make_shared<Platform>(
                        Platform{
                              num_platform,
                              room->GetID(),
                              subroom_id,
                              tracks,
                              });
                  AddPlatform(p);

            }//subroom
      }//rooms
qiancheng xu's avatar
qiancheng xu committed
728
	  return true;
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
}
      bool Building::InitInsideGoals()
      {
            bool found = false;
            for (auto& goalItr : _goals){
                  Goal* goal = goalItr.second;
                  if (goal->GetRoomID() == -1){
                        found = true;
                        std::cout << "Goal " << goal->GetId() << " is outside" << std::endl;
                        continue;
                  }

                  for (auto& roomItr : _rooms){
                        Room* room = roomItr.second.get();

                        if (goal->GetRoomID() != room->GetID()){
                              continue;
                        }

                        for (auto& subRoomItr : room->GetAllSubRooms()){
                              SubRoom* subRoom = subRoomItr.second.get();

                              if ((goal->GetSubRoomID() == subRoom->GetSubRoomID()) && (subRoom->IsInSubRoom(goal->GetCentroid()))){
                                    std::cout << "Goal " << goal->GetId() << " is in subroom " << subRoom->GetUID() << std::endl;
                                    Crossing* crossing = goal->GetCentreCrossing();
                                    subRoom->AddCrossing(crossing);
                                    crossing->SetRoom1(room);
                                    crossing->SetSubRoom1(subRoom);
                                    crossing->SetSubRoom2(subRoom);
                                    AddCrossing(crossing);
                                    found = true;
                                    break;
761 762 763 764 765 766 767
//                         for (auto& cross : subRoom->GetAllCrossings()){
//                              std::cout << "Crossing Subroom: " << cross->GetUniqueID() << std::endl;
//                         }
//
//                         for (auto& cross: _crossings){
//                              std::cout << "Crossing Building: " << cross.second->GetUniqueID() << std::endl;
//                         }
768

769 770 771
                              }
                        }
                  }
772

773 774 775 776 777 778
                  if (!found){
                        Log->Write("Warning: \t Goal %d seems to have no subroom and is not outside, please check your input",
                                   goal->GetId());
                  }
                  found = false;
            }
779

780
            Log->Write("INFO: \tInitInsideGoals successful!!!\n");
781

782 783
            return true;
      }
784
bool Building::correct() const {
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
      auto t_start = std::chrono::high_resolution_clock::now();
      Log->Write("INFO:\tenter correct ...");
      bool removed = false;

      for(auto&& room: this->GetAllRooms()) {
            for(auto&& subroom: room.second->GetAllSubRooms()) {
                  // -- remove exits *on* walls
                  removed = RemoveOverlappingDoors(subroom.second);
                  // --------------------------
                  // -- remove overlapping walls
                  auto walls = subroom.second->GetAllWalls(); // this call
                  // should be
                  // after
                  // eliminating
                  // nasty exits
800
#if DEBUG
801
                  std::cout<< "\n" << KRED << "correct Room " << room.first << "  Subroom " << subroom.first << RESET  << std::endl;
802
#endif
803 804 805 806 807
                  for(auto const & bigWall: walls) //self checking
                  {
                        // std::cout << "BigWall: " << std::endl;
                        // bigWall.WriteToErrorLog();
                        //special treatment for doors
Mohcine Chraibi's avatar
Mohcine Chraibi committed
808
/////
809 810 811 812
                        std::vector<Wall> WallPieces;
                        WallPieces = SplitWall(subroom.second, bigWall);
                        if(!WallPieces.empty())
                              removed = true;
813
#if DEBUG
814 815 816
                        z                    std::cout << "Wall pieces size : " <<  WallPieces.size() << std::endl;
                        for(auto w:WallPieces)
                              w.WriteToErrorLog();
Mohcine Chraibi's avatar
Mohcine Chraibi committed
817
#endif
818 819 820 821 822
                        int ok=0;
                        while(!ok)
                        {
                              ok = 1; // ok ==1 means no new pieces are found
                              for (auto wallPiece: WallPieces)
823
                              {
824 825 826
                                    std::vector<Wall> tmpWallPieces;
                                    tmpWallPieces = SplitWall(subroom.second, wallPiece);
                                    if(!tmpWallPieces.empty())
827
                                    {
828 829 830 831 832 833 834 835 836 837 838 839 840 841
                                          // std::cout << "set ok because tmp size =" << tmpWallPieces.size() << std::endl;
                                          ok = 0; /// stay in the loop
                                          // append tmpWallPieces to WallPiece
                                          WallPieces.insert(std::end(WallPieces),std::begin(tmpWallPieces), std::end(tmpWallPieces));
                                          // remove the line since it was split already
                                          auto it = std::find(WallPieces.begin(), WallPieces.end(), wallPiece);
                                          if (it != WallPieces.end())
                                          {
                                                // std::cout<< KGRN << "delete wall ..." << RESET <<std::endl;
                                                // wallPiece.WriteToErrorLog();
                                                WallPieces.erase(it);
                                          }

                                          // std::cout << "BNow Wall peces size : " <<  WallPieces.size() << std::endl;
842
                                    }
843
                              }
844
#if DEBUG
845 846 847 848 849 850 851 852
                              std::cout << "ok "<< ok << std::endl;
                              std::cout << "new while  Wall peces size : " <<  WallPieces.size() << std::endl;
                              std::cout << "====" << std::endl;

                              for(auto t: WallPieces){
                                    std::cout << ">> Piece: " << std::endl;
                                    t.WriteToErrorLog();
                              }
853
#endif
854 855 856 857 858 859 860 861 862 863 864 865 866
                              // getc(stdin);
                        }// while
                        // remove
                        // duplicates fromWllPiecs
                        if(!WallPieces.empty())
                        {
                              //remove  duplicaes from wallPiecess

                              auto end = WallPieces.end();
                              for (auto it = WallPieces.begin(); it != end; ++it) {
                                    end = std::remove(it + 1, end, *it);
                              }
                              WallPieces.erase(end, WallPieces.end());
867
#if DEBUG
868 869 870 871 872
                              std::cout << "..removing duplicates pieces..\n";
                              for(auto t: WallPieces){
                                    std::cout << ">>>> Piece: " << std::endl;
                                    t.WriteToErrorLog();
                              }
873
#endif
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
                              // remove big wall and add one wallpiece to walls
                              ReplaceBigWall(subroom.second, bigWall, WallPieces);
                        }
                  }// bigLine
            }//s
      }//r

      if(removed)
      {
            fs::path f("correct_"+this->GetConfig()->GetGeometryFile());
            //fs::path p(this->GetConfig()->GetProjectRootDir());
            //p = p / f;
            std::string filename = f.string();
            if(SaveGeometry(filename))
                  this->GetConfig()->SetGeometryFile(filename);
      }

      auto t_end = std::chrono::high_resolution_clock::now();
      double elapsedTimeMs = std::chrono::duration<double, std::milli>(t_end-t_start).count();
      Log->Write("INFO:\tLeave geometry correct with success (%.3f s)", elapsedTimeMs);
      return true;
895
}
Mohcine Chraibi's avatar
Mohcine Chraibi committed
896 897
bool Building::RemoveOverlappingDoors(const std::shared_ptr<SubRoom>& subroom) const
{
898
#if DEBUG
899
      std::cout << KRED << "\nEnter RemoveOverlappingDoors with subroom " << subroom->GetRoomID() << "," << subroom->GetSubRoomID() << RESET<<"\n";
900
#endif
901
      bool removed = false; // did we remove anything?
902 903 904 905
      vector<Line> exits = vector<Line>(); // transitions+crossings
      auto walls = subroom->GetAllWalls();
      vector<Wall> tmpWalls = vector<Wall>(); //splited big walls are stored here
      bool isBigWall = false; // mark walls as big. If not big, add them to tmpWalls
Mohcine Chraibi's avatar
Mohcine Chraibi committed
906 907 908 909 910 911
      //  collect all crossings
      for (auto&& cros: subroom->GetAllCrossings())
            exits.push_back(*cros);
      //collect all transitions
      for (auto&& trans: subroom->GetAllTransitions())
            exits.push_back(*trans);
912 913
#if DEBUG
      std::cout << "subroom walls: \n";
914 915 916
      for(auto w: subroom->GetAllWalls())
            w.WriteToErrorLog();
      std::cout << "---------------\n";
Mohcine Chraibi's avatar
Mohcine Chraibi committed
917
      // removing doors on walls
918
#endif
919 920
      while(!walls.empty())
      {
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
            auto wall = walls.back();
            walls.pop_back();
            isBigWall = false;
            for(auto  e=exits.begin(); e!=exits.end(); )
            {
                  if(wall.NearlyInLineSegment(e->GetPoint1()) && wall.NearlyInLineSegment(e->GetPoint2()))
                  {
                        isBigWall = true; // mark walls as big
                        double dist_pt1 = (wall.GetPoint1() - e->GetPoint1()).NormSquare();
                        double dist_pt2 = (wall.GetPoint1() - e->GetPoint2()).NormSquare();
                        Point A, B;

                        if(dist_pt1<dist_pt2)
                        {
                              A = e->GetPoint1();
                              B = e->GetPoint2();
                        }
                        else
                        {
                              A = e->GetPoint2();
                              B = e->GetPoint1();
                        }

                        Wall NewWall(wall.GetPoint1(), A);
                        Wall NewWall1(wall.GetPoint2(), B);
                        // NewWall.WriteToErrorLog();
                        // NewWall1.WriteToErrorLog();
                        // add new lines to be controled against overlap with exits
                        walls.push_back(NewWall);
                        walls.push_back(NewWall1);
                        subroom->RemoveWall(wall);
                        exits.erase(e); // we don't need to check this exit again
                        removed = true;
                        break; // we are done with this wall. get next wall.

                  }// if
                  else
                  {
                        e++;
                  }
            } // exits
            if(!isBigWall)
                  tmpWalls.push_back(wall);
964 965 966 967 968

      }// while

      // copy walls in subroom
      for(auto const & wall: tmpWalls)
Mohcine Chraibi's avatar
Mohcine Chraibi committed
969
      {
970
            subroom->AddWall(wall);
Mohcine Chraibi's avatar
Mohcine Chraibi committed
971
      }
972

973
#if DEBUG
974 975
      std::cout << "\nnew Subroom:  " << std::endl;
      for(auto w: subroom->GetAllWalls())
976
            w.WriteToErrorLog(); // AddWall won't add existing walls
977

978
      std::cout << KGRN << "\nLEAVE with removed=:   "<< removed << RESET << std::endl;
979 980
      getc(stdin);
#endif
981

982
      return removed;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
983
}
984

985
std::vector<Wall>  Building::SplitWall(const std::shared_ptr<SubRoom>& subroom, const Wall&  bigWall) const{
986
      std::vector<Wall> WallPieces;
987
#if DEBUG
988 989
      std::cout << subroom->GetSubRoomID() << "collect wall pieces with " << std::endl;
      bigWall.WriteToErrorLog();
Mohcine Chraibi's avatar
Mohcine Chraibi committed
990
#endif
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
      auto walls = subroom->GetAllWalls();
      auto crossings = subroom->GetAllCrossings();
      auto transitions = subroom->GetAllTransitions();
      // TODO: Hlines too?
      vector<Line> walls_and_exits = vector<Line>();
      // @todo: check if this is GetAllGoals()?
      //  collect all crossings
      for (auto&& cros:crossings)
            walls_and_exits.push_back(*cros);
      //collect all transitions
      for (auto&& trans: transitions)
            walls_and_exits.push_back(*trans);
      for (auto&& wall: walls)
            walls_and_exits.push_back(wall);

      for(auto const & other: walls_and_exits)
      {
1008
#if DEBUG
1009
            std::cout << other.toString() << "\n";
1010
#endif
1011 1012
            if((bigWall == other) || (bigWall.ShareCommonPointWith(other))) continue;
            Point intersectionPoint;
1013

1014 1015 1016
            if(bigWall.IntersectionWith(other, intersectionPoint))
            {
                  if(intersectionPoint == bigWall.GetPoint1() || intersectionPoint == bigWall.GetPoint2()) continue;
1017
#if DEBUG
1018 1019 1020 1021 1022 1023 1024 1025
                  std::cout << "BIG\n";
                  std::cout << bigWall.GetPoint1()._x << " " << bigWall.GetPoint1()._y << "\n";
                  std::cout << bigWall.GetPoint2()._x << " " << bigWall.GetPoint2()._y << "\n";
                  std::cout<< "intersectin with: " << std::endl;
                  std::cout << other.toString() << "\n";
                  std::cout << intersectionPoint._x <<" " <<intersectionPoint._y << "\n";
                  string s = intersectionPoint.toString();
                  std::cout << "\t >> Intersection at Point: " << s.c_str() << "\n";
1026
#endif
1027
                  //Point NAN_p(J_NAN, J_NAN);
1028

1029 1030
                  if(std::isnan(intersectionPoint._x) || std::isnan(intersectionPoint._y))
                        continue;
1031

1032 1033
                  Wall NewWall(intersectionPoint, bigWall.GetPoint2());// [IP -- P2]
                  Wall NewWall2(bigWall.GetPoint1(), intersectionPoint);// [IP -- P2]
1034

1035 1036
                  WallPieces.push_back(NewWall);
                  WallPieces.push_back(NewWall2);
1037
#if DEBUG
1038 1039 1040
                  std::cout << "Add newwall: " << std::endl;
                  NewWall.WriteToErrorLog();
                  NewWall2.WriteToErrorLog();
1041
#endif
1042 1043
            }
      }//other walls
1044
#if DEBUG
1045 1046
      std::cout << "size " << WallPieces.size() << "\n";
      std::cout << "Leave collect\n--------" << std::endl;
1047
#endif
1048 1049
// getc(stdin);

1050
      return WallPieces;
1051 1052 1053
}
bool Building::ReplaceBigWall(const std::shared_ptr<SubRoom>& subroom, const Wall& bigWall, std::vector<Wall>& WallPieces) const
{
Mohcine Chraibi's avatar
Mohcine Chraibi committed
1054
#if DEBUG
1055 1056
      Log->Write("INFO Replacing big line in Room %d | Subroom %d with:", subroom->GetRoomID(), subroom->GetSubRoomID());
      bigWall.WriteToErrorLog();
1057

1058
      // REMOVE BigLINE
Mohcine Chraibi's avatar
Mohcine Chraibi committed
1059

1060
      std::cout << "\ns+ =" << subroom->GetAllWalls().size() << "\n";
1061
#endif
Mohcine Chraibi's avatar
Mohcine Chraibi committed
1062

1063
      bool res = subroom->RemoveWall(bigWall);
Mohcine Chraibi's avatar
Mohcine Chraibi committed
1064

1065
#if DEBUG
1066
      std::cout << "s- =" << subroom->GetAllWalls().size() << "\n";
1067
#endif
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
      if(!res) {
            Log->Write("ERROR:  Correct fails. Could not remove wall: ");
            bigWall.WriteToErrorLog();
            return false;
      }
      // ADD SOME LINE
      res = AddWallToSubroom(subroom, WallPieces);
      if(!res) {
            Log->Write("ERROR:  Correct fails. Could not add new wall piece");
            return false;
      }

      return true;
1081
}
1082 1083
const string& Building::GetProjectFilename() const
{
1084
      return _configuration->GetProjectFile();
1085 1086
}

1087 1088
const string& Building::GetProjectRootDir() const
{
1089
      return _configuration->GetProjectRootDir();
1090
}
1091

1092 1093
const std::string& Building::GetGeometryFilename() const
{
1094
      return _configuration->GetGeometryFile();
1095
}
1096

1097
bool Building::AddWallToSubroom(
1098 1099
      const std::shared_ptr<SubRoom> & subroom,
      std::vector<Wall> WallPieces) const
1100 1101
{ // CHOOSE WHICH PIECE SHOULD BE ADDED TO SUBROOM
// this is a challngig function
1102
#if DEBUG
1103 1104 1105
      std::cout << "\n-----\nEnter add_wall with:\n";
      for(const auto & w : WallPieces)
            w.WriteToErrorLog();
1106
#endif
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
      auto walls = subroom->GetAllWalls();
      int maxCount = -1;
      Wall choosenWall;
      for(const auto & w : WallPieces) {
            // std::cout <<"\n check wall: \n";
            // w.WriteToErrorLog();
            int count = 0;
            for (const auto & checkWall: walls) {
                  if (checkWall==w) continue;// don't count big wall
                  if (w.ShareCommonPointWith(checkWall)) count++;
                  else
                  {   // first use the cheap ShareCommonPointWith() before entering
                        // this else
                        Point interP;
                        if (w.IntersectionWith(checkWall, interP))
                        {
                              if( (!std::isnan(interP._x)) && (!std::isnan(interP._y)))
                                    count++;
                        }
                  }
            }
            auto transitions = subroom->GetAllTransitions();
            auto crossings = subroom->GetAllCrossings();
            //auto h = subroom.second->GetAllHlines();
            for (auto transition: transitions)
                  if (w.ShareCommonPointWith(*transition)) count++;
            for (auto crossing: crossings)
                  if (w.ShareCommonPointWith(*crossing)) count++;

            if (count>=2)
            {
                  subroom->AddWall(w);
1139
#if DEBUG
1140 1141
                  Log->Write("INFO: Wall candidate: ");
                  w.WriteToErrorLog();
1142
#endif
1143 1144 1145 1146 1147
                  if (count > maxCount)
                  {
                        maxCount = count;
                        choosenWall = w;
                  }
1148
#if DEBUG
1149
                  std::cout << "\n -- count= " << count << ",  maxCount= " << maxCount << "\n";
1150
#endif
1151 1152 1153 1154 1155 1156
            }
      }// WallPieces
      if(maxCount<0)
            return false;
      else
      {
1157
#if DEBUG
1158 1159
            std::cout << KGRN << "Choosen Wall: " << RESET << std::endl;
            choosenWall.WriteToErrorLog();
1160
#endif
1161 1162 1163
            subroom->AddWall(choosenWall);
            return true;
      }
1164 1165
}

1166 1167
void Building::WriteToErrorLog() const
{
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
      Log->Write("GEOMETRY: ");
      for (int i = 0; i<GetNumberOfRooms(); i++) {
            Room* r = GetRoom(i);
            r->WriteToErrorLog();
      }
      Log->Write("ROUTING: ");

      for (map<int, Crossing*>::const_iterator iter = _crossings.begin();
           iter!=_crossings.end(); ++iter) {
            iter->second->WriteToErrorLog();
      }
      for (map<int, Transition*>::const_iterator iter = _transitions.begin();
           iter!=_transitions.end(); ++iter) {
            iter->second->WriteToErrorLog();
      }
      for (map<int, Hline*>::const_iterator iter = _hLines.begin();
           iter!=_hLines.end(); ++iter) {
            iter->second->WriteToErrorLog();
      }
      Log->Write("\n");
1188 1189
}

1190 1191
Room* Building::GetRoom(string caption) const
{
1192 1193 1194 1195 1196 1197 1198
      for (const auto& it: _rooms) {
            if (it.second->GetCaption()==caption)
                  return it.second.get();
      }
      Log->Write("ERROR: Room not found with caption "+caption);
      //return NULL;
      exit(EXIT_FAILURE);
1199 1200
}

1201
bool Building::AddCrossing(Crossing* line)
1202
{
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
      int IDRoom = line->GetRoom1()->GetID();
      int IDLine = line->GetUniqueID();
      int IDCrossing = 1000 * IDRoom + IDLine;
      if (_crossings.count(IDCrossing) != 0)
      {
            char tmp[CLENGTH];
            sprintf(tmp,
                    "ERROR: Duplicate index for crossing found [%d] in Routing::AddCrossing()",
                    IDCrossing);
            Log->Write(tmp);
            exit(EXIT_FAILURE);
      }
      _crossings[IDCrossing] = line;
      return true;
}
bool Building::RemoveTransition(Transition * line)
{
     // std::cout << "enter Building Remove Transitions with " << _transitions.size() << "\n";
      if (_transitions.count(line->GetID())!=0) {
           _transitions.erase(line->GetID());
           // std::cout << " enter Nuilding  Remove Transitions with " << _transitions.size() << "\n";
           return true;
      }
     // std::cout << "2 enter Nuilding  Remove Transitions with " << _transitions.size() << "\n";
     return false;
1228
}
1229
bool Building::AddTransition(Transition* line)
1230
{
1231 1232 1233 1234
      // std::cout << "building add transition "<< line->GetID()<< "\n";
      if (_transitions.count(line->GetID())!=0) {
            char tmp[CLENGTH];
            sprintf(tmp,
1235 1236
                    "ERROR: Duplicate index for transition found [%d] in Routing::AddTransition()",
                    line->GetID());
1237 1238 1239 1240
            Log->Write(tmp);
            exit(EXIT_FAILURE);
      }
      _transitions[line->GetID()] = line;
1241

1242
      return true;
1243 1244
}

1245
bool Building::AddHline(Hline* line)
1246
{
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
      if (_hLines.count(line->GetID())!=0) {
            // check if the lines are identical
            Hline* ori = _hLines[line->GetID()];
            if (ori->operator==(*line)) {
                  Log->Write("INFO: \tSkipping identical hlines with ID [%d]", line->GetID());
                  return false;
            }
            else {
                  Log->Write(
                        "ERROR: Duplicate index for hlines found [%d] in Routing::AddHline(). You have [%d] hlines",
                        line->GetID(), _hLines.size());
                  exit(EXIT_FAILURE);
            }
      }
      _hLines[line->GetID()] = line;
      return true;
1263 1264
}

1265
bool Building::AddGoal(Goal* goal)
1266
{
1267 1268 1269 1270 1271 1272 1273 1274
      if (_goals.count(goal->GetId())!=0) {
            Log->Write(
                  "ERROR: Duplicate index for goal found [%d] in Routing::AddGoal()",
                  goal->GetId());
            exit(EXIT_FAILURE);
      }
      _goals[goal->GetId()] = goal;

1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
      return true;
}

bool Building::


AddTrainType(std::shared_ptr<TrainType> TT)
{
      if (_trainTypes.count(TT->type)!=0) {
            Log->Write("WARNING: Duplicate type for train found [%s]",TT->type);
      }
      _trainTypes[TT->type] = TT;
      return true;
}
1290

1291 1292 1293 1294 1295 1296 1297 1298
bool Building::AddTrainTimeTable(std::shared_ptr<TrainTimeTable> TTT)
{
      if (_trainTimeTables.count(TTT->id)!=0) {
            Log->Write("WARNING: Duplicate id for train time table found [%d]",TTT->id);
            exit(EXIT_FAILURE);
      }
      _trainTimeTables[TTT->id] = TTT;
      return true;
1299 1300
}

1301 1302
const map<int, Crossing*>& Building::GetAllCrossings() const
{
1303
      return _crossings;