Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / linkgraph / linkgraphjob.cpp
blob8e5ec3283810133363bd917c5e93c19841fa9276
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 */
8 /** @file linkgraphjob.cpp Definition of link graph job classes used for cargo distribution. */
10 #include "../stdafx.h"
11 #include "../core/pool_func.hpp"
12 #include "../window_func.h"
13 #include "linkgraphjob.h"
14 #include "linkgraphschedule.h"
16 #include "../safeguards.h"
18 /* Initialize the link-graph-job-pool */
19 LinkGraphJobPool _link_graph_job_pool("LinkGraphJob");
20 INSTANTIATE_POOL_METHODS(LinkGraphJob)
22 /**
23 * Static instance of an invalid path.
24 * Note: This instance is created on task start.
25 * Lazy creation on first usage results in a data race between the CDist threads.
27 /* static */ Path *Path::invalid_path = new Path(INVALID_NODE, true);
29 /**
30 * Create a link graph job from a link graph. The link graph will be copied so
31 * that the calculations don't interfer with the normal operations on the
32 * original. The job is immediately started.
33 * @param orig Original LinkGraph to be copied.
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)
46 /**
47 * Erase all flows originating at a specific node.
48 * @param from Node to erase flows for.
50 void LinkGraphJob::EraseFlows(NodeID from)
52 for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
53 (*this)[node_id].Flows().erase(from);
57 /**
58 * Spawn a thread if possible and run the link graph job in the thread. If
59 * that's not possible run the job right now in the current thread.
61 void LinkGraphJob::SpawnThread()
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);
75 /**
76 * Join the calling thread with this job's thread if threading is enabled.
78 void LinkGraphJob::JoinThread()
80 if (this->thread.joinable()) {
81 this->thread.join();
85 /**
86 * Join the link graph job and destroy it.
88 LinkGraphJob::~LinkGraphJob()
90 this->JoinThread();
92 /* Don't update stuff from other pools, when everything is being removed.
93 * Accessing other pools may be invalid. */
94 if (CleaningPool()) return;
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());
101 /* Link graph has been merged into another one. */
102 if (!LinkGraph::IsValidID(this->link_graph.index)) return;
104 uint16 size = this->Size();
105 for (NodeID node_id = 0; node_id < size; ++node_id) {
106 Node from = (*this)[node_id];
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;
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;
123 LinkGraph *lg = LinkGraph::Get(ge.link_graph);
124 FlowStatMap &flows = from.Flows();
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);
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);
164 } else {
165 it->second.SwapShares(new_it->second);
166 flows.erase(new_it);
167 ++it;
170 ge.flows.insert(flows.begin(), flows.end());
171 InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
176 * Initialize the link graph job: Resize nodes and edges and populate them.
177 * This is done after the constructor so that we can do it in the calculation
178 * thread without delaying the main game.
180 void LinkGraphJob::Init()
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();
195 * Initialize a linkgraph job edge.
197 void LinkGraphJob::EdgeAnnotation::Init()
199 this->demand = 0;
200 this->flow = 0;
201 this->unsatisfied_demand = 0;
205 * Initialize a Linkgraph job node. The underlying memory is expected to be
206 * freshly allocated, without any constructors having been called.
207 * @param supply Initial undelivered supply.
209 void LinkGraphJob::NodeAnnotation::Init(uint supply)
211 this->undelivered_supply = supply;
212 new (&this->flows) FlowStatMap;
213 new (&this->paths) PathList;
217 * Add this path as a new child to the given base path, thus making this path
218 * a "fork" of the base path.
219 * @param base Path to fork from.
220 * @param cap Maximum capacity of the new leg.
221 * @param free_cap Remaining free capacity of the new leg.
222 * @param dist Distance of the new leg.
224 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
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++;
235 this->origin = base->origin;
239 * Push some flow along a path and register the path in the nodes it passes if
240 * successful.
241 * @param new_flow Amount of flow to push.
242 * @param job Link graph job this node belongs to.
243 * @param max_saturation Maximum saturation of edges.
244 * @return Amount of flow actually pushed.
246 uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
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;
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);
262 edge.AddFlow(new_flow);
264 this->flow += new_flow;
265 return new_flow;
269 * Create a leg of a path in the link graph.
270 * @param n Id of the link graph node this path passes.
271 * @param source If true, this is the first leg of the path.
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)