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/>.
10 /** @file group_cmd.cpp Handling of the engine groups */
13 #include "cmd_helper.h"
14 #include "command_func.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 #include "safeguards.h"
29 GroupID _new_group_id
;
31 GroupPool
_group_pool("Group");
32 INSTANTIATE_POOL_METHODS(Group
)
34 GroupStatistics::GroupStatistics()
36 this->num_engines
= CallocT
<uint16
>(Engine::GetPoolSize());
39 GroupStatistics::~GroupStatistics()
41 free(this->num_engines
);
47 void GroupStatistics::Clear()
49 this->num_vehicle
= 0;
50 this->num_profit_vehicle
= 0;
51 this->profit_last_year
= 0;
53 /* This is also called when NewGRF change. So the number of engines might have changed. Reallocate. */
54 free(this->num_engines
);
55 this->num_engines
= CallocT
<uint16
>(Engine::GetPoolSize());
59 * Returns the GroupStatistics for a specific group.
60 * @param company Owner of the group.
61 * @param id_g GroupID of the group.
62 * @param type VehicleType of the vehicles in the group.
63 * @return Statistics for the group.
65 /* static */ GroupStatistics
&GroupStatistics::Get(CompanyID company
, GroupID id_g
, VehicleType type
)
67 if (Group::IsValidID(id_g
)) {
68 Group
*g
= Group::Get(id_g
);
69 assert(g
->owner
== company
);
70 assert(g
->vehicle_type
== type
);
74 if (IsDefaultGroupID(id_g
)) return Company::Get(company
)->group_default
[type
];
75 if (IsAllGroupID(id_g
)) return Company::Get(company
)->group_all
[type
];
81 * Returns the GroupStatistic for the group of a vehicle.
83 * @return GroupStatistics for the group of the vehicle.
85 /* static */ GroupStatistics
&GroupStatistics::Get(const Vehicle
*v
)
87 return GroupStatistics::Get(v
->owner
, v
->group_id
, v
->type
);
91 * Returns the GroupStatistic for the ALL_GROUPO of a vehicle type.
93 * @return GroupStatistics for the ALL_GROUP of the vehicle type.
95 /* static */ GroupStatistics
&GroupStatistics::GetAllGroup(const Vehicle
*v
)
97 return GroupStatistics::Get(v
->owner
, ALL_GROUP
, v
->type
);
101 * Update all caches after loading a game, changing NewGRF etc..
103 /* static */ void GroupStatistics::UpdateAfterLoad()
105 /* Set up the engine count for all companies */
107 FOR_ALL_COMPANIES(c
) {
108 for (VehicleType type
= VEH_BEGIN
; type
< VEH_COMPANY_END
; type
++) {
109 c
->group_all
[type
].Clear();
110 c
->group_default
[type
].Clear();
117 g
->statistics
.Clear();
121 FOR_ALL_VEHICLES(v
) {
122 if (!v
->IsEngineCountable()) continue;
124 GroupStatistics::CountEngine(v
, 1);
125 if (v
->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v
, 1);
128 FOR_ALL_COMPANIES(c
) {
129 GroupStatistics::UpdateAutoreplace(c
->index
);
134 * Update num_vehicle when adding or removing a vehicle.
135 * @param v Vehicle to count.
136 * @param delta +1 to add, -1 to remove.
138 /* static */ void GroupStatistics::CountVehicle(const Vehicle
*v
, int delta
)
140 assert(delta
== 1 || delta
== -1);
142 GroupStatistics
&stats_all
= GroupStatistics::GetAllGroup(v
);
143 GroupStatistics
&stats
= GroupStatistics::Get(v
);
145 stats_all
.num_vehicle
+= delta
;
146 stats
.num_vehicle
+= delta
;
148 if (v
->age
> VEHICLE_PROFIT_MIN_AGE
) {
149 stats_all
.num_profit_vehicle
+= delta
;
150 stats_all
.profit_last_year
+= v
->GetDisplayProfitLastYear() * delta
;
151 stats
.num_profit_vehicle
+= delta
;
152 stats
.profit_last_year
+= v
->GetDisplayProfitLastYear() * delta
;
157 * Update num_engines when adding/removing an engine.
158 * @param v Engine to count.
159 * @param delta +1 to add, -1 to remove.
161 /* static */ void GroupStatistics::CountEngine(const Vehicle
*v
, int delta
)
163 assert(delta
== 1 || delta
== -1);
164 GroupStatistics::GetAllGroup(v
).num_engines
[v
->engine_type
] += delta
;
165 GroupStatistics::Get(v
).num_engines
[v
->engine_type
] += delta
;
169 * Add a vehicle to the profit sum of its group.
171 /* static */ void GroupStatistics::VehicleReachedProfitAge(const Vehicle
*v
)
173 GroupStatistics
&stats_all
= GroupStatistics::GetAllGroup(v
);
174 GroupStatistics
&stats
= GroupStatistics::Get(v
);
176 stats_all
.num_profit_vehicle
++;
177 stats_all
.profit_last_year
+= v
->GetDisplayProfitLastYear();
178 stats
.num_profit_vehicle
++;
179 stats
.profit_last_year
+= v
->GetDisplayProfitLastYear();
183 * Recompute the profits for all groups.
185 /* static */ void GroupStatistics::UpdateProfits()
187 /* Set up the engine count for all companies */
189 FOR_ALL_COMPANIES(c
) {
190 for (VehicleType type
= VEH_BEGIN
; type
< VEH_COMPANY_END
; type
++) {
191 c
->group_all
[type
].ClearProfits();
192 c
->group_default
[type
].ClearProfits();
199 g
->statistics
.ClearProfits();
203 FOR_ALL_VEHICLES(v
) {
204 if (v
->IsPrimaryVehicle() && v
->age
> VEHICLE_PROFIT_MIN_AGE
) GroupStatistics::VehicleReachedProfitAge(v
);
209 * Update autoreplace_defined and autoreplace_finished of all statistics of a company.
210 * @param company Company to update statistics for.
212 /* static */ void GroupStatistics::UpdateAutoreplace(CompanyID company
)
214 /* Set up the engine count for all companies */
215 Company
*c
= Company::Get(company
);
216 for (VehicleType type
= VEH_BEGIN
; type
< VEH_COMPANY_END
; type
++) {
217 c
->group_all
[type
].ClearAutoreplace();
218 c
->group_default
[type
].ClearAutoreplace();
224 if (g
->owner
!= company
) continue;
225 g
->statistics
.ClearAutoreplace();
228 for (EngineRenewList erl
= c
->engine_renew_list
; erl
!= NULL
; erl
= erl
->next
) {
229 const Engine
*e
= Engine::Get(erl
->from
);
230 GroupStatistics
&stats
= GroupStatistics::Get(company
, erl
->group_id
, e
->type
);
231 if (!stats
.autoreplace_defined
) {
232 stats
.autoreplace_defined
= true;
233 stats
.autoreplace_finished
= true;
235 if (stats
.num_engines
[erl
->from
] > 0) stats
.autoreplace_finished
= false;
240 * Update the num engines of a groupID. Decrease the old one and increase the new one
241 * @note called in SetTrainGroupID and UpdateTrainGroupID
242 * @param v Vehicle we have to update
243 * @param old_g index of the old group
244 * @param new_g index of the new group
246 static inline void UpdateNumEngineGroup(const Vehicle
*v
, GroupID old_g
, GroupID new_g
)
248 if (old_g
!= new_g
) {
249 /* Decrease the num engines in the old group */
250 GroupStatistics::Get(v
->owner
, old_g
, v
->type
).num_engines
[v
->engine_type
]--;
252 /* Increase the num engines in the new group */
253 GroupStatistics::Get(v
->owner
, new_g
, v
->type
).num_engines
[v
->engine_type
]++;
259 Group::Group(Owner owner
)
271 * Create a new vehicle group.
273 * @param flags type of operation
274 * @param p1 vehicle type
277 * @return the cost of this operation or an error
279 CommandCost
CmdCreateGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
281 VehicleType vt
= Extract
<VehicleType
, 0, 3>(p1
);
282 if (!IsCompanyBuildableVehicleType(vt
)) return CMD_ERROR
;
284 if (!Group::CanAllocateItem()) return CMD_ERROR
;
286 if (flags
& DC_EXEC
) {
287 Group
*g
= new Group(_current_company
);
288 g
->replace_protection
= false;
289 g
->vehicle_type
= vt
;
290 g
->parent
= INVALID_GROUP
;
292 _new_group_id
= g
->index
;
294 InvalidateWindowData(GetWindowClassForVehicleType(vt
), VehicleListIdentifier(VL_GROUP_LIST
, vt
, _current_company
).Pack());
297 return CommandCost();
302 * Add all vehicles in the given group to the default group and then deletes the group.
304 * @param flags type of operation
305 * @param p1 index of array group
306 * - p1 bit 0-15 : GroupID
309 * @return the cost of this operation or an error
311 CommandCost
CmdDeleteGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
313 Group
*g
= Group::GetIfValid(p1
);
314 if (g
== NULL
|| g
->owner
!= _current_company
) return CMD_ERROR
;
316 /* Remove all vehicles from the group */
317 DoCommand(0, p1
, 0, flags
, CMD_REMOVE_ALL_VEHICLES_GROUP
);
319 /* Delete sub-groups */
322 if (gp
->parent
== g
->index
) {
323 DoCommand(0, gp
->index
, 0, flags
, CMD_DELETE_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
) {
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
);
348 InvalidateWindowData(GetWindowClassForVehicleType(vt
), VehicleListIdentifier(VL_GROUP_LIST
, vt
, _current_company
).Pack());
351 return CommandCost();
354 static bool IsUniqueGroupNameForVehicleType(const char *name
, VehicleType type
)
359 if (g
->name
!= NULL
&& g
->vehicle_type
== type
&& strcmp(g
->name
, name
) == 0) return false;
368 * @param flags type of operation
369 * @param p1 index of array group
370 * - p1 bit 0-15 : GroupID
371 * - p1 bit 16: 0 - Rename grouop
372 * 1 - Set group parent
373 * @param p2 parent group index
374 * @param text the new name or an empty string when resetting to the default
375 * @return the cost of this operation or an error
377 CommandCost
CmdAlterGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
379 Group
*g
= Group::GetIfValid(GB(p1
, 0, 16));
380 if (g
== NULL
|| g
->owner
!= _current_company
) return CMD_ERROR
;
382 if (!HasBit(p1
, 16)) {
384 bool reset
= StrEmpty(text
);
387 if (Utf8StringLength(text
) >= MAX_LENGTH_GROUP_NAME_CHARS
) return CMD_ERROR
;
388 if (!IsUniqueGroupNameForVehicleType(text
, g
->vehicle_type
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
391 if (flags
& DC_EXEC
) {
392 /* Delete the old name */
394 /* Assign the new one */
395 g
->name
= reset
? NULL
: stredup(text
);
398 /* Set group parent */
399 const Group
*pg
= Group::GetIfValid(GB(p2
, 0, 16));
402 if (pg
->owner
!= _current_company
) return CMD_ERROR
;
403 if (pg
->vehicle_type
!= g
->vehicle_type
) return CMD_ERROR
;
405 /* Ensure request parent isn't child of group.
406 * This is the only place that infinite loops are prevented. */
407 if (GroupIsInGroup(pg
->index
, g
->index
)) return CMD_ERROR
;
410 if (flags
& DC_EXEC
) {
411 g
->parent
= (pg
== NULL
) ? INVALID_GROUP
: pg
->index
;
415 if (flags
& DC_EXEC
) {
416 SetWindowDirty(WC_REPLACE_VEHICLE
, g
->vehicle_type
);
417 InvalidateWindowData(GetWindowClassForVehicleType(g
->vehicle_type
), VehicleListIdentifier(VL_GROUP_LIST
, g
->vehicle_type
, _current_company
).Pack());
420 return CommandCost();
425 * Do add a vehicle to a group.
426 * @param v Vehicle to add.
427 * @param new_g Group to add to.
429 static void AddVehicleToGroup(Vehicle
*v
, GroupID new_g
)
431 GroupStatistics::CountVehicle(v
, -1);
434 default: NOT_REACHED();
436 SetTrainGroupID(Train::From(v
), new_g
);
442 if (v
->IsEngineCountable()) UpdateNumEngineGroup(v
, v
->group_id
, new_g
);
447 GroupStatistics::CountVehicle(v
, 1);
451 * Add a vehicle to a group
453 * @param flags type of operation
454 * @param p1 index of array group
455 * - p1 bit 0-15 : GroupID
456 * @param p2 vehicle to add to a group
457 * - p2 bit 0-19 : VehicleID
458 * - p2 bit 31 : Add shared vehicles as well.
460 * @return the cost of this operation or an error
462 CommandCost
CmdAddVehicleGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
464 Vehicle
*v
= Vehicle::GetIfValid(GB(p2
, 0, 20));
467 if (v
== NULL
|| (!Group::IsValidID(new_g
) && !IsDefaultGroupID(new_g
) && new_g
!= NEW_GROUP
)) return CMD_ERROR
;
469 if (Group::IsValidID(new_g
)) {
470 Group
*g
= Group::Get(new_g
);
471 if (g
->owner
!= _current_company
|| g
->vehicle_type
!= v
->type
) return CMD_ERROR
;
474 if (v
->owner
!= _current_company
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
476 if (new_g
== NEW_GROUP
) {
477 /* Create new group. */
478 CommandCost ret
= CmdCreateGroup(0, flags
, v
->type
, 0, NULL
);
479 if (ret
.Failed()) return ret
;
481 new_g
= _new_group_id
;
484 if (flags
& DC_EXEC
) {
485 AddVehicleToGroup(v
, new_g
);
487 if (HasBit(p2
, 31)) {
488 /* Add vehicles in the shared order list as well. */
489 for (Vehicle
*v2
= v
->FirstShared(); v2
!= NULL
; v2
= v2
->NextShared()) {
490 if (v2
->group_id
!= new_g
) AddVehicleToGroup(v2
, new_g
);
494 GroupStatistics::UpdateAutoreplace(v
->owner
);
496 /* Update the Replace Vehicle Windows */
497 SetWindowDirty(WC_REPLACE_VEHICLE
, v
->type
);
498 InvalidateWindowData(GetWindowClassForVehicleType(v
->type
), VehicleListIdentifier(VL_GROUP_LIST
, v
->type
, _current_company
).Pack());
501 return CommandCost();
505 * Add all shared vehicles of all vehicles from a group
507 * @param flags type of operation
508 * @param p1 index of group array
509 * - p1 bit 0-15 : GroupID
510 * @param p2 type of vehicles
512 * @return the cost of this operation or an error
514 CommandCost
CmdAddSharedVehicleGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
516 VehicleType type
= Extract
<VehicleType
, 0, 3>(p2
);
518 if (!Group::IsValidID(id_g
) || !IsCompanyBuildableVehicleType(type
)) return CMD_ERROR
;
520 if (flags
& DC_EXEC
) {
523 /* Find the first front engine which belong to the group id_g
524 * then add all shared vehicles of this front engine to the group id_g */
525 FOR_ALL_VEHICLES(v
) {
526 if (v
->type
== type
&& v
->IsPrimaryVehicle()) {
527 if (v
->group_id
!= id_g
) continue;
529 /* For each shared vehicles add it to the group */
530 for (Vehicle
*v2
= v
->FirstShared(); v2
!= NULL
; v2
= v2
->NextShared()) {
531 if (v2
->group_id
!= id_g
) DoCommand(tile
, id_g
, v2
->index
, flags
, CMD_ADD_VEHICLE_GROUP
, text
);
536 InvalidateWindowData(GetWindowClassForVehicleType(type
), VehicleListIdentifier(VL_GROUP_LIST
, type
, _current_company
).Pack());
539 return CommandCost();
544 * Remove all vehicles from a group
546 * @param flags type of operation
547 * @param p1 index of group array
548 * - p1 bit 0-15 : GroupID
551 * @return the cost of this operation or an error
553 CommandCost
CmdRemoveAllVehiclesGroup(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
556 Group
*g
= Group::GetIfValid(old_g
);
558 if (g
== NULL
|| g
->owner
!= _current_company
) return CMD_ERROR
;
560 if (flags
& DC_EXEC
) {
563 /* Find each Vehicle that belongs to the group old_g and add it to the default group */
564 FOR_ALL_VEHICLES(v
) {
565 if (v
->IsPrimaryVehicle()) {
566 if (v
->group_id
!= old_g
) continue;
568 /* Add The Vehicle to the default group */
569 DoCommand(tile
, DEFAULT_GROUP
, v
->index
, flags
, CMD_ADD_VEHICLE_GROUP
, text
);
573 InvalidateWindowData(GetWindowClassForVehicleType(g
->vehicle_type
), VehicleListIdentifier(VL_GROUP_LIST
, g
->vehicle_type
, _current_company
).Pack());
576 return CommandCost();
580 * Set replace protection for a group and its sub-groups.
581 * @param g initial group.
582 * @param protect 1 to set or 0 to clear protection.
584 static void SetGroupReplaceProtection(Group
*g
, bool protect
)
586 g
->replace_protection
= protect
;
590 if (pg
->parent
== g
->index
) SetGroupReplaceProtection(pg
, protect
);
595 * (Un)set global replace protection from a group
597 * @param flags type of operation
598 * @param p1 index of group array
599 * - p1 bit 0-15 : GroupID
601 * - p2 bit 0 : 1 to set or 0 to clear protection.
602 * - p2 bit 1 : 1 to apply to sub-groups.
604 * @return the cost of this operation or an error
606 CommandCost
CmdSetGroupReplaceProtection(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
608 Group
*g
= Group::GetIfValid(p1
);
609 if (g
== NULL
|| g
->owner
!= _current_company
) return CMD_ERROR
;
611 if (flags
& DC_EXEC
) {
613 SetGroupReplaceProtection(g
, HasBit(p2
, 0));
615 g
->replace_protection
= HasBit(p2
, 0);
618 SetWindowDirty(GetWindowClassForVehicleType(g
->vehicle_type
), VehicleListIdentifier(VL_GROUP_LIST
, g
->vehicle_type
, _current_company
).Pack());
619 InvalidateWindowData(WC_REPLACE_VEHICLE
, g
->vehicle_type
);
622 return CommandCost();
626 * Decrease the num_vehicle variable before delete an front engine from a group
627 * @note Called in CmdSellRailWagon and DeleteLasWagon,
628 * @param v FrontEngine of the train we want to remove.
630 void RemoveVehicleFromGroup(const Vehicle
*v
)
632 if (!v
->IsPrimaryVehicle()) return;
634 if (!IsDefaultGroupID(v
->group_id
)) GroupStatistics::CountVehicle(v
, -1);
639 * Affect the groupID of a train to new_g.
640 * @note called in CmdAddVehicleGroup and CmdMoveRailVehicle
641 * @param v First vehicle of the chain.
642 * @param new_g index of array group
644 void SetTrainGroupID(Train
*v
, GroupID new_g
)
646 if (!Group::IsValidID(new_g
) && !IsDefaultGroupID(new_g
)) return;
648 assert(v
->IsFrontEngine() || IsDefaultGroupID(new_g
));
650 for (Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
651 if (u
->IsEngineCountable()) UpdateNumEngineGroup(u
, u
->group_id
, new_g
);
656 /* Update the Replace Vehicle Windows */
657 GroupStatistics::UpdateAutoreplace(v
->owner
);
658 SetWindowDirty(WC_REPLACE_VEHICLE
, VEH_TRAIN
);
663 * Recalculates the groupID of a train. Should be called each time a vehicle is added
664 * to/removed from the chain,.
665 * @note this needs to be called too for 'wagon chains' (in the depot, without an engine)
666 * @note Called in CmdBuildRailVehicle, CmdBuildRailWagon, CmdMoveRailVehicle, CmdSellRailWagon
667 * @param v First vehicle of the chain.
669 void UpdateTrainGroupID(Train
*v
)
671 assert(v
->IsFrontEngine() || v
->IsFreeWagon());
673 GroupID new_g
= v
->IsFrontEngine() ? v
->group_id
: (GroupID
)DEFAULT_GROUP
;
674 for (Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
675 if (u
->IsEngineCountable()) UpdateNumEngineGroup(u
, u
->group_id
, new_g
);
680 /* Update the Replace Vehicle Windows */
681 GroupStatistics::UpdateAutoreplace(v
->owner
);
682 SetWindowDirty(WC_REPLACE_VEHICLE
, VEH_TRAIN
);
686 * Get the number of engines with EngineID id_e in the group with GroupID
687 * id_g and its sub-groups.
688 * @param company The company the group belongs to
689 * @param id_g The GroupID of the group used
690 * @param id_e The EngineID of the engine to count
691 * @return The number of engines with EngineID id_e in the group
693 uint
GetGroupNumEngines(CompanyID company
, GroupID id_g
, EngineID id_e
)
696 const Engine
*e
= Engine::Get(id_e
);
699 if (g
->parent
== id_g
) count
+= GetGroupNumEngines(company
, g
->index
, id_e
);
701 return count
+ GroupStatistics::Get(company
, id_g
, e
->type
).num_engines
[id_e
];
704 void RemoveAllGroupsForCompany(const CompanyID company
)
709 if (company
== g
->owner
) delete g
;
715 * Test if GroupID group is a descendant of (or is) GroupID search
716 * @param search The GroupID to search in
717 * @param group The GroupID to search for
718 * @return True iff group is search or a descendant of search
720 bool GroupIsInGroup(GroupID search
, GroupID group
)
722 if (!Group::IsValidID(search
)) return search
== group
;
725 if (search
== group
) return true;
726 search
= Group::Get(search
)->parent
;
727 } while (search
!= INVALID_GROUP
);