OpenTTD Source: src/linkgraph/linkgraphjob.cpp Source File

OpenTTD Source 13.1

linkgraphjob.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 "../core/pool_func.hpp"
12 #include "../window_func.h"
13 #include "linkgraphjob.h"
14 #include "linkgraphschedule.h"
15
16 #include "../safeguards.h"
17
18 /* Initialize the link-graph-job-pool */
19 LinkGraphJobPool _link_graph_job_pool("LinkGraphJob");
20 INSTANTIATE_POOL_METHODS(LinkGraphJob)
21
22
27 /* static */ Path *Path::invalid_path = new Path(INVALID_NODE, true);
28
35 LinkGraphJob::LinkGraphJob(const LinkGraph &orig) :
36 /* Copying the link graph here also copies its index member.
37 * This is on purpose. */
38 link_graph(orig),
39 settings(_settings_game.linkgraph),
40 join_date(_date + _settings_game.linkgraph.recalc_time),
41 job_completed(false),
42 job_aborted(false)
43 {
44 }
45
50 void LinkGraphJob::EraseFlows(NodeID from)
51 {
52 for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
53 (*this)[node_id].Flows().erase(from);
54 }
55 }
56
61 void LinkGraphJob::SpawnThread()
62 {
63 if (!StartNewThread(&this->thread, "ottd:linkgraph", &(LinkGraphSchedule::Run), this)) {
64 /* Of course this will hang a bit.
65 * On the other hand, if you want to play games which make this hang noticeably
66 * on a platform without threads then you'll probably get other problems first.
67 * OK:
68 * If someone comes and tells me that this hangs for them, I'll implement a
69 * smaller grained "Step" method for all handlers and add some more ticks where
70 * "Step" is called. No problem in principle. */
71 LinkGraphSchedule::Run(this);
72 }
73 }
74
78 void LinkGraphJob::JoinThread()
79 {
80 if (this->thread.joinable()) {
81 this->thread.join();
82 }
83 }
84
88 LinkGraphJob::~LinkGraphJob()
89 {
90 this->JoinThread();
91
92 /* Don't update stuff from other pools, when everything is being removed.
93 * Accessing other pools may be invalid. */
94 if (CleaningPool()) return;
95
96 /* If the job has been aborted, the job state is invalid.
97 * This should never be reached, as once the job has been marked as aborted
98 * the only valid job operation is to clear the LinkGraphJob pool. */
99 assert(!this->IsJobAborted());
100
101 /* Link graph has been merged into another one. */
102 if (!LinkGraph::IsValidID(this->link_graph.index)) return;
103
104 uint16 size = this->Size();
105 for (NodeID node_id = 0; node_id < size; ++node_id) {
106 Node from = (*this)[node_id];
107
108 /* The station can have been deleted. Remove all flows originating from it then. */
109 Station *st = Station::GetIfValid(from.Station());
110 if (st == nullptr) {
111 this->EraseFlows(node_id);
112 continue;
113 }
114
115 /* Link graph merging and station deletion may change around IDs. Make
116 * sure that everything is still consistent or ignore it otherwise. */
117 GoodsEntry &ge = st->goods[this->Cargo()];
118 if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
119 this->EraseFlows(node_id);
120 continue;
121 }
122
123 LinkGraph *lg = LinkGraph::Get(ge.link_graph);
124 FlowStatMap &flows = from.Flows();
125
126 for (EdgeIterator it(from.Begin()); it != from.End(); ++it) {
127 if (from[it->first].Flow() == 0) continue;
128 StationID to = (*this)[it->first].Station();
129 Station *st2 = Station::GetIfValid(to);
130 if (st2 == nullptr || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
131 st2->goods[this->Cargo()].node != it->first ||
132 (*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
133 /* Edge has been removed. Delete flows. */
134 StationIDStack erased = flows.DeleteFlows(to);
135 /* Delete old flows for source stations which have been deleted
136 * from the new flows. This avoids flow cycles between old and
137 * new flows. */
138 while (!erased.IsEmpty()) ge.flows.erase(erased.Pop());
139 } else if ((*lg)[node_id][it->first].LastUnrestrictedUpdate() == INVALID_DATE) {
140 /* Edge is fully restricted. */
141 flows.RestrictFlows(to);
142 }
143 }
144
145 /* Swap shares and invalidate ones that are completely deleted. Don't
146 * really delete them as we could then end up with unroutable cargo
147 * somewhere. Do delete them and also reroute relevant cargo if
148 * automatic distribution has been turned off for that cargo. */
149 for (FlowStatMap::iterator it(ge.flows.begin()); it != ge.flows.end();) {
150 FlowStatMap::iterator new_it = flows.find(it->first);
151 if (new_it == flows.end()) {
152 if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
153 it->second.Invalidate();
154 ++it;
155 } else {
156 FlowStat shares(INVALID_STATION, 1);
157 it->second.SwapShares(shares);
158 ge.flows.erase(it++);
159 for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
160 shares_it != shares.GetShares()->end(); ++shares_it) {
161 RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
162 }
163 }
164 } else {
165 it->second.SwapShares(new_it->second);
166 flows.erase(new_it);
167 ++it;
168 }
169 }
170 ge.flows.insert(flows.begin(), flows.end());
171 InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
172 }
173 }
174
180 void LinkGraphJob::Init()
181 {
182 uint size = this->Size();
183 this->nodes.resize(size);
184 this->edges.Resize(size, size);
185 for (uint i = 0; i < size; ++i) {
186 this->nodes[i].Init(this->link_graph[i].Supply());
187 EdgeAnnotation *node_edges = this->edges[i];
188 for (uint j = 0; j < size; ++j) {
189 node_edges[j].Init();
190 }
191 }
192 }
193
197 void LinkGraphJob::EdgeAnnotation::Init()
198 {
199 this->demand = 0;
200 this->flow = 0;
201 this->unsatisfied_demand = 0;
202 }
203
209 void LinkGraphJob::NodeAnnotation::Init(uint supply)
210 {
211 this->undelivered_supply = supply;
212 new (&this->flows) FlowStatMap;
213 new (&this->paths) PathList;
214 }
215
224 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
225 {
226 this->capacity = std::min(base->capacity, cap);
227 this->free_capacity = std::min(base->free_capacity, free_cap);
228 this->distance = base->distance + dist;
229 assert(this->distance > 0);
230 if (this->parent != base) {
231 this->Detach();
232 this->parent = base;
233 this->parent->num_children++;
234 }
235 this->origin = base->origin;
236 }
237
246 uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
247 {
248 if (this->parent != nullptr) {
249 LinkGraphJob::Edge edge = job[this->parent->node][this->node];
250 if (max_saturation != UINT_MAX) {
251 uint usable_cap = edge.Capacity() * max_saturation / 100;
252 if (usable_cap > edge.Flow()) {
253 new_flow = std::min(new_flow, usable_cap - edge.Flow());
254 } else {
255 return 0;
256 }
257 }
258 new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
259 if (this->flow == 0 && new_flow > 0) {
260 job[this->parent->node].Paths().push_front(this);
261 }
262 edge.AddFlow(new_flow);
263 }
264 this->flow += new_flow;
265 return new_flow;
266 }
267
273 Path::Path(NodeID n, bool source) :
274 distance(source ? 0 : UINT_MAX),
275 capacity(source ? UINT_MAX : 0),
276 free_capacity(source ? INT_MAX : INT_MIN),
277 flow(0), node(n), origin(source ? n : INVALID_NODE),
278 num_children(0), parent(nullptr)
279 {}
280
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:3252
SmallStack
Minimal stack that uses a pool to avoid pointers.
Definition: smallstack_type.hpp:136
Path::capacity
uint capacity
This capacity is min(capacity) fom all edges.
Definition: linkgraphjob.h:449
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:483
SmallStack::Pop
Titem Pop()
Pop an item from the stack.
Definition: smallstack_type.hpp:213
LinkGraphJob::EdgeAnnotation::demand
uint demand
Transport demand between the nodes.
Definition: linkgraphjob.h:36
Path
A leg of a path in the link graph.
Definition: linkgraphjob.h:365
Pool::PoolItem<&_link_graph_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:39
LinkGraphJob::Node
Link graph job node.
Definition: linkgraphjob.h:185
RerouteCargo
void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
Definition: station_cmd.cpp:3586
LinkGraphJob::nodes
NodeAnnotationVector nodes
Extra node data necessary for link graph calculation.
Definition: linkgraphjob.h:63
Path::invalid_path
static Path * invalid_path
Static instance of an invalid path.
Definition: linkgraphjob.h:367
LinkGraphJob::Edge::Flow
uint Flow() const
Get the total flow on the edge.
Definition: linkgraphjob.h:106
Station
Station data structure.
Definition: station_base.h:454
LinkGraphJob
Class for calculation jobs to be run on link graphs.
Definition: linkgraphjob.h:30
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
LinkGraphJob::~LinkGraphJob
~LinkGraphJob()
Join the link graph job and destroy it.
Definition: linkgraphjob.cpp:88
DT_MANUAL
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
Definition: linkgraph_type.h:25
LinkGraphJob::EdgeAnnotation::Init
void Init()
Initialize a linkgraph job edge.
Definition: linkgraphjob.cpp:197
Path::Fork
void Fork(Path *base, uint cap, int free_cap, uint dist)
Add this path as a new child to the given base path, thus making this path a "fork" of the base path.
Definition: linkgraphjob.cpp:224
LinkGraphJob::JoinThread
void JoinThread()
Join the calling thread with this job's thread if threading is enabled.
Definition: linkgraphjob.cpp:78
LinkGraphJob::EdgeAnnotation::flow
uint flow
Planned flow over this edge.
Definition: linkgraphjob.h:38
Path::origin
NodeID origin
Link graph node this path originates from.
Definition: linkgraphjob.h:453
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:338
LinkGraphJob::edges
EdgeAnnotationMatrix edges
Extra edge data necessary for link graph calculation.
Definition: linkgraphjob.h:64
LinkGraphJob::Size
NodeID Size() const
Get the size of the underlying link graph.
Definition: linkgraphjob.h:335
FlowStatMap::RestrictFlows
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:4645
_link_graph_job_pool
LinkGraphJobPool _link_graph_job_pool("LinkGraphJob")
The actual pool with link graph jobs.
FlowStat
Flow statistics telling how much flow should be sent along a link.
Definition: station_base.h:33
FlowStatMap::DeleteFlows
StationIDStack DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:4625
SmallMatrix::Resize
void Resize(uint new_width, uint new_height)
Set the size to a specific width and height, preserving item positions as far as possible in the proc...
Definition: smallmatrix_type.hpp:214
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
LinkGraphJob::SpawnThread
void SpawnThread()
Spawn a thread if possible and run the link graph job in the thread.
Definition: linkgraphjob.cpp:61
LinkGraphJob::EdgeAnnotation::unsatisfied_demand
uint unsatisfied_demand
Demand over this edge that hasn't been satisfied yet.
Definition: linkgraphjob.h:37
FlowStat::GetShares
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
Definition: station_base.h:89
LinkGraphJob::EdgeAnnotation
Annotation for a link graph edge.
Definition: linkgraphjob.h:35
GoodsEntry::node
NodeID node
ID of node in link graph referring to this goods entry.
Definition: station_base.h:255
LinkGraphJob::link_graph
const LinkGraph link_graph
Link graph to by analyzed. Is copied when job is started and mustn't be modified later.
Definition: linkgraphjob.h:59
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:46
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
LinkGraphJob::thread
std::thread thread
Thread the job is running in or a default-constructed thread if it's running in the main thread.
Definition: linkgraphjob.h:61
LinkGraph::EdgeWrapper::Capacity
uint Capacity() const
Get edge's capacity.
Definition: linkgraph.h:93
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
LinkGraphJob::Edge
A job edge.
Definition: linkgraphjob.h:78
GameSettings::linkgraph
LinkGraphSettings linkgraph
settings for link graph calculations
Definition: settings_type.h:597
linkgraphschedule.h
GoodsEntry::link_graph
LinkGraphID link_graph
Link graph this station belongs to.
Definition: station_base.h:254
LinkGraph::NodeWrapper::Station
StationID Station() const
Get ID of station belonging to wrapped node.
Definition: linkgraph.h:165
Path::distance
uint distance
Sum(distance of all legs up to this one).
Definition: linkgraphjob.h:448
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:167
Pool
Base class for all pools.
Definition: pool_type.hpp:81
LinkGraphJob::Node::Flows
FlowStatMap & Flows()
Get the flows running through this node.
Definition: linkgraphjob.h:233
INVALID_DATE
static const Date INVALID_DATE
Representation of an invalid date.
Definition: date_type.h:111
LinkGraphJob::Node::End
EdgeIterator End() const
Iterator for the "end" of the edge array.
Definition: linkgraphjob.h:221
LinkGraphJob::IsJobAborted
bool IsJobAborted() const
Check if job has been aborted.
Definition: linkgraphjob.h:290
GoodsEntry::flows
FlowStatMap flows
Planned flows through this station.
Definition: station_base.h:256
Path::AddFlow
void AddFlow(uint f)
Increase the flow on this leg only by the specified amount.
Definition: linkgraphjob.h:415
FlowStatMap
Flow descriptions by origin stations.
Definition: station_base.h:149
linkgraphjob.h
Pool::PoolItem<&_link_graph_job_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:316
Path::Path
Path(NodeID n, bool source=false)
Create a leg of a path in the link graph.
Definition: linkgraphjob.cpp:273
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:224
Path::free_capacity
int free_capacity
This capacity is min(edge.capacity - edge.flow) for the current run of Dijkstra.
Definition: linkgraphjob.h:450
SmallStack::IsEmpty
bool IsEmpty() const
Check if the stack is empty.
Definition: smallstack_type.hpp:244
SpecializedStation< Station, false >::GetIfValid
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
Definition: base_station_base.h:227
LinkGraphSchedule::Run
static void Run(LinkGraphJob *job)
Run all handlers for the given Job.
Definition: linkgraphschedule.cpp:87
LinkGraphJob::Cargo
CargoID Cargo() const
Get the cargo of the underlying link graph.
Definition: linkgraphjob.h:341
LinkGraphJob::EraseFlows
void EraseFlows(NodeID from)
Erase all flows originating at a specific node.
Definition: linkgraphjob.cpp:50
Pool::PoolItem<&_link_graph_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:326
LinkGraphJob::Node::Begin
EdgeIterator Begin() const
Iterator for the "begin" of the edge array.
Definition: linkgraphjob.h:214
LinkGraphJob::EdgeIterator
Iterator for job edges.
Definition: linkgraphjob.h:148
Path::num_children
uint num_children
Number of child legs that have been forked from this path.
Definition: linkgraphjob.h:454
LinkGraphJob::Init
void Init()
Initialize the link graph job: Resize nodes and edges and populate them.
Definition: linkgraphjob.cpp:180
LinkGraphJob::LinkGraphJob
LinkGraphJob()
Bare constructor, only for save/load.
Definition: linkgraphjob.h:270
LinkGraphJob::NodeAnnotation::Init
void Init(uint supply)
Initialize a Linkgraph job node.
Definition: linkgraphjob.cpp:209
LinkGraphJob::Edge::AddFlow
void AddFlow(uint flow)
Add some flow.
Definition: linkgraphjob.h:112