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