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