Fix ICU iterators on leading/trailing whitespace
[openttd/fttd.git] / src / group_cmd.cpp
blob102ec17bf06cf6aef1248864a9d3805b850dfb75
1 /* $Id$ */
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 */
10 /** @file group_cmd.cpp Handling of the engine groups */
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "command_func.h"
15 #include "train.h"
16 #include "vehiclelist.h"
17 #include "vehicle_func.h"
18 #include "autoreplace_base.h"
19 #include "autoreplace_func.h"
20 #include "string_func.h"
21 #include "company_func.h"
22 #include "core/pool_func.hpp"
23 #include "order_backup.h"
25 #include "table/strings.h"
27 GroupID _new_group_id;
29 template<> Group::Pool Group::PoolItem::pool ("Group");
30 INSTANTIATE_POOL_METHODS(Group)
32 GroupStatistics::GroupStatistics()
34 this->num_engines = CallocT<uint16>(Engine::GetPoolSize());
37 GroupStatistics::~GroupStatistics()
39 free(this->num_engines);
42 /**
43 * Clear all caches.
45 void GroupStatistics::Clear()
47 this->num_vehicle = 0;
48 this->num_profit_vehicle = 0;
49 this->profit_last_year = 0;
51 /* This is also called when NewGRF change. So the number of engines might have changed. Reallocate. */
52 free(this->num_engines);
53 this->num_engines = CallocT<uint16>(Engine::GetPoolSize());
56 /**
57 * Returns the GroupStatistics for a specific group.
58 * @param company Owner of the group.
59 * @param id_g GroupID of the group.
60 * @param type VehicleType of the vehicles in the group.
61 * @return Statistics for the group.
63 /* static */ GroupStatistics &GroupStatistics::Get(CompanyID company, GroupID id_g, VehicleType type)
65 if (Group::IsValidID(id_g)) {
66 Group *g = Group::Get(id_g);
67 assert(g->owner == company);
68 assert(g->vehicle_type == type);
69 return g->statistics;
72 if (IsDefaultGroupID(id_g)) return Company::Get(company)->group_default[type];
73 if (IsAllGroupID(id_g)) return Company::Get(company)->group_all[type];
75 NOT_REACHED();
78 /**
79 * Returns the GroupStatistic for the group of a vehicle.
80 * @param v Vehicle.
81 * @return GroupStatistics for the group of the vehicle.
83 /* static */ GroupStatistics &GroupStatistics::Get(const Vehicle *v)
85 return GroupStatistics::Get(v->owner, v->group_id, v->type);
88 /**
89 * Returns the GroupStatistic for the ALL_GROUPO of a vehicle type.
90 * @param v Vehicle.
91 * @return GroupStatistics for the ALL_GROUP of the vehicle type.
93 /* static */ GroupStatistics &GroupStatistics::GetAllGroup(const Vehicle *v)
95 return GroupStatistics::Get(v->owner, ALL_GROUP, v->type);
98 /**
99 * Update all caches after loading a game, changing NewGRF etc..
101 /* static */ void GroupStatistics::UpdateAfterLoad()
103 /* Set up the engine count for all companies */
104 Company *c;
105 FOR_ALL_COMPANIES(c) {
106 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
107 c->group_all[type].Clear();
108 c->group_default[type].Clear();
112 /* Recalculate */
113 Group *g;
114 FOR_ALL_GROUPS(g) {
115 g->statistics.Clear();
118 const Vehicle *v;
119 FOR_ALL_VEHICLES(v) {
120 if (!v->IsEngineCountable()) continue;
122 GroupStatistics::CountEngine(v, 1);
123 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, 1);
126 FOR_ALL_COMPANIES(c) {
127 GroupStatistics::UpdateAutoreplace(c->index);
132 * Update num_vehicle when adding or removing a vehicle.
133 * @param v Vehicle to count.
134 * @param delta +1 to add, -1 to remove.
136 /* static */ void GroupStatistics::CountVehicle(const Vehicle *v, int delta)
138 assert(delta == 1 || delta == -1);
140 GroupStatistics &stats_all = GroupStatistics::GetAllGroup(v);
141 GroupStatistics &stats = GroupStatistics::Get(v);
143 stats_all.num_vehicle += delta;
144 stats.num_vehicle += delta;
146 if (v->age > VEHICLE_PROFIT_MIN_AGE) {
147 stats_all.num_profit_vehicle += delta;
148 stats_all.profit_last_year += v->GetDisplayProfitLastYear() * delta;
149 stats.num_profit_vehicle += delta;
150 stats.profit_last_year += v->GetDisplayProfitLastYear() * delta;
155 * Update num_engines when adding/removing an engine.
156 * @param v Engine to count.
157 * @param delta +1 to add, -1 to remove.
159 /* static */ void GroupStatistics::CountEngine(const Vehicle *v, int delta)
161 assert(delta == 1 || delta == -1);
162 GroupStatistics::GetAllGroup(v).num_engines[v->engine_type] += delta;
163 GroupStatistics::Get(v).num_engines[v->engine_type] += delta;
167 * Add a vehicle to the profit sum of its group.
169 /* static */ void GroupStatistics::VehicleReachedProfitAge(const Vehicle *v)
171 GroupStatistics &stats_all = GroupStatistics::GetAllGroup(v);
172 GroupStatistics &stats = GroupStatistics::Get(v);
174 stats_all.num_profit_vehicle++;
175 stats_all.profit_last_year += v->GetDisplayProfitLastYear();
176 stats.num_profit_vehicle++;
177 stats.profit_last_year += v->GetDisplayProfitLastYear();
181 * Recompute the profits for all groups.
183 /* static */ void GroupStatistics::UpdateProfits()
185 /* Set up the engine count for all companies */
186 Company *c;
187 FOR_ALL_COMPANIES(c) {
188 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
189 c->group_all[type].ClearProfits();
190 c->group_default[type].ClearProfits();
194 /* Recalculate */
195 Group *g;
196 FOR_ALL_GROUPS(g) {
197 g->statistics.ClearProfits();
200 const Vehicle *v;
201 FOR_ALL_VEHICLES(v) {
202 if (v->IsPrimaryVehicle() && v->age > VEHICLE_PROFIT_MIN_AGE) GroupStatistics::VehicleReachedProfitAge(v);
207 * Update autoreplace_defined and autoreplace_finished of all statistics of a company.
208 * @param company Company to update statistics for.
210 /* static */ void GroupStatistics::UpdateAutoreplace(CompanyID company)
212 /* Set up the engine count for all companies */
213 Company *c = Company::Get(company);
214 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
215 c->group_all[type].ClearAutoreplace();
216 c->group_default[type].ClearAutoreplace();
219 /* Recalculate */
220 Group *g;
221 FOR_ALL_GROUPS(g) {
222 if (g->owner != company) continue;
223 g->statistics.ClearAutoreplace();
226 for (EngineRenewList erl = c->engine_renew_list; erl != NULL; erl = erl->next) {
227 const Engine *e = Engine::Get(erl->from);
228 GroupStatistics &stats = GroupStatistics::Get(company, erl->group_id, e->type);
229 if (!stats.autoreplace_defined) {
230 stats.autoreplace_defined = true;
231 stats.autoreplace_finished = true;
233 if (stats.num_engines[erl->from] > 0) stats.autoreplace_finished = false;
238 * Update the num engines of a groupID. Decrease the old one and increase the new one
239 * @note called in SetTrainGroupID and UpdateTrainGroupID
240 * @param v Vehicle we have to update
241 * @param old_g index of the old group
242 * @param new_g index of the new group
244 static inline void UpdateNumEngineGroup(const Vehicle *v, GroupID old_g, GroupID new_g)
246 if (old_g != new_g) {
247 /* Decrease the num engines in the old group */
248 GroupStatistics::Get(v->owner, old_g, v->type).num_engines[v->engine_type]--;
250 /* Increase the num engines in the new group */
251 GroupStatistics::Get(v->owner, new_g, v->type).num_engines[v->engine_type]++;
257 Group::Group(Owner owner)
259 this->owner = owner;
262 Group::~Group()
264 free(this->name);
269 * Create a new vehicle group.
270 * @param vt vehicle type
271 * @param flags type of operation
272 * @return the cost of this operation or an error
274 static CommandCost CreateNewGroup (VehicleType vt, DoCommandFlag flags)
276 if (!Group::CanAllocateItem()) return CMD_ERROR;
278 if (flags & DC_EXEC) {
279 Group *g = new Group(_current_company);
280 g->replace_protection = false;
281 g->vehicle_type = vt;
283 _new_group_id = g->index;
285 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
288 return CommandCost();
292 * Create a new vehicle group.
293 * @param tile unused
294 * @param flags type of operation
295 * @param p1 vehicle type
296 * @param p2 unused
297 * @param text unused
298 * @return the cost of this operation or an error
300 CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
302 VehicleType vt = Extract<VehicleType, 0, 3>(p1);
303 if (!IsCompanyBuildableVehicleType(vt)) return CMD_ERROR;
305 return CreateNewGroup (vt, flags);
310 * Add all vehicles in the given group to the default group and then deletes the group.
311 * @param tile unused
312 * @param flags type of operation
313 * @param p1 index of array group
314 * - p1 bit 0-15 : GroupID
315 * @param p2 unused
316 * @param text unused
317 * @return the cost of this operation or an error
319 CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
321 Group *g = Group::GetIfValid(p1);
322 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
324 /* Remove all vehicles from the group */
325 DoCommand(0, p1, 0, flags, CMD_REMOVE_ALL_VEHICLES_GROUP);
327 if (flags & DC_EXEC) {
328 /* Update backupped orders if needed */
329 OrderBackup::ClearGroup(g->index);
331 /* If we set an autoreplace for the group we delete, remove it. */
332 if (_current_company < MAX_COMPANIES) {
333 Company *c;
334 EngineRenew *er;
336 c = Company::Get(_current_company);
337 FOR_ALL_ENGINE_RENEWS(er) {
338 if (er->group_id == g->index) RemoveEngineReplacementForCompany(c, er->from, g->index, flags);
342 VehicleType vt = g->vehicle_type;
344 /* Delete the Replace Vehicle Windows */
345 DeleteWindowById(WC_REPLACE_VEHICLE, g->vehicle_type);
346 delete g;
348 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
351 return CommandCost();
354 static bool IsUniqueGroupNameForVehicleType(const char *name, VehicleType type)
356 const Group *g;
358 FOR_ALL_GROUPS(g) {
359 if (g->name != NULL && g->vehicle_type == type && strcmp(g->name, name) == 0) return false;
362 return true;
366 * Rename a group
367 * @param tile unused
368 * @param flags type of operation
369 * @param p1 index of array group
370 * - p1 bit 0-15 : GroupID
371 * @param p2 unused
372 * @param text the new name or an empty string when resetting to the default
373 * @return the cost of this operation or an error
375 CommandCost CmdRenameGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
377 Group *g = Group::GetIfValid(p1);
378 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
380 bool reset = StrEmpty(text);
382 if (!reset) {
383 if (Utf8StringLength(text) >= MAX_LENGTH_GROUP_NAME_CHARS) return CMD_ERROR;
384 if (!IsUniqueGroupNameForVehicleType(text, g->vehicle_type)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
387 if (flags & DC_EXEC) {
388 /* Delete the old name */
389 free(g->name);
390 /* Assign the new one */
391 g->name = reset ? NULL : strdup(text);
393 SetWindowDirty(WC_REPLACE_VEHICLE, g->vehicle_type);
394 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
397 return CommandCost();
402 * Do add a vehicle to a group.
403 * @param v Vehicle to add.
404 * @param new_g Group to add to.
406 static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
408 GroupStatistics::CountVehicle(v, -1);
410 switch (v->type) {
411 default: NOT_REACHED();
412 case VEH_TRAIN:
413 SetTrainGroupID(Train::From(v), new_g);
414 break;
416 case VEH_ROAD:
417 case VEH_SHIP:
418 case VEH_AIRCRAFT:
419 if (v->IsEngineCountable()) UpdateNumEngineGroup(v, v->group_id, new_g);
420 v->group_id = new_g;
421 break;
424 GroupStatistics::CountVehicle(v, 1);
428 * Add a vehicle to a group
429 * @param tile unused
430 * @param flags type of operation
431 * @param p1 index of array group
432 * - p1 bit 0-15 : GroupID
433 * @param p2 vehicle to add to a group
434 * - p2 bit 0-19 : VehicleID
435 * - p2 bit 31 : Add shared vehicles as well.
436 * @param text unused
437 * @return the cost of this operation or an error
439 CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
441 Vehicle *v = Vehicle::GetIfValid(GB(p2, 0, 20));
442 GroupID new_g = p1;
444 if (v == NULL || (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP)) return CMD_ERROR;
446 if (Group::IsValidID(new_g)) {
447 Group *g = Group::Get(new_g);
448 if (g->owner != _current_company || g->vehicle_type != v->type) return CMD_ERROR;
451 if (v->owner != _current_company || !v->IsPrimaryVehicle()) return CMD_ERROR;
453 if (new_g == NEW_GROUP) {
454 /* Create new group. */
455 CommandCost ret = CreateNewGroup (v->type, flags);
456 if (ret.Failed()) return ret;
458 new_g = _new_group_id;
461 if (flags & DC_EXEC) {
462 AddVehicleToGroup(v, new_g);
464 if (HasBit(p2, 31)) {
465 /* Add vehicles in the shared order list as well. */
466 for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
467 if (v2->group_id != new_g) AddVehicleToGroup(v2, new_g);
471 GroupStatistics::UpdateAutoreplace(v->owner);
473 /* Update the Replace Vehicle Windows */
474 SetWindowDirty(WC_REPLACE_VEHICLE, v->type);
475 InvalidateWindowData(GetWindowClassForVehicleType(v->type), VehicleListIdentifier(VL_GROUP_LIST, v->type, _current_company).Pack());
478 return CommandCost();
482 * Add all shared vehicles of all vehicles from a group
483 * @param tile unused
484 * @param flags type of operation
485 * @param p1 index of group array
486 * - p1 bit 0-15 : GroupID
487 * @param p2 type of vehicles
488 * @param text unused
489 * @return the cost of this operation or an error
491 CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
493 VehicleType type = Extract<VehicleType, 0, 3>(p2);
494 GroupID id_g = p1;
495 if (!Group::IsValidID(id_g) || !IsCompanyBuildableVehicleType(type)) return CMD_ERROR;
497 if (flags & DC_EXEC) {
498 Vehicle *v;
500 /* Find the first front engine which belong to the group id_g
501 * then add all shared vehicles of this front engine to the group id_g */
502 FOR_ALL_VEHICLES(v) {
503 if (v->type == type && v->IsPrimaryVehicle()) {
504 if (v->group_id != id_g) continue;
506 /* For each shared vehicles add it to the group */
507 for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
508 if (v2->group_id != id_g) DoCommand(tile, id_g, v2->index, flags, CMD_ADD_VEHICLE_GROUP, text);
513 InvalidateWindowData(GetWindowClassForVehicleType(type), VehicleListIdentifier(VL_GROUP_LIST, type, _current_company).Pack());
516 return CommandCost();
521 * Remove all vehicles from a group
522 * @param tile unused
523 * @param flags type of operation
524 * @param p1 index of group array
525 * - p1 bit 0-15 : GroupID
526 * @param p2 unused
527 * @param text unused
528 * @return the cost of this operation or an error
530 CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
532 GroupID old_g = p1;
533 Group *g = Group::GetIfValid(old_g);
535 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
537 if (flags & DC_EXEC) {
538 Vehicle *v;
540 /* Find each Vehicle that belongs to the group old_g and add it to the default group */
541 FOR_ALL_VEHICLES(v) {
542 if (v->IsPrimaryVehicle()) {
543 if (v->group_id != old_g) continue;
545 /* Add The Vehicle to the default group */
546 DoCommand(tile, DEFAULT_GROUP, v->index, flags, CMD_ADD_VEHICLE_GROUP, text);
550 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
553 return CommandCost();
558 * (Un)set global replace protection from a group
559 * @param tile unused
560 * @param flags type of operation
561 * @param p1 index of group array
562 * - p1 bit 0-15 : GroupID
563 * @param p2
564 * - p2 bit 0 : 1 to set or 0 to clear protection.
565 * @param text unused
566 * @return the cost of this operation or an error
568 CommandCost CmdSetGroupReplaceProtection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
570 Group *g = Group::GetIfValid(p1);
571 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
573 if (flags & DC_EXEC) {
574 g->replace_protection = HasBit(p2, 0);
576 SetWindowDirty(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
577 InvalidateWindowData(WC_REPLACE_VEHICLE, g->vehicle_type);
580 return CommandCost();
584 * Decrease the num_vehicle variable before delete an front engine from a group
585 * @note Called in CmdSellRailWagon and DeleteLasWagon,
586 * @param v FrontEngine of the train we want to remove.
588 void RemoveVehicleFromGroup(const Vehicle *v)
590 if (!v->IsPrimaryVehicle()) return;
592 if (!IsDefaultGroupID(v->group_id)) GroupStatistics::CountVehicle(v, -1);
597 * Affect the groupID of a train to new_g.
598 * @note called in CmdAddVehicleGroup and CmdMoveRailVehicle
599 * @param v First vehicle of the chain.
600 * @param new_g index of array group
602 void SetTrainGroupID(Train *v, GroupID new_g)
604 if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g)) return;
606 assert(v->IsFrontEngine() || IsDefaultGroupID(new_g));
608 for (Vehicle *u = v; u != NULL; u = u->Next()) {
609 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
611 u->group_id = new_g;
614 /* Update the Replace Vehicle Windows */
615 GroupStatistics::UpdateAutoreplace(v->owner);
616 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
621 * Recalculates the groupID of a train. Should be called each time a vehicle is added
622 * to/removed from the chain,.
623 * @note this needs to be called too for 'wagon chains' (in the depot, without an engine)
624 * @note Called in CmdBuildRailVehicle, CmdBuildRailWagon, CmdMoveRailVehicle, CmdSellRailWagon
625 * @param v First vehicle of the chain.
627 void UpdateTrainGroupID(Train *v)
629 assert(v->IsFrontEngine() || v->IsFreeWagon());
631 GroupID new_g = v->IsFrontEngine() ? v->group_id : (GroupID)DEFAULT_GROUP;
632 for (Vehicle *u = v; u != NULL; u = u->Next()) {
633 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
635 u->group_id = new_g;
638 /* Update the Replace Vehicle Windows */
639 GroupStatistics::UpdateAutoreplace(v->owner);
640 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
644 * Get the number of engines with EngineID id_e in the group with GroupID
645 * id_g
646 * @param company The company the group belongs to
647 * @param id_g The GroupID of the group used
648 * @param id_e The EngineID of the engine to count
649 * @return The number of engines with EngineID id_e in the group
651 uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
653 const Engine *e = Engine::Get(id_e);
654 return GroupStatistics::Get(company, id_g, e->type).num_engines[id_e];
657 void RemoveAllGroupsForCompany(const CompanyID company)
659 Group *g;
661 FOR_ALL_GROUPS(g) {
662 if (company == g->owner) delete g;