OpenTTD
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 */
21 
22 
27 /* static */ Path *Path::invalid_path = new Path(INVALID_NODE, true);
28 
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 {
42 }
43 
48 void LinkGraphJob::EraseFlows(NodeID from)
49 {
50  for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
51  (*this)[node_id].Flows().erase(from);
52  }
53 }
54 
60 {
61  if (!StartNewThread(&this->thread, "ottd:linkgraph", &(LinkGraphSchedule::Run), this)) {
62  /* Of course this will hang a bit.
63  * On the other hand, if you want to play games which make this hang noticeably
64  * on a platform without threads then you'll probably get other problems first.
65  * OK:
66  * If someone comes and tells me that this hangs for him/her, I'll implement a
67  * smaller grained "Step" method for all handlers and add some more ticks where
68  * "Step" is called. No problem in principle. */
70  }
71 }
72 
77 {
78  if (this->thread.joinable()) {
79  this->thread.join();
80  }
81 }
82 
87 {
88  this->JoinThread();
89 
90  /* Don't update stuff from other pools, when everything is being removed.
91  * Accessing other pools may be invalid. */
92  if (CleaningPool()) return;
93 
94  /* Link graph has been merged into another one. */
95  if (!LinkGraph::IsValidID(this->link_graph.index)) return;
96 
97  uint size = this->Size();
98  for (NodeID node_id = 0; node_id < size; ++node_id) {
99  Node from = (*this)[node_id];
100 
101  /* The station can have been deleted. Remove all flows originating from it then. */
102  Station *st = Station::GetIfValid(from.Station());
103  if (st == nullptr) {
104  this->EraseFlows(node_id);
105  continue;
106  }
107 
108  /* Link graph merging and station deletion may change around IDs. Make
109  * sure that everything is still consistent or ignore it otherwise. */
110  GoodsEntry &ge = st->goods[this->Cargo()];
111  if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
112  this->EraseFlows(node_id);
113  continue;
114  }
115 
117  FlowStatMap &flows = from.Flows();
118 
119  for (EdgeIterator it(from.Begin()); it != from.End(); ++it) {
120  if (from[it->first].Flow() == 0) continue;
121  StationID to = (*this)[it->first].Station();
122  Station *st2 = Station::GetIfValid(to);
123  if (st2 == nullptr || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
124  st2->goods[this->Cargo()].node != it->first ||
125  (*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
126  /* Edge has been removed. Delete flows. */
127  StationIDStack erased = flows.DeleteFlows(to);
128  /* Delete old flows for source stations which have been deleted
129  * from the new flows. This avoids flow cycles between old and
130  * new flows. */
131  while (!erased.IsEmpty()) ge.flows.erase(erased.Pop());
132  } else if ((*lg)[node_id][it->first].LastUnrestrictedUpdate() == INVALID_DATE) {
133  /* Edge is fully restricted. */
134  flows.RestrictFlows(to);
135  }
136  }
137 
138  /* Swap shares and invalidate ones that are completely deleted. Don't
139  * really delete them as we could then end up with unroutable cargo
140  * somewhere. Do delete them and also reroute relevant cargo if
141  * automatic distribution has been turned off for that cargo. */
142  for (FlowStatMap::iterator it(ge.flows.begin()); it != ge.flows.end();) {
143  FlowStatMap::iterator new_it = flows.find(it->first);
144  if (new_it == flows.end()) {
145  if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
146  it->second.Invalidate();
147  ++it;
148  } else {
149  FlowStat shares(INVALID_STATION, 1);
150  it->second.SwapShares(shares);
151  ge.flows.erase(it++);
152  for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
153  shares_it != shares.GetShares()->end(); ++shares_it) {
154  RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
155  }
156  }
157  } else {
158  it->second.SwapShares(new_it->second);
159  flows.erase(new_it);
160  ++it;
161  }
162  }
163  ge.flows.insert(flows.begin(), flows.end());
164  InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
165  }
166 }
167 
174 {
175  uint size = this->Size();
176  this->nodes.resize(size);
177  this->edges.Resize(size, size);
178  for (uint i = 0; i < size; ++i) {
179  this->nodes[i].Init(this->link_graph[i].Supply());
180  EdgeAnnotation *node_edges = this->edges[i];
181  for (uint j = 0; j < size; ++j) {
182  node_edges[j].Init();
183  }
184  }
185 }
186 
191 {
192  this->demand = 0;
193  this->flow = 0;
194  this->unsatisfied_demand = 0;
195 }
196 
203 {
204  this->undelivered_supply = supply;
205  new (&this->flows) FlowStatMap;
206  new (&this->paths) PathList;
207 }
208 
217 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
218 {
219  this->capacity = min(base->capacity, cap);
220  this->free_capacity = min(base->free_capacity, free_cap);
221  this->distance = base->distance + dist;
222  assert(this->distance > 0);
223  if (this->parent != base) {
224  this->Detach();
225  this->parent = base;
226  this->parent->num_children++;
227  }
228  this->origin = base->origin;
229 }
230 
239 uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
240 {
241  if (this->parent != nullptr) {
242  LinkGraphJob::Edge edge = job[this->parent->node][this->node];
243  if (max_saturation != UINT_MAX) {
244  uint usable_cap = edge.Capacity() * max_saturation / 100;
245  if (usable_cap > edge.Flow()) {
246  new_flow = min(new_flow, usable_cap - edge.Flow());
247  } else {
248  return 0;
249  }
250  }
251  new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
252  if (this->flow == 0 && new_flow > 0) {
253  job[this->parent->node].Paths().push_front(this);
254  }
255  edge.AddFlow(new_flow);
256  }
257  this->flow += new_flow;
258  return new_flow;
259 }
260 
266 Path::Path(NodeID n, bool source) :
267  distance(source ? 0 : UINT_MAX),
268  capacity(source ? UINT_MAX : 0),
269  free_capacity(source ? INT_MAX : INT_MIN),
270  flow(0), node(n), origin(source ? n : INVALID_NODE),
271  num_children(0), parent(nullptr)
272 {}
273 
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
void Init()
Initialize a linkgraph job edge.
Minimal stack that uses a pool to avoid pointers.
int free_capacity
This capacity is min(edge.capacity - edge.flow) for the current run of Dijkstra.
Definition: linkgraphjob.h:424
std::thread thread
Thread the job is running in or a default-constructed thread if it&#39;s running in the main thread...
Definition: linkgraphjob.h:60
A job edge.
Definition: linkgraphjob.h:75
Annotation for a link graph edge.
Definition: linkgraphjob.h:34
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:291
LinkGraphJobPool _link_graph_job_pool("LinkGraphJob")
The actual pool with link graph jobs.
uint Flow() const
Get the total flow on the edge.
Definition: linkgraphjob.h:103
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:20
StationIDStack DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Stores station stats for a single cargo.
Definition: station_base.h:170
Tindex index
Index of this pool item.
Definition: pool_type.hpp:189
Manual distribution. No link graph calculations are run.
void AddFlow(uint f)
Increase the flow on this leg only by the specified amount.
Definition: linkgraphjob.h:389
StationID Station() const
Get ID of station belonging to wrapped node.
Definition: linkgraph.h:157
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:479
A connected component of a link graph.
Definition: linkgraph.h:38
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:48
void Init(uint supply)
Initialize a Linkgraph job node.
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
bool IsEmpty() const
Check if the stack is empty.
void Init()
Initialize the link graph job: Resize nodes and edges and populate them.
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...
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...
LinkGraphID link_graph
Link graph this station belongs to.
Definition: station_base.h:257
Path(NodeID n, bool source=false)
Create a leg of a path in the link graph.
uint distance
Sum(distance of all legs up to this one).
Definition: linkgraphjob.h:422
static const Date INVALID_DATE
Representation of an invalid date.
Definition: date_type.h:108
A leg of a path in the link graph.
Definition: linkgraphjob.h:340
Declaration of link graph schedule used for cargo distribution.
uint num_children
Number of child legs that have been forked from this path.
Definition: linkgraphjob.h:428
Titem Pop()
Pop an item from the stack.
NodeID node
ID of node in link graph referring to this goods entry.
Definition: station_base.h:258
Link graph job node.
Definition: linkgraphjob.h:182
Station view; Window numbers:
Definition: window_type.h:338
static Path * invalid_path
Static instance of an invalid path.
Definition: linkgraphjob.h:342
Declaration of link graph job classes used for cargo distribution.
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
uint capacity
This capacity is min(capacity) fom all edges.
Definition: linkgraphjob.h:423
void SpawnThread()
Spawn a thread if possible and run the link graph job in the thread.
NodeID origin
Link graph node this path originates from.
Definition: linkgraphjob.h:427
void AddFlow(uint flow)
Add some flow.
Definition: linkgraphjob.h:109
Base class for all pools.
Definition: pool_type.hpp:82
CargoID Cargo() const
Get the cargo of the underlying link graph.
Definition: linkgraphjob.h:316
FlowStatMap flows
Planned flows through this station.
Definition: station_base.h:259
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:224
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:270
const LinkGraph link_graph
Link graph to by analyzed. Is copied when job is started and mustn&#39;t be modified later.
Definition: linkgraphjob.h:58
static void Run(LinkGraphJob *job)
Run all handlers for the given Job.
FlowStatMap & Flows()
Get the flows running through this node.
Definition: linkgraphjob.h:230
void EraseFlows(NodeID from)
Erase all flows originating at a specific node.
void JoinThread()
Join the calling thread with this job&#39;s thread if threading is enabled.
void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
Definition: station_base.h:92
EdgeIterator End() const
Iterator for the "end" of the edge array.
Definition: linkgraphjob.h:218
Iterator for job edges.
Definition: linkgraphjob.h:145
uint Size() const
Get the size of the underlying link graph.
Definition: linkgraphjob.h:310
Flow statistics telling how much flow should be sent along a link.
Definition: station_base.h:36
LinkGraphJob()
Bare constructor, only for save/load.
Definition: linkgraphjob.h:267
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:280
Flow descriptions by origin stations.
Definition: station_base.h:152
EdgeAnnotationMatrix edges
Extra edge data necessary for link graph calculation.
Definition: linkgraphjob.h:63
uint Capacity() const
Get edge&#39;s capacity.
Definition: linkgraph.h:91
Date _date
Current date in days (day counter)
Definition: date.cpp:26
NodeAnnotationVector nodes
Extra node data necessary for link graph calculation.
Definition: linkgraphjob.h:62
EdgeIterator Begin() const
Iterator for the "begin" of the edge array.
Definition: linkgraphjob.h:211
Station data structure.
Definition: station_base.h:450
~LinkGraphJob()
Join the link graph job and destroy it.
LinkGraphSettings linkgraph
settings for link graph calculations
Class for calculation jobs to be run on link graphs.
Definition: linkgraphjob.h:29
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:3316
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.