OpenTTD Source: src/group_cmd.cpp Source File

OpenTTD Source 14.0-beta3

group_cmd.cpp
Go to the documentation of this file.
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
10 #include "stdafx.h"
11 #include "command_func.h"
12 #include "train.h"
13 #include "vehiclelist.h"
14 #include "vehicle_func.h"
15 #include "autoreplace_base.h"
16 #include "autoreplace_func.h"
17 #include "string_func.h"
18 #include "company_func.h"
19 #include "core/pool_func.hpp"
20 #include "order_backup.h"
21 #include "group_cmd.h"
22
23 #include "table/strings.h"
24
25 #include "safeguards.h"
26
27 GroupPool _group_pool("Group");
28 INSTANTIATE_POOL_METHODS(Group)
29
30
33 void GroupStatistics::Clear()
34 {
35 this->num_vehicle = 0;
36 this->profit_last_year = 0;
37 this->num_vehicle_min_age = 0;
38 this->profit_last_year_min_age = 0;
39
40 /* This is also called when NewGRF change. So the number of engines might have changed. Reset. */
41 this->num_engines.clear();
42 }
43
49 uint16_t GroupStatistics::GetNumEngines(EngineID engine) const
50 {
51 auto found = this->num_engines.find(engine);
52 if (found != std::end(this->num_engines)) return found->second;
53 return 0;
54 }
55
63 /* static */ GroupStatistics &GroupStatistics::Get(CompanyID company, GroupID id_g, VehicleType type)
64 {
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;
70 }
71
72 if (IsDefaultGroupID(id_g)) return Company::Get(company)->group_default[type];
73 if (IsAllGroupID(id_g)) return Company::Get(company)->group_all[type];
74
75 NOT_REACHED();
76 }
77
83 /* static */ GroupStatistics &GroupStatistics::Get(const Vehicle *v)
84 {
85 return GroupStatistics::Get(v->owner, v->group_id, v->type);
86 }
87
93 /* static */ GroupStatistics &GroupStatistics::GetAllGroup(const Vehicle *v)
94 {
95 return GroupStatistics::Get(v->owner, ALL_GROUP, v->type);
96 }
97
101 /* static */ void GroupStatistics::UpdateAfterLoad()
102 {
103 /* Set up the engine count for all companies */
104 for (Company *c : Company::Iterate()) {
105 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
106 c->group_all[type].Clear();
107 c->group_default[type].Clear();
108 }
109 }
110
111 /* Recalculate */
112 for (Group *g : Group::Iterate()) {
113 g->statistics.Clear();
114 }
115
116 for (const Vehicle *v : Vehicle::Iterate()) {
117 if (!v->IsEngineCountable()) continue;
118
119 GroupStatistics::CountEngine(v, 1);
120 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, 1);
121 }
122
123 for (const Company *c : Company::Iterate()) {
124 GroupStatistics::UpdateAutoreplace(c->index);
125 }
126 }
127
133 /* static */ void GroupStatistics::CountVehicle(const Vehicle *v, int delta)
134 {
135 assert(delta == 1 || delta == -1);
136
137 GroupStatistics &stats_all = GroupStatistics::GetAllGroup(v);
138 GroupStatistics &stats = GroupStatistics::Get(v);
139
140 stats_all.num_vehicle += delta;
141 stats_all.profit_last_year += v->GetDisplayProfitLastYear() * delta;
142 stats.num_vehicle += delta;
143 stats.profit_last_year += v->GetDisplayProfitLastYear() * delta;
144
145 if (v->age > VEHICLE_PROFIT_MIN_AGE) {
146 stats_all.num_vehicle_min_age += delta;
147 stats_all.profit_last_year_min_age += v->GetDisplayProfitLastYear() * delta;
148 stats.num_vehicle_min_age += delta;
149 stats.profit_last_year_min_age += v->GetDisplayProfitLastYear() * delta;
150 }
151 }
152
158 /* static */ void GroupStatistics::CountEngine(const Vehicle *v, int delta)
159 {
160 assert(delta == 1 || delta == -1);
161 GroupStatistics::GetAllGroup(v).num_engines[v->engine_type] += delta;
162 GroupStatistics::Get(v).num_engines[v->engine_type] += delta;
163 }
164
168 /* static */ void GroupStatistics::AddProfitLastYear(const Vehicle *v)
169 {
170 GroupStatistics &stats_all = GroupStatistics::GetAllGroup(v);
171 GroupStatistics &stats = GroupStatistics::Get(v);
172
173 stats_all.profit_last_year += v->GetDisplayProfitLastYear();
174 stats.profit_last_year += v->GetDisplayProfitLastYear();
175 }
176
180 /* static */ void GroupStatistics::VehicleReachedMinAge(const Vehicle *v)
181 {
182 GroupStatistics &stats_all = GroupStatistics::GetAllGroup(v);
183 GroupStatistics &stats = GroupStatistics::Get(v);
184
185 stats_all.num_vehicle_min_age++;
186 stats_all.profit_last_year_min_age += v->GetDisplayProfitLastYear();
187 stats.num_vehicle_min_age++;
188 stats.profit_last_year_min_age += v->GetDisplayProfitLastYear();
189 }
190
194 /* static */ void GroupStatistics::UpdateProfits()
195 {
196 /* Set up the engine count for all companies */
197 for (Company *c : Company::Iterate()) {
198 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
199 c->group_all[type].ClearProfits();
200 c->group_default[type].ClearProfits();
201 }
202 }
203
204 /* Recalculate */
205 for (Group *g : Group::Iterate()) {
206 g->statistics.ClearProfits();
207 }
208
209 for (const Vehicle *v : Vehicle::Iterate()) {
210 if (v->IsPrimaryVehicle()) {
211 GroupStatistics::AddProfitLastYear(v);
212 if (v->age > VEHICLE_PROFIT_MIN_AGE) GroupStatistics::VehicleReachedMinAge(v);
213 }
214 }
215 }
216
221 /* static */ void GroupStatistics::UpdateAutoreplace(CompanyID company)
222 {
223 /* Set up the engine count for all companies */
224 Company *c = Company::Get(company);
225 for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {
226 c->group_all[type].ClearAutoreplace();
227 c->group_default[type].ClearAutoreplace();
228 }
229
230 /* Recalculate */
231 for (Group *g : Group::Iterate()) {
232 if (g->owner != company) continue;
233 g->statistics.ClearAutoreplace();
234 }
235
236 for (EngineRenewList erl = c->engine_renew_list; erl != nullptr; erl = erl->next) {
237 const Engine *e = Engine::Get(erl->from);
238 GroupStatistics &stats = GroupStatistics::Get(company, erl->group_id, e->type);
239 if (!stats.autoreplace_defined) {
240 stats.autoreplace_defined = true;
241 stats.autoreplace_finished = true;
242 }
243 if (GetGroupNumEngines(company, erl->group_id, erl->from) > 0) stats.autoreplace_finished = false;
244 }
245 }
246
254 static inline void UpdateNumEngineGroup(const Vehicle *v, GroupID old_g, GroupID new_g)
255 {
256 if (old_g != new_g) {
257 /* Decrease the num engines in the old group */
258 GroupStatistics::Get(v->owner, old_g, v->type).num_engines[v->engine_type]--;
259
260 /* Increase the num engines in the new group */
261 GroupStatistics::Get(v->owner, new_g, v->type).num_engines[v->engine_type]++;
262 }
263 }
264
265
266 const Livery *GetParentLivery(const Group *g)
267 {
268 if (g->parent == INVALID_GROUP) {
269 const Company *c = Company::Get(g->owner);
270 return &c->livery[LS_DEFAULT];
271 }
272
273 const Group *pg = Group::Get(g->parent);
274 return &pg->livery;
275 }
276
277
283 static void PropagateChildLivery(const Group *g, bool reset_cache)
284 {
285 if (reset_cache) {
286 /* Company colour data is indirectly cached. */
287 for (Vehicle *v : Vehicle::Iterate()) {
288 if (v->group_id == g->index && (!v->IsGroundVehicle() || v->IsFrontEngine())) {
289 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
290 u->colourmap = PAL_NONE;
291 u->InvalidateNewGRFCache();
292 }
293 }
294 }
295 }
296
297 for (Group *cg : Group::Iterate()) {
298 if (cg->parent == g->index) {
299 if (!HasBit(cg->livery.in_use, 0)) cg->livery.colour1 = g->livery.colour1;
300 if (!HasBit(cg->livery.in_use, 1)) cg->livery.colour2 = g->livery.colour2;
301 PropagateChildLivery(cg, reset_cache);
302 }
303 }
304 }
305
311 void UpdateCompanyGroupLiveries(const Company *c)
312 {
313 for (Group *g : Group::Iterate()) {
314 if (g->owner == c->index && g->parent == INVALID_GROUP) {
315 if (!HasBit(g->livery.in_use, 0)) g->livery.colour1 = c->livery[LS_DEFAULT].colour1;
316 if (!HasBit(g->livery.in_use, 1)) g->livery.colour2 = c->livery[LS_DEFAULT].colour2;
317 PropagateChildLivery(g, false);
318 }
319 }
320 }
321
322 Group::Group(Owner owner)
323 {
324 this->owner = owner;
325 this->folded = false;
326 }
327
328
336 std::tuple<CommandCost, GroupID> CmdCreateGroup(DoCommandFlag flags, VehicleType vt, GroupID parent_group)
337 {
338 if (!IsCompanyBuildableVehicleType(vt)) return { CMD_ERROR, INVALID_GROUP };
339
340 if (!Group::CanAllocateItem()) return { CMD_ERROR, INVALID_GROUP };
341
342 const Group *pg = Group::GetIfValid(parent_group);
343 if (pg != nullptr) {
344 if (pg->owner != _current_company) return { CMD_ERROR, INVALID_GROUP };
345 if (pg->vehicle_type != vt) return { CMD_ERROR, INVALID_GROUP };
346 }
347
348 if (flags & DC_EXEC) {
349 Group *g = new Group(_current_company);
350 g->vehicle_type = vt;
351 g->parent = INVALID_GROUP;
352
353 if (pg == nullptr) {
354 const Company *c = Company::Get(_current_company);
355 g->livery.colour1 = c->livery[LS_DEFAULT].colour1;
356 g->livery.colour2 = c->livery[LS_DEFAULT].colour2;
357 if (c->settings.renew_keep_length) SetBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
358 } else {
359 g->parent = pg->index;
360 g->livery.colour1 = pg->livery.colour1;
361 g->livery.colour2 = pg->livery.colour2;
362 g->flags = pg->flags;
363 }
364
365 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
366 InvalidateWindowData(WC_COMPANY_COLOUR, g->owner, g->vehicle_type);
367
368 return { CommandCost(), g->index };
369 }
370
371 return { CommandCost(), INVALID_GROUP};
372 }
373
374
381 CommandCost CmdDeleteGroup(DoCommandFlag flags, GroupID group_id)
382 {
383 Group *g = Group::GetIfValid(group_id);
384 if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
385
386 /* Remove all vehicles from the group */
387 Command<CMD_REMOVE_ALL_VEHICLES_GROUP>::Do(flags, group_id);
388
389 /* Delete sub-groups */
390 for (const Group *gp : Group::Iterate()) {
391 if (gp->parent == g->index) {
392 Command<CMD_DELETE_GROUP>::Do(flags, gp->index);
393 }
394 }
395
396 if (flags & DC_EXEC) {
397 /* Update backupped orders if needed */
398 OrderBackup::ClearGroup(g->index);
399
400 /* If we set an autoreplace for the group we delete, remove it. */
401 if (_current_company < MAX_COMPANIES) {
402 Company *c;
403
404 c = Company::Get(_current_company);
405 for (EngineRenew *er : EngineRenew::Iterate()) {
406 if (er->group_id == g->index) RemoveEngineReplacementForCompany(c, er->from, g->index, flags);
407 }
408 }
409
410 VehicleType vt = g->vehicle_type;
411
412 /* Delete the Replace Vehicle Windows */
413 CloseWindowById(WC_REPLACE_VEHICLE, g->vehicle_type);
414 delete g;
415
416 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
417 InvalidateWindowData(WC_COMPANY_COLOUR, _current_company, vt);
418 }
419
420 return CommandCost();
421 }
422
432 CommandCost CmdAlterGroup(DoCommandFlag flags, AlterGroupMode mode, GroupID group_id, GroupID parent_id, const std::string &text)
433 {
434 Group *g = Group::GetIfValid(group_id);
435 if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
436
437 if (mode == AlterGroupMode::Rename) {
438 /* Rename group */
439 bool reset = text.empty();
440
441 if (!reset) {
442 if (Utf8StringLength(text) >= MAX_LENGTH_GROUP_NAME_CHARS) return CMD_ERROR;
443 }
444
445 if (flags & DC_EXEC) {
446 /* Assign the new one */
447 if (reset) {
448 g->name.clear();
449 } else {
450 g->name = text;
451 }
452 }
453 } else if (mode == AlterGroupMode::SetParent) {
454 /* Set group parent */
455 const Group *pg = Group::GetIfValid(parent_id);
456
457 if (pg != nullptr) {
458 if (pg->owner != _current_company) return CMD_ERROR;
459 if (pg->vehicle_type != g->vehicle_type) return CMD_ERROR;
460
461 /* Ensure request parent isn't child of group.
462 * This is the only place that infinite loops are prevented. */
463 if (GroupIsInGroup(pg->index, g->index)) return_cmd_error(STR_ERROR_GROUP_CAN_T_SET_PARENT_RECURSION);
464 }
465
466 if (flags & DC_EXEC) {
467 g->parent = (pg == nullptr) ? INVALID_GROUP : pg->index;
468 GroupStatistics::UpdateAutoreplace(g->owner);
469
470 if (!HasBit(g->livery.in_use, 0) || !HasBit(g->livery.in_use, 1)) {
471 /* Update livery with new parent's colours if either colour is default. */
472 const Livery *livery = GetParentLivery(g);
473 if (!HasBit(g->livery.in_use, 0)) g->livery.colour1 = livery->colour1;
474 if (!HasBit(g->livery.in_use, 1)) g->livery.colour2 = livery->colour2;
475
476 PropagateChildLivery(g, true);
477 MarkWholeScreenDirty();
478 }
479 }
480 } else {
481 return CMD_ERROR;
482 }
483
484 if (flags & DC_EXEC) {
485 InvalidateWindowData(WC_REPLACE_VEHICLE, g->vehicle_type, 1);
486 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
487 InvalidateWindowData(WC_COMPANY_COLOUR, g->owner, g->vehicle_type);
488 InvalidateWindowClassesData(WC_VEHICLE_VIEW);
489 InvalidateWindowClassesData(WC_VEHICLE_DETAILS);
490 }
491
492 return CommandCost();
493 }
494
495
501 static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
502 {
503 GroupStatistics::CountVehicle(v, -1);
504
505 switch (v->type) {
506 default: NOT_REACHED();
507 case VEH_TRAIN:
508 SetTrainGroupID(Train::From(v), new_g);
509 break;
510
511 case VEH_ROAD:
512 case VEH_SHIP:
513 case VEH_AIRCRAFT:
514 if (v->IsEngineCountable()) UpdateNumEngineGroup(v, v->group_id, new_g);
515 v->group_id = new_g;
516 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
517 u->colourmap = PAL_NONE;
518 u->InvalidateNewGRFCache();
519 u->UpdateViewport(true);
520 }
521 break;
522 }
523
524 GroupStatistics::CountVehicle(v, 1);
525 }
526
535 std::tuple<CommandCost, GroupID> CmdAddVehicleGroup(DoCommandFlag flags, GroupID group_id, VehicleID veh_id, bool add_shared, const VehicleListIdentifier &vli)
536 {
537 GroupID new_g = group_id;
538 if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP) return { CMD_ERROR, INVALID_GROUP };
539
540 VehicleList list;
541 if (veh_id == INVALID_VEHICLE && vli.Valid()) {
542 if (!GenerateVehicleSortList(&list, vli) || list.empty()) return { CMD_ERROR, INVALID_GROUP };
543 } else {
544 Vehicle *v = Vehicle::GetIfValid(veh_id);
545 if (v == nullptr) return { CMD_ERROR, INVALID_GROUP };
546 list.push_back(v);
547 }
548
549 VehicleType vtype = list.front()->type;
550 for (const Vehicle *v : list) {
551 if (v->owner != _current_company || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_GROUP };
552 }
553
554 if (Group::IsValidID(new_g)) {
555 Group *g = Group::Get(new_g);
556 if (g->owner != _current_company || g->vehicle_type != vtype) return { CMD_ERROR, INVALID_GROUP };
557 }
558
559 if (new_g == NEW_GROUP) {
560 /* Create new group. */
561 auto [ret, new_group_id] = CmdCreateGroup(flags, vtype, INVALID_GROUP);
562 if (ret.Failed()) return { ret, new_group_id };
563
564 new_g = new_group_id;
565 }
566
567 if (flags & DC_EXEC) {
568 for (const Vehicle *vc : list) {
569 /* VehicleList is const but we need to modify the vehicle. */
570 Vehicle *v = Vehicle::Get(vc->index);
571 AddVehicleToGroup(v, new_g);
572
573 if (add_shared) {
574 /* Add vehicles in the shared order list as well. */
575 for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
576 if (v2->group_id != new_g) AddVehicleToGroup(v2, new_g);
577 }
578 }
579
580 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
581 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
582 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
583 InvalidateWindowData(WC_VEHICLE_VIEW, v->index);
584 InvalidateWindowData(WC_VEHICLE_DETAILS, v->index);
585 }
586
587 GroupStatistics::UpdateAutoreplace(_current_company);
588
589 /* Update the Replace Vehicle Windows */
590 SetWindowDirty(WC_REPLACE_VEHICLE, vtype);
591 InvalidateWindowData(GetWindowClassForVehicleType(vtype), VehicleListIdentifier(VL_GROUP_LIST, vtype, _current_company).Pack());
592 }
593
594 return { CommandCost(), new_g };
595 }
596
604 CommandCost CmdAddSharedVehicleGroup(DoCommandFlag flags, GroupID id_g, VehicleType type)
605 {
606 if (!Group::IsValidID(id_g) || !IsCompanyBuildableVehicleType(type)) return CMD_ERROR;
607
608 if (flags & DC_EXEC) {
609 /* Find the first front engine which belong to the group id_g
610 * then add all shared vehicles of this front engine to the group id_g */
611 for (const Vehicle *v : Vehicle::Iterate()) {
612 if (v->type == type && v->IsPrimaryVehicle()) {
613 if (v->group_id != id_g) continue;
614
615 /* For each shared vehicles add it to the group */
616 for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
617 if (v2->group_id != id_g) Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, id_g, v2->index, false, VehicleListIdentifier{});
618 }
619 }
620 }
621
622 InvalidateWindowData(GetWindowClassForVehicleType(type), VehicleListIdentifier(VL_GROUP_LIST, type, _current_company).Pack());
623 }
624
625 return CommandCost();
626 }
627
628
635 CommandCost CmdRemoveAllVehiclesGroup(DoCommandFlag flags, GroupID group_id)
636 {
637 Group *g = Group::GetIfValid(group_id);
638
639 if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
640
641 if (flags & DC_EXEC) {
642 /* Find each Vehicle that belongs to the group old_g and add it to the default group */
643 for (const Vehicle *v : Vehicle::Iterate()) {
644 if (v->IsPrimaryVehicle()) {
645 if (v->group_id != group_id) continue;
646
647 /* Add The Vehicle to the default group */
648 Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, DEFAULT_GROUP, v->index, false, VehicleListIdentifier{});
649 }
650 }
651
652 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
653 }
654
655 return CommandCost();
656 }
657
665 CommandCost CmdSetGroupLivery(DoCommandFlag flags, GroupID group_id, bool primary, Colours colour)
666 {
667 Group *g = Group::GetIfValid(group_id);
668
669 if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
670
671 if (colour >= COLOUR_END && colour != INVALID_COLOUR) return CMD_ERROR;
672
673 if (flags & DC_EXEC) {
674 if (primary) {
675 SB(g->livery.in_use, 0, 1, colour != INVALID_COLOUR);
676 if (colour == INVALID_COLOUR) colour = GetParentLivery(g)->colour1;
677 g->livery.colour1 = colour;
678 } else {
679 SB(g->livery.in_use, 1, 1, colour != INVALID_COLOUR);
680 if (colour == INVALID_COLOUR) colour = GetParentLivery(g)->colour2;
681 g->livery.colour2 = colour;
682 }
683
684 PropagateChildLivery(g, true);
685 MarkWholeScreenDirty();
686 }
687
688 return CommandCost();
689 }
690
696 static void SetGroupFlag(Group *g, GroupFlags flag, bool set, bool children)
697 {
698 if (set) {
699 SetBit(g->flags, flag);
700 } else {
701 ClrBit(g->flags, flag);
702 }
703
704 if (!children) return;
705
706 for (Group *pg : Group::Iterate()) {
707 if (pg->parent == g->index) SetGroupFlag(pg, flag, set, true);
708 }
709 }
710
720 CommandCost CmdSetGroupFlag(DoCommandFlag flags, GroupID group_id, GroupFlags flag, bool value, bool recursive)
721 {
722 Group *g = Group::GetIfValid(group_id);
723 if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
724
725 if (flag >= GroupFlags::GF_END) return CMD_ERROR;
726
727 if (flags & DC_EXEC) {
728 SetGroupFlag(g, flag, value, recursive);
729
730 SetWindowDirty(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
731 InvalidateWindowData(WC_REPLACE_VEHICLE, g->vehicle_type);
732 }
733
734 return CommandCost();
735 }
736
743 void SetTrainGroupID(Train *v, GroupID new_g)
744 {
745 if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g)) return;
746
747 assert(v->IsFrontEngine() || IsDefaultGroupID(new_g));
748
749 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
750 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
751
752 u->group_id = new_g;
753 u->colourmap = PAL_NONE;
754 u->InvalidateNewGRFCache();
755 u->UpdateViewport(true);
756 }
757
758 /* Update the Replace Vehicle Windows */
759 GroupStatistics::UpdateAutoreplace(v->owner);
760 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
761 }
762
763
771 void UpdateTrainGroupID(Train *v)
772 {
773 assert(v->IsFrontEngine() || v->IsFreeWagon());
774
775 GroupID new_g = v->IsFrontEngine() ? v->group_id : (GroupID)DEFAULT_GROUP;
776 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
777 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
778
779 u->group_id = new_g;
780 u->colourmap = PAL_NONE;
781 u->InvalidateNewGRFCache();
782 }
783
784 /* Update the Replace Vehicle Windows */
785 GroupStatistics::UpdateAutoreplace(v->owner);
786 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
787 }
788
797 uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
798 {
799 uint count = 0;
800 const Engine *e = Engine::Get(id_e);
801 for (const Group *g : Group::Iterate()) {
802 if (g->parent == id_g) count += GetGroupNumEngines(company, g->index, id_e);
803 }
804 return count + GroupStatistics::Get(company, id_g, e->type).GetNumEngines(id_e);
805 }
806
815 uint GetGroupNumVehicle(CompanyID company, GroupID id_g, VehicleType type)
816 {
817 uint count = 0;
818 for (const Group *g : Group::Iterate()) {
819 if (g->parent == id_g) count += GetGroupNumVehicle(company, g->index, type);
820 }
821 return count + GroupStatistics::Get(company, id_g, type).num_vehicle;
822 }
823
832 uint GetGroupNumVehicleMinAge(CompanyID company, GroupID id_g, VehicleType type)
833 {
834 uint count = 0;
835 for (const Group *g : Group::Iterate()) {
836 if (g->parent == id_g) count += GetGroupNumVehicleMinAge(company, g->index, type);
837 }
838 return count + GroupStatistics::Get(company, id_g, type).num_vehicle_min_age;
839 }
840
849 Money GetGroupProfitLastYearMinAge(CompanyID company, GroupID id_g, VehicleType type)
850 {
851 Money sum = 0;
852 for (const Group *g : Group::Iterate()) {
853 if (g->parent == id_g) sum += GetGroupProfitLastYearMinAge(company, g->index, type);
854 }
855 return sum + GroupStatistics::Get(company, id_g, type).profit_last_year_min_age;
856 }
857
858 void RemoveAllGroupsForCompany(const CompanyID company)
859 {
860 for (Group *g : Group::Iterate()) {
861 if (company == g->owner) delete g;
862 }
863 }
864
865
872 bool GroupIsInGroup(GroupID search, GroupID group)
873 {
874 if (!Group::IsValidID(search)) return search == group;
875
876 do {
877 if (search == group) return true;
878 search = Group::Get(search)->parent;
879 } while (search != INVALID_GROUP);
880
881 return false;
882 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
Vehicle::IsFrontEngine
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:931
CmdAddSharedVehicleGroup
CommandCost CmdAddSharedVehicleGroup(DoCommandFlag flags, GroupID id_g, VehicleType type)
Add all shared vehicles of all vehicles from a group.
Definition: group_cmd.cpp:604
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3200
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
autoreplace_base.h
VehicleList
std::vector< const Vehicle * > VehicleList
A list of vehicles.
Definition: vehiclelist.h:54
Pool::PoolItem<&_group_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:335
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3082
GroupFlags
GroupFlags
Definition: group.h:65
GroupStatistics::CountEngine
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:158
Company::group_all
GroupStatistics group_all[VEH_COMPANY_END]
NOSAVE: Statistics for the ALL_GROUP group.
Definition: company_base.h:126
train.h
command_func.h
Pool::PoolItem<&_group_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:346
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
CmdCreateGroup
std::tuple< CommandCost, GroupID > CmdCreateGroup(DoCommandFlag flags, VehicleType vt, GroupID parent_group)
Create a new vehicle group.
Definition: group_cmd.cpp:336
CmdDeleteGroup
CommandCost CmdDeleteGroup(DoCommandFlag flags, GroupID group_id)
Add all vehicles in the given group to the default group and then deletes the group.
Definition: group_cmd.cpp:381
Vehicle::IsEngineCountable
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
Definition: vehicle.cpp:714
AlterGroupMode
AlterGroupMode
Action for CmdAlterGroup.
Definition: group_cmd.h:23
VehicleListIdentifier
The information about a vehicle list.
Definition: vehiclelist.h:28
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:627
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition: vehicle_base.h:1116
WC_COMPANY_COLOUR
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
Definition: window_type.h:230
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1141
vehiclelist.h
Group::parent
GroupID parent
Parent group.
Definition: group.h:83
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:234
CmdAddVehicleGroup
std::tuple< CommandCost, GroupID > CmdAddVehicleGroup(DoCommandFlag flags, GroupID group_id, VehicleID veh_id, bool add_shared, const VehicleListIdentifier &vli)
Add a vehicle to a group.
Definition: group_cmd.cpp:535
GroupStatistics::num_engines
std::map< EngineID, uint16_t > num_engines
Caches the number of engines of each type the company owns.
Definition: group.h:27
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:357
UpdateNumEngineGroup
static void UpdateNumEngineGroup(const Vehicle *v, GroupID old_g, GroupID new_g)
Update the num engines of a groupID.
Definition: group_cmd.cpp:254
GroupStatistics::CountVehicle
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:133
GroupStatistics::VehicleReachedMinAge
static void VehicleReachedMinAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
Definition: group_cmd.cpp:180
GroupStatistics::autoreplace_finished
bool autoreplace_finished
Have all autoreplacement finished?
Definition: group.h:31
Group::livery
Livery livery
Custom colour scheme for vehicles in this group.
Definition: group.h:78
MAX_LENGTH_GROUP_NAME_CHARS
static const uint MAX_LENGTH_GROUP_NAME_CHARS
The maximum length of a group name in characters including '\0'.
Definition: group_type.h:20
Engine
Definition: engine_base.h:37
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
GroupStatistics::profit_last_year
Money profit_last_year
Sum of profits for all vehicles.
Definition: group.h:25
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:304
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:371
Group::vehicle_type
VehicleType vehicle_type
Vehicle type of the group.
Definition: group.h:75
NEW_GROUP
static const GroupID NEW_GROUP
Sentinel for a to-be-created group.
Definition: group_type.h:15
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:369
GetGroupProfitLastYearMinAge
Money GetGroupProfitLastYearMinAge(CompanyID company, GroupID id_g, VehicleType type)
Get last year's profit of vehicles above minimum age for the group with GroupID id_g and its sub-grou...
Definition: group_cmd.cpp:849
SetTrainGroupID
void SetTrainGroupID(Train *v, GroupID new_g)
Affect the groupID of a train to new_g.
Definition: group_cmd.cpp:743
UpdateTrainGroupID
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
Definition: group_cmd.cpp:771
ALL_GROUP
static const GroupID ALL_GROUP
All vehicles are in this group.
Definition: group_type.h:16
Group
Group data.
Definition: group.h:72
CompanySettings::renew_keep_length
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
Definition: settings_type.h:612
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:378
AlterGroupMode::Rename
@ Rename
Change group name.
GroupStatistics
Statistics and caches on the vehicles in a group.
Definition: group.h:24
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
INVALID_GROUP
static const GroupID INVALID_GROUP
Sentinel for invalid groups.
Definition: group_type.h:18
CommandCost
Common return value for all commands.
Definition: command_type.h:23
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition: window_type.h:339
VEH_COMPANY_END
@ VEH_COMPANY_END
Last company-ownable type.
Definition: vehicle_type.h:29
PropagateChildLivery
static void PropagateChildLivery(const Group *g, bool reset_cache)
Propagate a livery change to a group's children, and optionally update cached vehicle colourmaps.
Definition: group_cmd.cpp:283
Group::statistics
GroupStatistics statistics
NOSAVE: Statistics and caches on the vehicles in the group.
Definition: group.h:79
Company::group_default
GroupStatistics group_default[VEH_COMPANY_END]
NOSAVE: Statistics for the DEFAULT_GROUP group.
Definition: company_base.h:127
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:260
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:54
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:318
GetGroupNumVehicle
uint GetGroupNumVehicle(CompanyID company, GroupID id_g, VehicleType type)
Get the number of vehicles in the group with GroupID id_g and its sub-groups.
Definition: group_cmd.cpp:815
WC_REPLACE_VEHICLE
@ WC_REPLACE_VEHICLE
Replace vehicle window; Window numbers:
Definition: window_type.h:218
Group::owner
Owner owner
Group Owner.
Definition: group.h:74
IsCompanyBuildableVehicleType
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
Livery::in_use
byte in_use
Bit 0 set if this livery should override the default livery first colour, Bit 1 for the second colour...
Definition: livery.h:79
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:105
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition: window_type.h:200
GetGroupNumVehicleMinAge
uint GetGroupNumVehicleMinAge(CompanyID company, GroupID id_g, VehicleType type)
Get the number of vehicles above profit minimum age in the group with GroupID id_g and its sub-groups...
Definition: group_cmd.cpp:832
VehicleListIdentifier::Pack
uint32_t Pack() const
Pack a VehicleListIdentifier in a single uint32.
Definition: vehiclelist.cpp:22
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
GenerateVehicleSortList
bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli)
Generate a list of vehicles based on window type.
Definition: vehiclelist.cpp:114
safeguards.h
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:221
Train
'Train' is either a loco or a wagon.
Definition: train.h:89
GroupStatistics::Get
static GroupStatistics & Get(CompanyID company, GroupID id_g, VehicleType type)
Returns the GroupStatistics for a specific group.
Definition: group_cmd.cpp:63
DEFAULT_GROUP
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition: group_type.h:17
GroupStatistics::GetAllGroup
static GroupStatistics & GetAllGroup(const Vehicle *v)
Returns the GroupStatistic for the ALL_GROUPO of a vehicle type.
Definition: group_cmd.cpp:93
GroupStatistics::profit_last_year_min_age
Money profit_last_year_min_age
Sum of profits for vehicles considered for profit statistics.
Definition: group.h:26
VehicleID
uint32_t VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:16
_group_pool
GroupPool _group_pool("Group")
Pool of groups.
EngineRenew
Struct to store engine replacements.
Definition: autoreplace_base.h:33
stdafx.h
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
CmdRemoveAllVehiclesGroup
CommandCost CmdRemoveAllVehiclesGroup(DoCommandFlag flags, GroupID group_id)
Remove all vehicles from a group.
Definition: group_cmd.cpp:635
GroupStatistics::num_vehicle
uint16_t num_vehicle
Number of vehicles.
Definition: group.h:28
GroupStatistics::autoreplace_defined
bool autoreplace_defined
Are any autoreplace rules set?
Definition: group.h:30
group_cmd.h
CmdSetGroupFlag
CommandCost CmdSetGroupFlag(DoCommandFlag flags, GroupID group_id, GroupFlags flag, bool value, bool recursive)
(Un)set group flag from a group
Definition: group_cmd.cpp:720
CmdSetGroupLivery
CommandCost CmdSetGroupLivery(DoCommandFlag flags, GroupID group_id, bool primary, Colours colour)
Set the livery for a vehicle group.
Definition: group_cmd.cpp:665
string_func.h
IsAllGroupID
bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition: group.h:99
Vehicle::FirstShared
Vehicle * FirstShared() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:721
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:50
vehicle_func.h
Pool::PoolItem<&_company_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:384
Pool
Base class for all pools.
Definition: pool_type.hpp:80
Group::flags
uint8_t flags
Group flags.
Definition: group.h:77
GroupStatistics::UpdateProfits
static void UpdateProfits()
Recompute the profits for all groups.
Definition: group_cmd.cpp:194
SetGroupFlag
static void SetGroupFlag(Group *g, GroupFlags flag, bool set, bool children)
Set group flag for a group and its sub-groups.
Definition: group_cmd.cpp:696
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1201
GetGroupNumEngines
uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
Get the number of engines with EngineID id_e in the group with GroupID id_g and its sub-groups.
Definition: group_cmd.cpp:797
InvalidateWindowClassesData
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition: window.cpp:3217
CmdAlterGroup
CommandCost CmdAlterGroup(DoCommandFlag flags, AlterGroupMode mode, GroupID group_id, GroupID parent_id, const std::string &text)
Alter a group.
Definition: group_cmd.cpp:432
Livery::colour1
Colours colour1
First colour, for all vehicles.
Definition: livery.h:80
Vehicle::NextShared
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
Definition: vehicle_base.h:709
GroupIsInGroup
bool GroupIsInGroup(GroupID search, GroupID group)
Test if GroupID group is a descendant of (or is) GroupID search.
Definition: group_cmd.cpp:872
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:351
Vehicle::age
TimerGameCalendar::Date age
Age in days.
Definition: vehicle_base.h:288
Pool::PoolItem<&_group_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:305
OrderBackup::ClearGroup
static void ClearGroup(GroupID group)
Clear the group of all backups having this group ID.
Definition: order_backup.cpp:218
GroupID
uint16_t GroupID
Type for all group identifiers.
Definition: group_type.h:13
RemoveEngineReplacementForCompany
CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine, GroupID group, DoCommandFlag flags)
Remove an engine replacement for the company.
Definition: autoreplace_func.h:93
Group::name
std::string name
Group Name.
Definition: group.h:73
company_func.h
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:225
CommandHelper
Definition: command_func.h:93
AlterGroupMode::SetParent
@ SetParent
Change group parent.
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1552
OverflowSafeInt< int64_t >
Group::folded
bool folded
NOSAVE: Is this group folded in the group view?
Definition: group.h:81
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
EngineID
uint16_t EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
GroundVehicle::IsFreeWagon
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
Definition: ground_vehicle.hpp:309
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
Pool::PoolItem<&_group_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:324
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:51
GroupStatistics::GetNumEngines
uint16_t GetNumEngines(EngineID engine) const
Get number of vehicles of a specific engine ID.
Definition: group_cmd.cpp:49
CompanyProperties::engine_renew_list
EngineRenewList engine_renew_list
Engine renewals of this company.
Definition: company_base.h:104
autoreplace_func.h
pool_func.hpp
order_backup.h
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
Company
Definition: company_base.h:116
AddVehicleToGroup
static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
Do add a vehicle to a group.
Definition: group_cmd.cpp:501
Livery::colour2
Colours colour2
Second colour, for vehicles with 2CC support.
Definition: livery.h:81
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
UpdateCompanyGroupLiveries
void UpdateCompanyGroupLiveries(const Company *c)
Update group liveries for a company.
Definition: group_cmd.cpp:311
Livery
Information about a particular livery.
Definition: livery.h:78
Vehicle::GetDisplayProfitLastYear
Money GetDisplayProfitLastYear() const
Gets the profit vehicle had last year.
Definition: vehicle_base.h:618
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:56
GroupStatistics::UpdateAfterLoad
static void UpdateAfterLoad()
Update all caches after loading a game, changing NewGRF, etc.
Definition: group_cmd.cpp:101
GetWindowClassForVehicleType
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:97
GF_REPLACE_WAGON_REMOVAL
@ GF_REPLACE_WAGON_REMOVAL
If set, autoreplace will perform wagon removal on vehicles in this group.
Definition: group.h:67
VEHICLE_PROFIT_MIN_AGE
static const int VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
Definition: vehicle_func.h:27
GroupStatistics::AddProfitLastYear
static void AddProfitLastYear(const Vehicle *v)
Add a vehicle's last year profit to the profit sum of its group.
Definition: group_cmd.cpp:168
GroupStatistics::num_vehicle_min_age
uint16_t num_vehicle_min_age
Number of vehicles considered for profit statistics;.
Definition: group.h:29
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103