(svn r25652) -Fix: Improve text caret movement for complex scripts.
[openttd/fttd.git] / src / group_cmd.cpp
blobe86b9de2833324eb700206bf79a72be54cc545b7
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 GroupPool _group_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 tile unused
271 * @param flags type of operation
272 * @param p1 vehicle type
273 * @param p2 unused
274 * @param text unused
275 * @return the cost of this operation or an error
277 CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
279 VehicleType vt = Extract<VehicleType, 0, 3>(p1);
280 if (!IsCompanyBuildableVehicleType(vt)) return CMD_ERROR;
282 if (!Group::CanAllocateItem()) return CMD_ERROR;
284 if (flags & DC_EXEC) {
285 Group *g = new Group(_current_company);
286 g->replace_protection = false;
287 g->vehicle_type = vt;
289 _new_group_id = g->index;
291 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
294 return CommandCost();
299 * Add all vehicles in the given group to the default group and then deletes the group.
300 * @param tile unused
301 * @param flags type of operation
302 * @param p1 index of array group
303 * - p1 bit 0-15 : GroupID
304 * @param p2 unused
305 * @param text unused
306 * @return the cost of this operation or an error
308 CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
310 Group *g = Group::GetIfValid(p1);
311 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
313 /* Remove all vehicles from the group */
314 DoCommand(0, p1, 0, flags, CMD_REMOVE_ALL_VEHICLES_GROUP);
316 if (flags & DC_EXEC) {
317 /* Update backupped orders if needed */
318 OrderBackup::ClearGroup(g->index);
320 /* If we set an autoreplace for the group we delete, remove it. */
321 if (_current_company < MAX_COMPANIES) {
322 Company *c;
323 EngineRenew *er;
325 c = Company::Get(_current_company);
326 FOR_ALL_ENGINE_RENEWS(er) {
327 if (er->group_id == g->index) RemoveEngineReplacementForCompany(c, er->from, g->index, flags);
331 VehicleType vt = g->vehicle_type;
333 /* Delete the Replace Vehicle Windows */
334 DeleteWindowById(WC_REPLACE_VEHICLE, g->vehicle_type);
335 delete g;
337 InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
340 return CommandCost();
343 static bool IsUniqueGroupNameForVehicleType(const char *name, VehicleType type)
345 const Group *g;
347 FOR_ALL_GROUPS(g) {
348 if (g->name != NULL && g->vehicle_type == type && strcmp(g->name, name) == 0) return false;
351 return true;
355 * Rename a group
356 * @param tile unused
357 * @param flags type of operation
358 * @param p1 index of array group
359 * - p1 bit 0-15 : GroupID
360 * @param p2 unused
361 * @param text the new name or an empty string when resetting to the default
362 * @return the cost of this operation or an error
364 CommandCost CmdRenameGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
366 Group *g = Group::GetIfValid(p1);
367 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
369 bool reset = StrEmpty(text);
371 if (!reset) {
372 if (Utf8StringLength(text) >= MAX_LENGTH_GROUP_NAME_CHARS) return CMD_ERROR;
373 if (!IsUniqueGroupNameForVehicleType(text, g->vehicle_type)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
376 if (flags & DC_EXEC) {
377 /* Delete the old name */
378 free(g->name);
379 /* Assign the new one */
380 g->name = reset ? NULL : strdup(text);
382 SetWindowDirty(WC_REPLACE_VEHICLE, g->vehicle_type);
383 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
386 return CommandCost();
391 * Do add a vehicle to a group.
392 * @param v Vehicle to add.
393 * @param new_g Group to add to.
395 static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
397 GroupStatistics::CountVehicle(v, -1);
399 switch (v->type) {
400 default: NOT_REACHED();
401 case VEH_TRAIN:
402 SetTrainGroupID(Train::From(v), new_g);
403 break;
405 case VEH_ROAD:
406 case VEH_SHIP:
407 case VEH_AIRCRAFT:
408 if (v->IsEngineCountable()) UpdateNumEngineGroup(v, v->group_id, new_g);
409 v->group_id = new_g;
410 break;
413 GroupStatistics::CountVehicle(v, 1);
417 * Add a vehicle to a group
418 * @param tile unused
419 * @param flags type of operation
420 * @param p1 index of array group
421 * - p1 bit 0-15 : GroupID
422 * @param p2 vehicle to add to a group
423 * - p2 bit 0-19 : VehicleID
424 * - p2 bit 31 : Add shared vehicles as well.
425 * @param text unused
426 * @return the cost of this operation or an error
428 CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
430 Vehicle *v = Vehicle::GetIfValid(GB(p2, 0, 20));
431 GroupID new_g = p1;
433 if (v == NULL || (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP)) return CMD_ERROR;
435 if (Group::IsValidID(new_g)) {
436 Group *g = Group::Get(new_g);
437 if (g->owner != _current_company || g->vehicle_type != v->type) return CMD_ERROR;
440 if (v->owner != _current_company || !v->IsPrimaryVehicle()) return CMD_ERROR;
442 if (new_g == NEW_GROUP) {
443 /* Create new group. */
444 CommandCost ret = CmdCreateGroup(0, flags, v->type, 0, NULL);
445 if (ret.Failed()) return ret;
447 new_g = _new_group_id;
450 if (flags & DC_EXEC) {
451 AddVehicleToGroup(v, new_g);
453 if (HasBit(p2, 31)) {
454 /* Add vehicles in the shared order list as well. */
455 for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
456 if (v2->group_id != new_g) AddVehicleToGroup(v2, new_g);
460 GroupStatistics::UpdateAutoreplace(v->owner);
462 /* Update the Replace Vehicle Windows */
463 SetWindowDirty(WC_REPLACE_VEHICLE, v->type);
464 InvalidateWindowData(GetWindowClassForVehicleType(v->type), VehicleListIdentifier(VL_GROUP_LIST, v->type, _current_company).Pack());
467 return CommandCost();
471 * Add all shared vehicles of all vehicles from a group
472 * @param tile unused
473 * @param flags type of operation
474 * @param p1 index of group array
475 * - p1 bit 0-15 : GroupID
476 * @param p2 type of vehicles
477 * @param text unused
478 * @return the cost of this operation or an error
480 CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
482 VehicleType type = Extract<VehicleType, 0, 3>(p2);
483 GroupID id_g = p1;
484 if (!Group::IsValidID(id_g) || !IsCompanyBuildableVehicleType(type)) return CMD_ERROR;
486 if (flags & DC_EXEC) {
487 Vehicle *v;
489 /* Find the first front engine which belong to the group id_g
490 * then add all shared vehicles of this front engine to the group id_g */
491 FOR_ALL_VEHICLES(v) {
492 if (v->type == type && v->IsPrimaryVehicle()) {
493 if (v->group_id != id_g) continue;
495 /* For each shared vehicles add it to the group */
496 for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
497 if (v2->group_id != id_g) DoCommand(tile, id_g, v2->index, flags, CMD_ADD_VEHICLE_GROUP, text);
502 InvalidateWindowData(GetWindowClassForVehicleType(type), VehicleListIdentifier(VL_GROUP_LIST, type, _current_company).Pack());
505 return CommandCost();
510 * Remove all vehicles from a group
511 * @param tile unused
512 * @param flags type of operation
513 * @param p1 index of group array
514 * - p1 bit 0-15 : GroupID
515 * @param p2 unused
516 * @param text unused
517 * @return the cost of this operation or an error
519 CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
521 GroupID old_g = p1;
522 Group *g = Group::GetIfValid(old_g);
524 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
526 if (flags & DC_EXEC) {
527 Vehicle *v;
529 /* Find each Vehicle that belongs to the group old_g and add it to the default group */
530 FOR_ALL_VEHICLES(v) {
531 if (v->IsPrimaryVehicle()) {
532 if (v->group_id != old_g) continue;
534 /* Add The Vehicle to the default group */
535 DoCommand(tile, DEFAULT_GROUP, v->index, flags, CMD_ADD_VEHICLE_GROUP, text);
539 InvalidateWindowData(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
542 return CommandCost();
547 * (Un)set global replace protection from a group
548 * @param tile unused
549 * @param flags type of operation
550 * @param p1 index of group array
551 * - p1 bit 0-15 : GroupID
552 * @param p2
553 * - p2 bit 0 : 1 to set or 0 to clear protection.
554 * @param text unused
555 * @return the cost of this operation or an error
557 CommandCost CmdSetGroupReplaceProtection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
559 Group *g = Group::GetIfValid(p1);
560 if (g == NULL || g->owner != _current_company) return CMD_ERROR;
562 if (flags & DC_EXEC) {
563 g->replace_protection = HasBit(p2, 0);
565 SetWindowDirty(GetWindowClassForVehicleType(g->vehicle_type), VehicleListIdentifier(VL_GROUP_LIST, g->vehicle_type, _current_company).Pack());
566 InvalidateWindowData(WC_REPLACE_VEHICLE, g->vehicle_type);
569 return CommandCost();
573 * Decrease the num_vehicle variable before delete an front engine from a group
574 * @note Called in CmdSellRailWagon and DeleteLasWagon,
575 * @param v FrontEngine of the train we want to remove.
577 void RemoveVehicleFromGroup(const Vehicle *v)
579 if (!v->IsPrimaryVehicle()) return;
581 if (!IsDefaultGroupID(v->group_id)) GroupStatistics::CountVehicle(v, -1);
586 * Affect the groupID of a train to new_g.
587 * @note called in CmdAddVehicleGroup and CmdMoveRailVehicle
588 * @param v First vehicle of the chain.
589 * @param new_g index of array group
591 void SetTrainGroupID(Train *v, GroupID new_g)
593 if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g)) return;
595 assert(v->IsFrontEngine() || IsDefaultGroupID(new_g));
597 for (Vehicle *u = v; u != NULL; u = u->Next()) {
598 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
600 u->group_id = new_g;
603 /* Update the Replace Vehicle Windows */
604 GroupStatistics::UpdateAutoreplace(v->owner);
605 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
610 * Recalculates the groupID of a train. Should be called each time a vehicle is added
611 * to/removed from the chain,.
612 * @note this needs to be called too for 'wagon chains' (in the depot, without an engine)
613 * @note Called in CmdBuildRailVehicle, CmdBuildRailWagon, CmdMoveRailVehicle, CmdSellRailWagon
614 * @param v First vehicle of the chain.
616 void UpdateTrainGroupID(Train *v)
618 assert(v->IsFrontEngine() || v->IsFreeWagon());
620 GroupID new_g = v->IsFrontEngine() ? v->group_id : (GroupID)DEFAULT_GROUP;
621 for (Vehicle *u = v; u != NULL; u = u->Next()) {
622 if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
624 u->group_id = new_g;
627 /* Update the Replace Vehicle Windows */
628 GroupStatistics::UpdateAutoreplace(v->owner);
629 SetWindowDirty(WC_REPLACE_VEHICLE, VEH_TRAIN);
633 * Get the number of engines with EngineID id_e in the group with GroupID
634 * id_g
635 * @param company The company the group belongs to
636 * @param id_g The GroupID of the group used
637 * @param id_e The EngineID of the engine to count
638 * @return The number of engines with EngineID id_e in the group
640 uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
642 const Engine *e = Engine::Get(id_e);
643 return GroupStatistics::Get(company, id_g, e->type).num_engines[id_e];
646 void RemoveAllGroupsForCompany(const CompanyID company)
648 Group *g;
650 FOR_ALL_GROUPS(g) {
651 if (company == g->owner) delete g;