OpenTTD
roadveh_cmd.cpp
Go to the documentation of this file.
1 /* $Id: roadveh_cmd.cpp 27667 2016-10-16 14:58:38Z frosch $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD 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.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "roadveh.h"
14 #include "command_func.h"
15 #include "news_func.h"
17 #include "station_base.h"
18 #include "company_func.h"
19 #include "articulated_vehicles.h"
20 #include "newgrf_sound.h"
21 #include "pathfinder/yapf/yapf.h"
22 #include "strings_func.h"
23 #include "tunnelbridge_map.h"
24 #include "date_func.h"
25 #include "vehicle_func.h"
26 #include "sound_func.h"
27 #include "ai/ai.hpp"
28 #include "game/game.hpp"
29 #include "depot_map.h"
30 #include "effectvehicle_func.h"
31 #include "roadstop_base.h"
32 #include "spritecache.h"
33 #include "core/random_func.hpp"
34 #include "company_base.h"
35 #include "core/backup_type.hpp"
36 #include "newgrf.h"
37 #include "zoom_func.h"
38 
39 #include "table/strings.h"
40 
41 #include "safeguards.h"
42 
43 static const uint16 _roadveh_images[] = {
44  0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
45  0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
46  0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
47  0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
48  0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
49  0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
50  0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
51  0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
52 };
53 
54 static const uint16 _roadveh_full_adder[] = {
55  0, 88, 0, 0, 0, 0, 48, 48,
56  48, 48, 0, 0, 64, 64, 0, 16,
57  16, 0, 88, 0, 0, 0, 0, 48,
58  48, 48, 48, 0, 0, 64, 64, 0,
59  16, 16, 0, 88, 0, 0, 0, 0,
60  48, 48, 48, 48, 0, 0, 64, 64,
61  0, 16, 16, 0, 8, 8, 8, 8,
62  0, 0, 0, 8, 8, 8, 8
63 };
64 assert_compile(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
65 
66 template <>
67 bool IsValidImageIndex<VEH_ROAD>(uint8 image_index)
68 {
69  return image_index < lengthof(_roadveh_images);
70 }
71 
74  TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_X_NE, // Enter from north east
75  TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_Y_SE, // Enter from south east
76  TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_RIGHT_S, // Enter from south west
78 };
79 
80 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
82 };
83 
87 };
88 
89 
94 bool RoadVehicle::IsBus() const
95 {
96  assert(this->IsFrontEngine());
98 }
99 
106 {
107  int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
108 
109  if (offset != NULL) {
110  offset->x = ScaleGUITrad(reference_width) / 2;
111  offset->y = 0;
112  }
113  return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
114 }
115 
116 static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
117 {
118  const Engine *e = Engine::Get(engine);
119  uint8 spritenum = e->u.road.image_index;
120 
121  if (is_custom_sprite(spritenum)) {
122  GetCustomVehicleIcon(engine, DIR_W, image_type, result);
123  if (result->IsValid()) return;
124 
125  spritenum = e->original_image_index;
126  }
127 
128  assert(IsValidImageIndex<VEH_ROAD>(spritenum));
129  result->Set(DIR_W + _roadveh_images[spritenum]);
130 }
131 
133 {
134  uint8 spritenum = this->spritenum;
135 
136  if (is_custom_sprite(spritenum)) {
137  GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
138  if (result->IsValid()) return;
139 
140  spritenum = this->GetEngine()->original_image_index;
141  }
142 
143  assert(IsValidImageIndex<VEH_ROAD>(spritenum));
144  SpriteID sprite = direction + _roadveh_images[spritenum];
145 
146  if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
147 
148  result->Set(sprite);
149 }
150 
160 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
161 {
162  VehicleSpriteSeq seq;
163  GetRoadVehIcon(engine, image_type, &seq);
164 
165  Rect rect;
166  seq.GetBounds(&rect);
167  preferred_x = Clamp(preferred_x,
168  left - UnScaleGUI(rect.left),
169  right - UnScaleGUI(rect.right));
170 
171  seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
172 }
173 
183 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
184 {
185  VehicleSpriteSeq seq;
186  GetRoadVehIcon(engine, image_type, &seq);
187 
188  Rect rect;
189  seq.GetBounds(&rect);
190 
191  width = UnScaleGUI(rect.right - rect.left + 1);
192  height = UnScaleGUI(rect.bottom - rect.top + 1);
193  xoffs = UnScaleGUI(rect.left);
194  yoffs = UnScaleGUI(rect.top);
195 }
196 
202 static uint GetRoadVehLength(const RoadVehicle *v)
203 {
204  const Engine *e = v->GetEngine();
205  uint length = VEHICLE_LENGTH;
206 
207  uint16 veh_len = CALLBACK_FAILED;
208  if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
209  /* Use callback 36 */
210  veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
211  if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
212  } else {
213  /* Use callback 11 */
214  veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
215  }
216  if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
217  if (veh_len != 0) {
218  length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
219  }
220 
221  return length;
222 }
223 
230 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
231 {
232  assert(v->type == VEH_ROAD);
233  assert(v->IsFrontEngine());
234 
236 
238 
239  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
240  /* Check the v->first cache. */
241  assert(u->First() == v);
242 
243  /* Update the 'first engine' */
244  u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
245 
246  /* Update the length of the vehicle. */
247  uint veh_len = GetRoadVehLength(u);
248  /* Verify length hasn't changed. */
249  if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
250 
251  u->gcache.cached_veh_length = veh_len;
252  v->gcache.cached_total_length += u->gcache.cached_veh_length;
253 
254  /* Update visual effect */
255  u->UpdateVisualEffect();
256 
257  /* Update cargo aging period. */
258  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
259  }
260 
261  uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
262  v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
263 }
264 
275 {
276  if (HasTileRoadType(tile, ROADTYPE_TRAM) != HasBit(e->info.misc_flags, EF_ROAD_TRAM)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
277 
278  if (flags & DC_EXEC) {
279  const RoadVehicleInfo *rvi = &e->u.road;
280 
281  RoadVehicle *v = new RoadVehicle();
282  *ret = v;
284  v->owner = _current_company;
285 
286  v->tile = tile;
287  int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
288  int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
289  v->x_pos = x;
290  v->y_pos = y;
291  v->z_pos = GetSlopePixelZ(x, y);
292 
293  v->state = RVSB_IN_DEPOT;
295 
296  v->spritenum = rvi->image_index;
298  v->cargo_cap = rvi->capacity;
299  v->refit_cap = 0;
300 
301  v->last_station_visited = INVALID_STATION;
302  v->last_loading_station = INVALID_STATION;
303  v->engine_type = e->index;
304  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
305 
306  v->reliability = e->reliability;
308  v->max_age = e->GetLifeLengthInDays();
309  _new_vehicle_id = v->index;
310 
311  v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
312 
314  v->build_year = _cur_year;
315 
316  v->sprite_seq.Set(SPR_IMG_QUERY);
318  v->SetFrontEngine();
319 
320  v->roadtype = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
321  v->compatible_roadtypes = RoadTypeToRoadTypes(v->roadtype);
323 
325  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
326 
329 
330  /* Call various callbacks after the whole consist has been constructed */
331  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
332  u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
333  u->refit_cap = 0;
335  u->InvalidateNewGRFCache();
336  }
338  /* Initialize cached values for realistic acceleration. */
340 
341  v->UpdatePosition();
342 
344  }
345 
346  return CommandCost();
347 }
348 
349 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
350 {
351  if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
352 
354  case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
355  case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
356 
357  default: NOT_REACHED();
358  }
359 }
360 
361 bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
362 {
363  FindDepotData rfdd = FindClosestRoadDepot(this, 0);
364  if (rfdd.best_length == UINT_MAX) return false;
365 
366  if (location != NULL) *location = rfdd.tile;
367  if (destination != NULL) *destination = GetDepotIndex(rfdd.tile);
368 
369  return true;
370 }
371 
381 CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
382 {
384  if (v == NULL) return CMD_ERROR;
385 
386  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
387 
388  CommandCost ret = CheckOwnership(v->owner);
389  if (ret.Failed()) return ret;
390 
391  if ((v->vehstatus & VS_STOPPED) ||
392  (v->vehstatus & VS_CRASHED) ||
393  v->breakdown_ctr != 0 ||
394  v->overtaking != 0 ||
395  v->state == RVSB_WORMHOLE ||
396  v->IsInDepot() ||
397  v->current_order.IsType(OT_LOADING)) {
398  return CMD_ERROR;
399  }
400 
402 
404 
405  if (flags & DC_EXEC) v->reverse_ctr = 180;
406 
407  return CommandCost();
408 }
409 
410 
412 {
413  for (RoadVehicle *v = this; v != NULL; v = v->Next()) {
414  v->colourmap = PAL_NONE;
415  v->UpdateViewport(true, false);
416  }
417  this->CargoChanged();
418 }
419 
421 {
422  static const int8 _delta_xy_table[8][10] = {
423  /* y_extent, x_extent, y_offs, x_offs, y_bb_offs, x_bb_offs, y_extent_shorten, x_extent_shorten, y_bb_offs_shorten, x_bb_offs_shorten */
424  {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
425  {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
426  {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
427  {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
428  {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
429  {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
430  {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
431  {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
432  };
433 
434  int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
435  if (!IsDiagonalDirection(direction)) shorten >>= 1;
436 
437  const int8 *bb = _delta_xy_table[direction];
438  this->x_bb_offs = bb[5] + bb[9] * shorten;
439  this->y_bb_offs = bb[4] + bb[8] * shorten;;
440  this->x_offs = bb[3];
441  this->y_offs = bb[2];
442  this->x_extent = bb[1] + bb[7] * shorten;
443  this->y_extent = bb[0] + bb[6] * shorten;
444  this->z_extent = 6;
445 }
446 
452 {
453  int max_speed = this->vcache.cached_max_speed;
454 
455  /* Limit speed to 50% while reversing, 75% in curves. */
456  for (const RoadVehicle *u = this; u != NULL; u = u->Next()) {
457  if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
459  max_speed = this->vcache.cached_max_speed / 2;
460  break;
461  } else if ((u->direction & 1) == 0) {
462  max_speed = this->vcache.cached_max_speed * 3 / 4;
463  }
464  }
465 
466  /* Vehicle is on the middle part of a bridge. */
467  if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
468  max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
469  }
470  }
471 
472  return min(max_speed, this->current_order.GetMaxSpeed() * 2);
473 }
474 
480 {
481  RoadVehicle *first = v->First();
482  Vehicle *u = v;
483  for (; v->Next() != NULL; v = v->Next()) u = v;
484  u->SetNext(NULL);
485  v->last_station_visited = first->last_station_visited; // for PreDestructor
486 
487  /* Only leave the road stop when we're really gone. */
488  if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
489 
490  delete v;
491 }
492 
493 static void RoadVehSetRandomDirection(RoadVehicle *v)
494 {
495  static const DirDiff delta[] = {
497  };
498 
499  do {
500  uint32 r = Random();
501 
502  v->direction = ChangeDir(v->direction, delta[r & 3]);
503  v->UpdateViewport(true, true);
504  } while ((v = v->Next()) != NULL);
505 }
506 
513 {
514  v->crashed_ctr++;
515  if (v->crashed_ctr == 2) {
517  } else if (v->crashed_ctr <= 45) {
518  if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
519  } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
520  bool ret = v->Next() != NULL;
522  return ret;
523  }
524 
525  return true;
526 }
527 
535 {
536  const Vehicle *u = (Vehicle*)data;
537 
538  return (v->type == VEH_TRAIN &&
539  abs(v->z_pos - u->z_pos) <= 6 &&
540  abs(v->x_pos - u->x_pos) <= 4 &&
541  abs(v->y_pos - u->y_pos) <= 4) ? v : NULL;
542 }
543 
544 uint RoadVehicle::Crash(bool flooded)
545 {
546  uint pass = this->GroundVehicleBase::Crash(flooded);
547  if (this->IsFrontEngine()) {
548  pass += 1; // driver
549 
550  /* If we're in a drive through road stop we ought to leave it */
551  if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
552  RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
553  }
554  }
555  this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
556  return pass;
557 }
558 
559 static void RoadVehCrash(RoadVehicle *v)
560 {
561  uint pass = v->Crash();
562 
563  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
564  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
565 
566  SetDParam(0, pass);
568  (pass == 1) ?
569  STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH,
570  NT_ACCIDENT,
571  v->index
572  );
573 
574  ModifyStationRatingAround(v->tile, v->owner, -160, 22);
575  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
576 }
577 
578 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
579 {
580  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
581  if (u->state == RVSB_WORMHOLE) continue;
582 
583  TileIndex tile = u->tile;
584 
585  if (!IsLevelCrossingTile(tile)) continue;
586 
588  RoadVehCrash(v);
589  return true;
590  }
591  }
592 
593  return false;
594 }
595 
597 {
598  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
599 
600  const Station *st = Station::Get(station);
601  if (!CanVehicleUseStation(this, st)) {
602  /* There is no stop left at the station, so don't even TRY to go there */
603  this->IncrementRealOrderIndex();
604  return 0;
605  }
606 
607  return st->xy;
608 }
609 
610 static void StartRoadVehSound(const RoadVehicle *v)
611 {
612  if (!PlayVehicleSound(v, VSE_START)) {
613  SoundID s = RoadVehInfo(v->engine_type)->sfx;
614  if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0) {
615  s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
616  }
617  SndPlayVehicleFx(s, v);
618  }
619 }
620 
622  int x;
623  int y;
624  const Vehicle *veh;
625  Vehicle *best;
626  uint best_diff;
627  Direction dir;
628 };
629 
630 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
631 {
632  static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
633  static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
634 
635  RoadVehFindData *rvf = (RoadVehFindData*)data;
636 
637  short x_diff = v->x_pos - rvf->x;
638  short y_diff = v->y_pos - rvf->y;
639 
640  if (v->type == VEH_ROAD &&
641  !v->IsInDepot() &&
642  abs(v->z_pos - rvf->veh->z_pos) < 6 &&
643  v->direction == rvf->dir &&
644  rvf->veh->First() != v->First() &&
645  (dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
646  (dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
647  (dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
648  (dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
649  uint diff = abs(x_diff) + abs(y_diff);
650 
651  if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
652  rvf->best = v;
653  rvf->best_diff = diff;
654  }
655  }
656 
657  return NULL;
658 }
659 
660 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
661 {
662  RoadVehFindData rvf;
663  RoadVehicle *front = v->First();
664 
665  if (front->reverse_ctr != 0) return NULL;
666 
667  rvf.x = x;
668  rvf.y = y;
669  rvf.dir = dir;
670  rvf.veh = v;
671  rvf.best_diff = UINT_MAX;
672 
673  if (front->state == RVSB_WORMHOLE) {
674  FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
675  FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
676  } else {
677  FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
678  }
679 
680  /* This code protects a roadvehicle from being blocked for ever
681  * If more than 1480 / 74 days a road vehicle is blocked, it will
682  * drive just through it. The ultimate backup-code of TTD.
683  * It can be disabled. */
684  if (rvf.best_diff == UINT_MAX) {
685  front->blocked_ctr = 0;
686  return NULL;
687  }
688 
689  if (update_blocked_ctr && ++front->blocked_ctr > 1480) return NULL;
690 
691  return RoadVehicle::From(rvf.best);
692 }
693 
699 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
700 {
701  if (v->IsBus()) {
702  /* Check if station was ever visited before */
703  if (!(st->had_vehicle_of_type & HVOT_BUS)) {
704  st->had_vehicle_of_type |= HVOT_BUS;
705  SetDParam(0, st->index);
707  v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
709  v->index,
710  st->index
711  );
712  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
713  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
714  }
715  } else {
716  /* Check if station was ever visited before */
717  if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
718  st->had_vehicle_of_type |= HVOT_TRUCK;
719  SetDParam(0, st->index);
721  v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
723  v->index,
724  st->index
725  );
726  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
727  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
728  }
729  }
730 }
731 
740 {
742  default: NOT_REACHED();
743  case AM_ORIGINAL:
744  return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
745 
746  case AM_REALISTIC:
747  return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
748  }
749 }
750 
751 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
752 {
753  static const Direction _roadveh_new_dir[] = {
756  DIR_E , DIR_SE, DIR_S
757  };
758 
759  x = x - v->x_pos + 1;
760  y = y - v->y_pos + 1;
761 
762  if ((uint)x > 2 || (uint)y > 2) return v->direction;
763  return _roadveh_new_dir[y * 4 + x];
764 }
765 
766 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
767 {
768  Direction new_dir = RoadVehGetNewDirection(v, x, y);
769  Direction old_dir = v->direction;
770  DirDiff delta;
771 
772  if (new_dir == old_dir) return old_dir;
773  delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
774  return ChangeDir(old_dir, delta);
775 }
776 
777 struct OvertakeData {
778  const RoadVehicle *u;
779  const RoadVehicle *v;
780  TileIndex tile;
781  Trackdir trackdir;
782 };
783 
784 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
785 {
786  const OvertakeData *od = (OvertakeData*)data;
787 
788  return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : NULL;
789 }
790 
798 {
799  TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->compatible_roadtypes);
800  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
801  TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
802  TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
803 
804  /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
805  if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
806 
807  /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
808  return HasVehicleOnPos(od->tile, od, EnumFindVehBlockingOvertake);
809 }
810 
811 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
812 {
813  OvertakeData od;
814 
815  od.v = v;
816  od.u = u;
817 
818  /* Trams can't overtake other trams */
819  if (v->roadtype == ROADTYPE_TRAM) return;
820 
821  /* Don't overtake in stations */
822  if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
823 
824  /* For now, articulated road vehicles can't overtake anything. */
825  if (v->HasArticulatedPart()) return;
826 
827  /* Vehicles are not driving in same direction || direction is not a diagonal direction */
828  if (v->direction != u->direction || !(v->direction & 1)) return;
829 
830  /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
832 
833  /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
834  * accelerating, take the maximum speed for the comparison, else the current speed.
835  * Original acceleration always accelerates, so always use the maximum speed. */
836  int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
837  if (u_speed >= v->GetCurrentMaxSpeed() &&
838  !(u->vehstatus & VS_STOPPED) &&
839  u->cur_speed != 0) {
840  return;
841  }
842 
843  od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
844 
845  /* Are the current and the next tile suitable for overtaking?
846  * - Does the track continue along od.trackdir
847  * - No junctions
848  * - No barred levelcrossing
849  * - No other vehicles in the way
850  */
851  od.tile = v->tile;
852  if (CheckRoadBlockedForOvertaking(&od)) return;
853 
854  od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
855  if (CheckRoadBlockedForOvertaking(&od)) return;
856 
857  /* When the vehicle in front of us is stopped we may only take
858  * half the time to pass it than when the vehicle is moving. */
859  v->overtaking_ctr = (od.u->cur_speed == 0 || (od.u->vehstatus & VS_STOPPED)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
861 }
862 
863 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
864 {
865  if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
866 
867  if (old_z < v->z_pos) {
868  v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
869  } else {
870  uint16 spd = v->cur_speed + 2;
871  if (spd <= v->vcache.cached_max_speed) v->cur_speed = spd;
872  }
873 }
874 
875 static int PickRandomBit(uint bits)
876 {
877  uint i;
878  uint num = RandomRange(CountBits(bits));
879 
880  for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
881  return i;
882 }
883 
893 {
894 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
895 
896  TileIndex desttile;
897  Trackdir best_track;
898  bool path_found = true;
899 
900  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->compatible_roadtypes);
901  TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
902  TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
903 
904  if (IsTileType(tile, MP_ROAD)) {
905  if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->compatible_roadtypes) == 0)) {
906  /* Road depot owned by another company or with the wrong orientation */
907  trackdirs = TRACKDIR_BIT_NONE;
908  }
909  } else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
910  /* Standard road stop (drive-through stops are treated as normal road) */
911 
912  if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
913  /* different station owner or wrong orientation or the vehicle has articulated parts */
914  trackdirs = TRACKDIR_BIT_NONE;
915  } else {
916  /* Our station */
917  RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
918 
919  if (GetRoadStopType(tile) != rstype) {
920  /* Wrong station type */
921  trackdirs = TRACKDIR_BIT_NONE;
922  } else {
923  /* Proper station type, check if there is free loading bay */
925  !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
926  /* Station is full and RV queuing is off */
927  trackdirs = TRACKDIR_BIT_NONE;
928  }
929  }
930  }
931  }
932  /* The above lookups should be moved to GetTileTrackStatus in the
933  * future, but that requires more changes to the pathfinder and other
934  * stuff, probably even more arguments to GTTS.
935  */
936 
937  /* Remove tracks unreachable from the enter dir */
938  trackdirs &= _road_enter_dir_to_reachable_trackdirs[enterdir];
939  if (trackdirs == TRACKDIR_BIT_NONE) {
940  /* No reachable tracks, so we'll reverse */
941  return_track(_road_reverse_table[enterdir]);
942  }
943 
944  if (v->reverse_ctr != 0) {
945  bool reverse = true;
946  if (v->roadtype == ROADTYPE_TRAM) {
947  /* Trams may only reverse on a tile if it contains at least the straight
948  * trackbits or when it is a valid turning tile (i.e. one roadbit) */
950  RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
951  reverse = ((rb & straight) == straight) ||
952  (rb == DiagDirToRoadBits(enterdir));
953  }
954  if (reverse) {
955  v->reverse_ctr = 0;
956  if (v->tile != tile) {
957  return_track(_road_reverse_table[enterdir]);
958  }
959  }
960  }
961 
962  desttile = v->dest_tile;
963  if (desttile == 0) {
964  /* We've got no destination, pick a random track */
965  return_track(PickRandomBit(trackdirs));
966  }
967 
968  /* Only one track to choose between? */
969  if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
970  return_track(FindFirstBit2x64(trackdirs));
971  }
972 
974  case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
975  case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
976 
977  default: NOT_REACHED();
978  }
979  v->HandlePathfindingResult(path_found);
980 
981 found_best_track:;
982 
983  if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
984 
985  return best_track;
986 }
987 
989  byte x, y;
990 };
991 
992 #include "table/roadveh_movement.h"
993 
994 static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
995 {
996  /* Don't leave unless v and following wagons are in the depot. */
997  for (const RoadVehicle *u = v; u != NULL; u = u->Next()) {
998  if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
999  }
1000 
1002  v->direction = DiagDirToDir(dir);
1003 
1004  Trackdir tdir = _roadveh_depot_exit_trackdir[dir];
1005  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
1006 
1007  int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1008  int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1009 
1010  if (first) {
1011  /* We are leaving a depot, but have to go to the exact same one; re-enter */
1012  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1013  VehicleEnterDepot(v);
1014  return true;
1015  }
1016 
1017  if (RoadVehFindCloseTo(v, x, y, v->direction, false) != NULL) return true;
1018 
1020 
1021  StartRoadVehSound(v);
1022 
1023  /* Vehicle is about to leave a depot */
1024  v->cur_speed = 0;
1025  }
1026 
1027  v->vehstatus &= ~VS_HIDDEN;
1028  v->state = tdir;
1029  v->frame = RVC_DEPOT_START_FRAME;
1030 
1031  v->x_pos = x;
1032  v->y_pos = y;
1033  v->UpdatePosition();
1034  v->UpdateInclination(true, true);
1035 
1037 
1038  return true;
1039 }
1040 
1041 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1042 {
1043  if (prev->tile == v->tile && !already_reversed) {
1044  /* If the previous vehicle is on the same tile as this vehicle is
1045  * then it must have reversed. */
1046  return _road_reverse_table[entry_dir];
1047  }
1048 
1049  byte prev_state = prev->state;
1050  Trackdir dir;
1051 
1052  if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1053  DiagDirection diag_dir = INVALID_DIAGDIR;
1054 
1055  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1056  diag_dir = GetTunnelBridgeDirection(tile);
1057  } else if (IsRoadDepotTile(tile)) {
1058  diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1059  }
1060 
1061  if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1062  dir = DiagDirToDiagTrackdir(diag_dir);
1063  } else {
1064  if (already_reversed && prev->tile != tile) {
1065  /*
1066  * The vehicle has reversed, but did not go straight back.
1067  * It immediately turn onto another tile. This means that
1068  * the roadstate of the previous vehicle cannot be used
1069  * as the direction we have to go with this vehicle.
1070  *
1071  * Next table is build in the following way:
1072  * - first row for when the vehicle in front went to the northern or
1073  * western tile, second for southern and eastern.
1074  * - columns represent the entry direction.
1075  * - cell values are determined by the Trackdir one has to take from
1076  * the entry dir (column) to the tile in north or south by only
1077  * going over the trackdirs used for turning 90 degrees, i.e.
1078  * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1079  */
1080  static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1083  dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1084  } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1085  dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1086  } else if (prev_state < TRACKDIR_END) {
1087  dir = (Trackdir)prev_state;
1088  } else {
1089  return INVALID_TRACKDIR;
1090  }
1091  }
1092 
1093  /* Do some sanity checking. */
1094  static const RoadBits required_roadbits[] = {
1096  ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1097  };
1098  RoadBits required = required_roadbits[dir & 0x07];
1099 
1100  if ((required & GetAnyRoadBits(tile, v->roadtype, true)) == ROAD_NONE) {
1101  dir = INVALID_TRACKDIR;
1102  }
1103 
1104  return dir;
1105 }
1106 
1115 {
1116  /* The 'current' company is not necessarily the owner of the vehicle. */
1117  Backup<CompanyByte> cur_company(_current_company, c, FILE_LINE);
1118 
1120 
1121  cur_company.Restore();
1122  return ret.Succeeded();
1123 }
1124 
1125 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1126 {
1127  if (v->overtaking != 0) {
1128  if (IsTileType(v->tile, MP_STATION)) {
1129  /* Force us to be not overtaking! */
1130  v->overtaking = 0;
1131  } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1132  /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1133  * if the vehicle started a corner. To protect that, only allow an abort of
1134  * overtake if we are on straight roads */
1136  v->overtaking = 0;
1137  }
1138  }
1139  }
1140 
1141  /* If this vehicle is in a depot and we've reached this point it must be
1142  * one of the articulated parts. It will stay in the depot until activated
1143  * by the previous vehicle in the chain when it gets to the right place. */
1144  if (v->IsInDepot()) return true;
1145 
1146  if (v->state == RVSB_WORMHOLE) {
1147  /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1149 
1150  if (v->IsFrontEngine()) {
1151  const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1152  if (u != NULL) {
1153  v->cur_speed = u->First()->cur_speed;
1154  return false;
1155  }
1156  }
1157 
1159  /* Vehicle has just entered a bridge or tunnel */
1160  v->x_pos = gp.x;
1161  v->y_pos = gp.y;
1162  v->UpdatePosition();
1163  v->UpdateInclination(true, true);
1164  return true;
1165  }
1166 
1167  v->x_pos = gp.x;
1168  v->y_pos = gp.y;
1169  v->UpdatePosition();
1170  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
1171  return true;
1172  }
1173 
1174  /* Get move position data for next frame.
1175  * For a drive-through road stop use 'straight road' move data.
1176  * In this case v->state is masked to give the road stop entry direction. */
1177  RoadDriveEntry rd = _road_drive_data[v->roadtype][(
1179  (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1180 
1181  if (rd.x & RDE_NEXT_TILE) {
1182  TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1183  Trackdir dir;
1184 
1185  if (v->IsFrontEngine()) {
1186  /* If this is the front engine, look for the right path. */
1187  dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1188  } else {
1189  dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1190  }
1191 
1192  if (dir == INVALID_TRACKDIR) {
1193  if (!v->IsFrontEngine()) error("Disconnecting road vehicle.");
1194  v->cur_speed = 0;
1195  return false;
1196  }
1197 
1198 again:
1199  uint start_frame = RVC_DEFAULT_START_FRAME;
1200  if (IsReversingRoadTrackdir(dir)) {
1201  /* When turning around we can't be overtaking. */
1202  v->overtaking = 0;
1203 
1204  /* Turning around */
1205  if (v->roadtype == ROADTYPE_TRAM) {
1206  /* Determine the road bits the tram needs to be able to turn around
1207  * using the 'big' corner loop. */
1208  RoadBits needed;
1209  switch (dir) {
1210  default: NOT_REACHED();
1211  case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1212  case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1213  case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1214  case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1215  }
1216  if ((v->Previous() != NULL && v->Previous()->tile == tile) ||
1217  (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1218  (needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE)) {
1219  /*
1220  * Taking the 'big' corner for trams only happens when:
1221  * - The previous vehicle in this (articulated) tram chain is
1222  * already on the 'next' tile, we just follow them regardless of
1223  * anything. When it is NOT on the 'next' tile, the tram started
1224  * doing a reversing turn when the piece of tram track on the next
1225  * tile did not exist yet. Do not use the big tram loop as that is
1226  * going to cause the tram to split up.
1227  * - Or the front of the tram can drive over the next tile.
1228  */
1229  } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
1230  /*
1231  * Taking the 'small' corner for trams only happens when:
1232  * - We are not the from vehicle of an articulated tram.
1233  * - Or when the company cannot build on the next tile.
1234  *
1235  * The 'small' corner means that the vehicle is on the end of a
1236  * tram track and needs to start turning there. To do this properly
1237  * the tram needs to start at an offset in the tram turning 'code'
1238  * for 'big' corners. It furthermore does not go to the next tile,
1239  * so that needs to be fixed too.
1240  */
1241  tile = v->tile;
1242  start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1243  } else {
1244  /* The company can build on the next tile, so wait till (s)he does. */
1245  v->cur_speed = 0;
1246  return false;
1247  }
1248  } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1249  v->cur_speed = 0;
1250  return false;
1251  } else {
1252  tile = v->tile;
1253  }
1254  }
1255 
1256  /* Get position data for first frame on the new tile */
1257  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1258 
1259  int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1260  int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1261 
1262  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1263  if (v->IsFrontEngine()) {
1264  Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1265  if (u != NULL) {
1266  v->cur_speed = u->First()->cur_speed;
1267  return false;
1268  }
1269  }
1270 
1271  uint32 r = VehicleEnterTile(v, tile, x, y);
1272  if (HasBit(r, VETS_CANNOT_ENTER)) {
1273  if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1274  v->cur_speed = 0;
1275  return false;
1276  }
1277  /* Try an about turn to re-enter the previous tile */
1278  dir = _road_reverse_table[rd.x & 3];
1279  goto again;
1280  }
1281 
1282  if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1283  if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1284  /* New direction is trying to turn vehicle around.
1285  * We can't turn at the exit of a road stop so wait.*/
1286  v->cur_speed = 0;
1287  return false;
1288  }
1289 
1290  /* If we are a drive through road stop and the next tile is of
1291  * the same road stop and the next tile isn't this one (i.e. we
1292  * are not reversing), then keep the reservation and state.
1293  * This way we will not be shortly unregister from the road
1294  * stop. It also makes it possible to load when on the edge of
1295  * two road stops; otherwise you could get vehicles that should
1296  * be loading but are not actually loading. */
1297  if (IsDriveThroughStopTile(v->tile) &&
1299  v->tile != tile) {
1300  /* So, keep 'our' state */
1301  dir = (Trackdir)v->state;
1302  } else if (IsRoadStop(v->tile)) {
1303  /* We're not continuing our drive through road stop, so leave. */
1305  }
1306  }
1307 
1308  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1309  v->tile = tile;
1310  v->state = (byte)dir;
1311  v->frame = start_frame;
1312  }
1313  if (new_dir != v->direction) {
1314  v->direction = new_dir;
1315  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1316  }
1317  v->x_pos = x;
1318  v->y_pos = y;
1319  v->UpdatePosition();
1320  RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1321  return true;
1322  }
1323 
1324  if (rd.x & RDE_TURNED) {
1325  /* Vehicle has finished turning around, it will now head back onto the same tile */
1326  Trackdir dir;
1327  uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1328 
1329  if (v->roadtype == ROADTYPE_TRAM && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, ROADTYPE_TRAM, true))) {
1330  /*
1331  * The tram is turning around with one tram 'roadbit'. This means that
1332  * it is using the 'big' corner 'drive data'. However, to support the
1333  * trams to take a small corner, there is a 'turned' marker in the middle
1334  * of the turning 'drive data'. When the tram took the long corner, we
1335  * will still use the 'big' corner drive data, but we advance it one
1336  * frame. We furthermore set the driving direction so the turning is
1337  * going to be properly shown.
1338  */
1339  turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1340  switch (rd.x & 0x3) {
1341  default: NOT_REACHED();
1342  case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1343  case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1344  case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1345  case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1346  }
1347  } else {
1348  if (v->IsFrontEngine()) {
1349  /* If this is the front engine, look for the right path. */
1350  dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1351  } else {
1352  dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1353  }
1354  }
1355 
1356  if (dir == INVALID_TRACKDIR) {
1357  v->cur_speed = 0;
1358  return false;
1359  }
1360 
1361  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1362 
1363  int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1364  int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1365 
1366  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1367  if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
1368 
1369  uint32 r = VehicleEnterTile(v, v->tile, x, y);
1370  if (HasBit(r, VETS_CANNOT_ENTER)) {
1371  v->cur_speed = 0;
1372  return false;
1373  }
1374 
1375  v->state = dir;
1376  v->frame = turn_around_start_frame;
1377 
1378  if (new_dir != v->direction) {
1379  v->direction = new_dir;
1380  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1381  }
1382 
1383  v->x_pos = x;
1384  v->y_pos = y;
1385  v->UpdatePosition();
1386  RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1387  return true;
1388  }
1389 
1390  /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1391  * it's on a depot tile, check if it's time to activate the next vehicle in
1392  * the chain yet. */
1393  if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
1394  if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1395  RoadVehLeaveDepot(v->Next(), false);
1396  }
1397  }
1398 
1399  /* Calculate new position for the vehicle */
1400  int x = (v->x_pos & ~15) + (rd.x & 15);
1401  int y = (v->y_pos & ~15) + (rd.y & 15);
1402 
1403  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1404 
1405  if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1406  /* Vehicle is not in a road stop.
1407  * Check for another vehicle to overtake */
1408  RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1409 
1410  if (u != NULL) {
1411  u = u->First();
1412  /* There is a vehicle in front overtake it if possible */
1413  if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1414  if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1415 
1416  /* In case an RV is stopped in a road stop, why not try to load? */
1417  if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1419  v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1421  Station *st = Station::GetByTile(v->tile);
1422  v->last_station_visited = st->index;
1423  RoadVehArrivesAt(v, st);
1424  v->BeginLoading();
1425  }
1426  return false;
1427  }
1428  }
1429 
1430  Direction old_dir = v->direction;
1431  if (new_dir != old_dir) {
1432  v->direction = new_dir;
1433  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1434 
1435  /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1436  * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1437  * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1438  * The short (inner) curve has 8 frames, this elongates it to 10. */
1439  v->UpdateInclination(false, true);
1440  return true;
1441  }
1442 
1443  /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1444  * if the vehicle is in a drive-through road stop and this is the destination station
1445  * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1446  * (the station test and stop type test ensure that other vehicles, using the road stop as
1447  * a through route, do not stop) */
1448  if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1450  (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1452  v->owner == GetTileOwner(v->tile) &&
1454  v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1455 
1457  Station *st = Station::GetByTile(v->tile);
1458 
1459  /* Vehicle is at the stop position (at a bay) in a road stop.
1460  * Note, if vehicle is loading/unloading it has already been handled,
1461  * so if we get here the vehicle has just arrived or is just ready to leave. */
1462  if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1463  /* Vehicle has arrived at a bay in a road stop */
1464 
1465  if (IsDriveThroughStopTile(v->tile)) {
1466  TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
1467 
1468  /* Check if next inline bay is free and has compatible road. */
1469  if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && (GetRoadTypes(next_tile) & v->compatible_roadtypes) != 0) {
1470  v->frame++;
1471  v->x_pos = x;
1472  v->y_pos = y;
1473  v->UpdatePosition();
1474  RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1475  return true;
1476  }
1477  }
1478 
1479  rs->SetEntranceBusy(false);
1481 
1482  v->last_station_visited = st->index;
1483 
1484  if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1485  RoadVehArrivesAt(v, st);
1486  v->BeginLoading();
1487  return false;
1488  }
1489  } else {
1490  /* Vehicle is ready to leave a bay in a road stop */
1491  if (rs->IsEntranceBusy()) {
1492  /* Road stop entrance is busy, so wait as there is nowhere else to go */
1493  v->cur_speed = 0;
1494  return false;
1495  }
1496  if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1497  }
1498 
1499  if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1500 
1501  StartRoadVehSound(v);
1503  }
1504 
1505  /* Check tile position conditions - i.e. stop position in depot,
1506  * entry onto bridge or into tunnel */
1507  uint32 r = VehicleEnterTile(v, v->tile, x, y);
1508  if (HasBit(r, VETS_CANNOT_ENTER)) {
1509  v->cur_speed = 0;
1510  return false;
1511  }
1512 
1513  if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1514  v->current_order.Free();
1515  }
1516 
1517  /* Move to next frame unless vehicle arrived at a stop position
1518  * in a depot or entered a tunnel/bridge */
1519  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1520  v->x_pos = x;
1521  v->y_pos = y;
1522  v->UpdatePosition();
1523  RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1524  return true;
1525 }
1526 
1527 static bool RoadVehController(RoadVehicle *v)
1528 {
1529  /* decrease counters */
1530  v->current_order_time++;
1531  if (v->reverse_ctr != 0) v->reverse_ctr--;
1532 
1533  /* handle crashed */
1534  if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1535  return RoadVehIsCrashed(v);
1536  }
1537 
1538  /* road vehicle has broken down? */
1539  if (v->HandleBreakdown()) return true;
1540  if (v->vehstatus & VS_STOPPED) return true;
1541 
1542  ProcessOrders(v);
1543  v->HandleLoading();
1544 
1545  if (v->current_order.IsType(OT_LOADING)) return true;
1546 
1547  if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return true;
1548 
1549  v->ShowVisualEffect();
1550 
1551  /* Check how far the vehicle needs to proceed */
1552  int j = v->UpdateSpeed();
1553 
1554  int adv_spd = v->GetAdvanceDistance();
1555  bool blocked = false;
1556  while (j >= adv_spd) {
1557  j -= adv_spd;
1558 
1559  RoadVehicle *u = v;
1560  for (RoadVehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
1561  if (!IndividualRoadVehicleController(u, prev)) {
1562  blocked = true;
1563  break;
1564  }
1565  }
1566  if (blocked) break;
1567 
1568  /* Determine distance to next map position */
1569  adv_spd = v->GetAdvanceDistance();
1570 
1571  /* Test for a collision, but only if another movement will occur. */
1572  if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1573  }
1574 
1575  v->SetLastSpeed();
1576 
1577  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
1578  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
1579 
1580  u->UpdateViewport(false, false);
1581  }
1582 
1583  /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1584  * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1585  * on next tick to discover whether it is still blocked. */
1586  if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1587 
1588  return true;
1589 }
1590 
1592 {
1593  const Engine *e = this->GetEngine();
1594  if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1595 
1596  uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1597  if (cost_factor == 0) return 0;
1598 
1599  return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1600 }
1601 
1603 {
1604  this->tick_counter++;
1605 
1606  if (this->IsFrontEngine()) {
1607  if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1608  return RoadVehController(this);
1609  }
1610 
1611  return true;
1612 }
1613 
1614 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1615 {
1616  /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1617  if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1618  if (v->IsChainInDepot()) {
1620  return;
1621  }
1622 
1623  uint max_penalty;
1625  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1626  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1627  default: NOT_REACHED();
1628  }
1629 
1630  FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1631  /* Only go to the depot if it is not too far out of our way. */
1632  if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1633  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1634  /* If we were already heading for a depot but it has
1635  * suddenly moved farther away, we continue our normal
1636  * schedule? */
1637  v->current_order.MakeDummy();
1639  }
1640  return;
1641  }
1642 
1643  DepotID depot = GetDepotIndex(rfdd.tile);
1644 
1645  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1647  !Chance16(1, 20)) {
1648  return;
1649  }
1650 
1653  v->dest_tile = rfdd.tile;
1655 }
1656 
1658 {
1659  AgeVehicle(this);
1660 
1661  if (!this->IsFrontEngine()) return;
1662 
1663  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1664  if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1665 
1666  CheckIfRoadVehNeedsService(this);
1667 
1668  CheckOrders(this);
1669 
1670  if (this->running_ticks == 0) return;
1671 
1673 
1674  this->profit_this_year -= cost.GetCost();
1675  this->running_ticks = 0;
1676 
1677  SubtractMoneyFromCompanyFract(this->owner, cost);
1678 
1681 }
1682 
1684 {
1685  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1686 
1687  if (this->IsInDepot()) {
1688  /* We'll assume the road vehicle is facing outwards */
1689  return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1690  }
1691 
1692  if (IsStandardRoadStopTile(this->tile)) {
1693  /* We'll assume the road vehicle is facing outwards */
1694  return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1695  }
1696 
1697  /* Drive through road stops / wormholes (tunnels) */
1699 
1700  /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1701  * otherwise transform it into a valid track direction */
1702  return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);
1703 }