OpenTTD Source: src/pathfinder/yapf/yapf_base.hpp Source File

OpenTTD Source 15.0-beta1

yapf_base.hpp
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#ifndef YAPF_BASE_HPP
11#define YAPF_BASE_HPP
12
13#include "../../debug.h"
14#include "../../settings_type.h"
15#include "../../misc/dbg_helpers.h"
16#include "yapf_type.hpp"
17
48template <class Types>
49 class CYapfBaseT {
50public:
51 typedef typename Types::Tpf Tpf;
52 typedef typename Types::TrackFollower TrackFollower;
53 typedef typename Types::NodeList NodeList;
54 typedef typename Types::VehicleType VehicleType;
55 typedef typename NodeList::Item Node;
56 typedef typename Node::Key Key;
57
58 NodeList nodes;
59
60protected:
61 Node *best_dest_node = nullptr;
62 Node *best_intermediate_node = nullptr;
63 const YAPFSettings *settings;
64 int max_search_nodes;
65 const VehicleType *vehicle = nullptr;
66
67 int stats_cost_calcs = 0;
68 int stats_cache_hits = 0;
69
70public:
71 int num_steps = 0;
72
73public:
75 inline CYapfBaseT() : settings(&_settings_game.pf.yapf), max_search_nodes(PfGetSettings().max_search_nodes) {}
76
78 ~CYapfBaseT() {}
79
80protected:
82 inline Tpf &Yapf()
83 {
84 return *static_cast<Tpf *>(this);
85 }
86
87public:
89 inline const YAPFSettings &PfGetSettings() const
90 {
91 return *this->settings;
92 }
93
103 inline bool FindPath(const VehicleType *v)
104 {
105 this->vehicle = v;
106
107 Yapf().PfSetStartupNodes();
108
109 for (;;) {
110 this->num_steps++;
111 Node *best_open_node = this->nodes.GetBestOpenNode();
112 if (best_open_node == nullptr) break;
113
114 if (Yapf().PfDetectDestination(*best_open_node)) {
115 this->best_dest_node = best_open_node;
116 break;
117 }
118
119 Yapf().PfFollowNode(*best_open_node);
120 if (this->max_search_nodes != 0 && this->nodes.ClosedCount() >= this->max_search_nodes) break;
121
122 this->nodes.PopOpenNode(best_open_node->GetKey());
123 this->nodes.InsertClosedNode(*best_open_node);
124 }
125
126 const bool destination_found = (this->best_dest_node != nullptr);
127
128 if (_debug_yapf_level >= 3) {
129 const UnitID veh_idx = (this->vehicle != nullptr) ? this->vehicle->unitnumber : 0;
130 const char ttc = Yapf().TransportTypeChar();
131 const float cache_hit_ratio = (this->stats_cache_hits == 0) ? 0.0f : ((float)this->stats_cache_hits / (float)(this->stats_cache_hits + this->stats_cost_calcs) * 100.0f);
132 const int cost = destination_found ? this->best_dest_node->cost : -1;
133 const int dist = destination_found ? this->best_dest_node->estimate - this->best_dest_node->cost : -1;
134
135 Debug(yapf, 3, "[YAPF{}]{}{:4d} - {} rounds - {} open - {} closed - CHR {:4.1f}% - C {} D {}",
136 ttc, destination_found ? '-' : '!', veh_idx, this->num_steps, this->nodes.OpenCount(), this->nodes.ClosedCount(), cache_hit_ratio, cost, dist
137 );
138 }
139
140 return destination_found;
141 }
142
147 inline Node *GetBestNode()
148 {
149 return (this->best_dest_node != nullptr) ? this->best_dest_node : this->best_intermediate_node;
150 }
151
156 inline Node &CreateNewNode()
157 {
158 Node &node = this->nodes.CreateNewNode();
159 return node;
160 }
161
163 inline void AddStartupNode(Node &n)
164 {
165 Yapf().PfNodeCacheFetch(n);
166 /* insert the new node only if it is not there */
167 if (this->nodes.FindOpenNode(n.key) == nullptr) {
168 this->nodes.InsertOpenNode(n);
169 } else {
170 /* if we are here, it means that node is already there - how it is possible?
171 * probably the train is in the position that both its ends point to the same tile/exit-dir
172 * very unlikely, but it happened */
173 }
174 }
175
177 inline void AddMultipleNodes(Node *parent, const TrackFollower &tf)
178 {
179 bool is_choice = (KillFirstBit(tf.new_td_bits) != TRACKDIR_BIT_NONE);
180 for (TrackdirBits rtds = tf.new_td_bits; rtds != TRACKDIR_BIT_NONE; rtds = KillFirstBit(rtds)) {
181 Trackdir td = (Trackdir)FindFirstBit(rtds);
182 Node &n = Yapf().CreateNewNode();
183 n.Set(parent, tf.new_tile, td, is_choice);
184 Yapf().AddNewNode(n, tf);
185 }
186 }
187
196 void PruneIntermediateNodeBranch(Node *n)
197 {
198 bool intermediate_on_branch = false;
199 while (n != nullptr && (n->segment->end_segment_reason & ESRB_CHOICE_FOLLOWS) == 0) {
200 if (n == Yapf().best_intermediate_node) intermediate_on_branch = true;
201 n = n->parent;
202 }
203 if (intermediate_on_branch) Yapf().best_intermediate_node = n;
204 }
205
210 void AddNewNode(Node &n, const TrackFollower &tf)
211 {
212 /* evaluate the node */
213 bool cached = Yapf().PfNodeCacheFetch(n);
214 if (!cached) {
215 this->stats_cost_calcs++;
216 } else {
217 this->stats_cache_hits++;
218 }
219
220 bool valid = Yapf().PfCalcCost(n, &tf);
221
222 if (valid) valid = Yapf().PfCalcEstimate(n);
223
224 /* have the cost or estimate callbacks marked this node as invalid? */
225 if (!valid) return;
226
227 /* The new node can be set as the best intermediate node only once we're
228 * certain it will be finalized by being inserted into the open list. */
229 bool set_intermediate = this->max_search_nodes > 0 && (this->best_intermediate_node == nullptr || (this->best_intermediate_node->GetCostEstimate() - this->best_intermediate_node->GetCost()) > (n.GetCostEstimate() - n.GetCost()));
230
231 /* check new node against open list */
232 Node *open_node = this->nodes.FindOpenNode(n.GetKey());
233 if (open_node != nullptr) {
234 /* another node exists with the same key in the open list
235 * is it better than new one? */
236 if (n.GetCostEstimate() < open_node->GetCostEstimate()) {
237 /* update the old node by value from new one */
238 this->nodes.PopOpenNode(n.GetKey());
239 *open_node = n;
240 /* add the updated old node back to open list */
241 this->nodes.InsertOpenNode(*open_node);
242 if (set_intermediate) this->best_intermediate_node = open_node;
243 }
244 return;
245 }
246
247 /* check new node against closed list */
248 Node *closed_node = this->nodes.FindClosedNode(n.GetKey());
249 if (closed_node != nullptr) {
250 /* another node exists with the same key in the closed list
251 * is it better than new one? */
252 int node_est = n.GetCostEstimate();
253 int closed_est = closed_node->GetCostEstimate();
254 if (node_est < closed_est) {
255 /* If this assert occurs, you have probably problem in
256 * your Tderived::PfCalcCost() or Tderived::PfCalcEstimate().
257 * The problem could be:
258 * - PfCalcEstimate() gives too large numbers
259 * - PfCalcCost() gives too small numbers
260 * - You have used negative cost penalty in some cases (cost bonus) */
261 NOT_REACHED();
262 }
263 return;
264 }
265 /* the new node is really new
266 * add it to the open list */
267 this->nodes.InsertOpenNode(n);
268 if (set_intermediate) this->best_intermediate_node = &n;
269 }
270
271 const VehicleType * GetVehicle() const
272 {
273 return this->vehicle;
274 }
275
276 void DumpBase(DumpTarget &dmp) const
277 {
278 dmp.WriteStructT("nodes", &this->nodes);
279 dmp.WriteValue("num_steps", this->num_steps);
280 }
281};
282
283#endif /* YAPF_BASE_HPP */
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition bitmath_func.hpp:213
KillFirstBit
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
Definition bitmath_func.hpp:250
CYapfBaseT
CYapfBaseT - A-star type path finder base class.
Definition yapf_base.hpp:49
CYapfBaseT::num_steps
int num_steps
this is there for debugging purposes (hope it doesn't hurt)
Definition yapf_base.hpp:71
CYapfBaseT::PruneIntermediateNodeBranch
void PruneIntermediateNodeBranch(Node *n)
In some cases an intermediate node branch should be pruned.
Definition yapf_base.hpp:196
CYapfBaseT::Key
Node::Key Key
key to hash tables
Definition yapf_base.hpp:56
CYapfBaseT::CYapfBaseT
CYapfBaseT()
default constructor
Definition yapf_base.hpp:75
CYapfBaseT::AddNewNode
void AddNewNode(Node &n, const TrackFollower &tf)
AddNewNode() - called by Tderived::PfFollowNode() for each child node.
Definition yapf_base.hpp:210
CYapfBaseT::vehicle
const VehicleType * vehicle
vehicle that we are trying to drive
Definition yapf_base.hpp:65
CYapfBaseT::best_intermediate_node
Node * best_intermediate_node
here should be node closest to the destination if path not found
Definition yapf_base.hpp:62
CYapfBaseT::settings
const YAPFSettings * settings
current settings (_settings_game.yapf)
Definition yapf_base.hpp:63
CYapfBaseT::stats_cache_hits
int stats_cache_hits
stats - how many node's costs were reused from cache
Definition yapf_base.hpp:68
CYapfBaseT::AddMultipleNodes
void AddMultipleNodes(Node *parent, const TrackFollower &tf)
add multiple nodes - direct children of the given node
Definition yapf_base.hpp:177
CYapfBaseT::stats_cost_calcs
int stats_cost_calcs
stats - how many node's costs were calculated
Definition yapf_base.hpp:67
CYapfBaseT::max_search_nodes
int max_search_nodes
maximum number of nodes we are allowed to visit before we give up
Definition yapf_base.hpp:64
CYapfBaseT::GetBestNode
Node * GetBestNode()
If path was found return the best node that has reached the destination.
Definition yapf_base.hpp:147
CYapfBaseT::~CYapfBaseT
~CYapfBaseT()
default destructor
Definition yapf_base.hpp:78
CYapfBaseT::FindPath
bool FindPath(const VehicleType *v)
Main pathfinder routine:
Definition yapf_base.hpp:103
CYapfBaseT::CreateNewNode
Node & CreateNewNode()
Calls NodeList::CreateNewNode() - allocates new node that can be filled and used as argument for AddS...
Definition yapf_base.hpp:156
CYapfBaseT::nodes
NodeList nodes
node list multi-container
Definition yapf_base.hpp:58
CYapfBaseT::Tpf
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
Definition yapf_base.hpp:51
CYapfBaseT::PfGetSettings
const YAPFSettings & PfGetSettings() const
return current settings (can be custom - company based - but later)
Definition yapf_base.hpp:89
CYapfBaseT::VehicleType
Types::VehicleType VehicleType
the type of vehicle
Definition yapf_base.hpp:54
CYapfBaseT::AddStartupNode
void AddStartupNode(Node &n)
Add new node (created by CreateNewNode and filled with data) into open list.
Definition yapf_base.hpp:163
CYapfBaseT::best_dest_node
Node * best_dest_node
pointer to the destination node found at last round
Definition yapf_base.hpp:61
CYapfBaseT::Node
NodeList::Item Node
this will be our node type
Definition yapf_base.hpp:55
CYapfBaseT::NodeList
Types::NodeList NodeList
our node list
Definition yapf_base.hpp:53
CYapfBaseT::Yapf
Tpf & Yapf()
to access inherited path finder
Definition yapf_base.hpp:82
NodeList
Hash table based node list multi-container class.
Definition nodelist.hpp:21
NodeList::InsertClosedNode
void InsertClosedNode(Titem &item)
close node
Definition nodelist.hpp:122
NodeList::FindClosedNode
Titem * FindClosedNode(const Key &key)
return the closed node specified by a key or nullptr if not found
Definition nodelist.hpp:129
NodeList::InsertOpenNode
void InsertOpenNode(Titem &item)
insert given item as open node (into m_open and m_open_queue)
Definition nodelist.hpp:76
NodeList::OpenCount
int OpenCount()
return number of open nodes
Definition nodelist.hpp:41
NodeList::ClosedCount
int ClosedCount()
return number of closed nodes
Definition nodelist.hpp:47
NodeList::CreateNewNode
Titem & CreateNewNode()
allocate new data item from items
Definition nodelist.hpp:59
NodeList::GetBestOpenNode
Titem * GetBestOpenNode()
return the best open node
Definition nodelist.hpp:87
NodeList::PopOpenNode
Titem & PopOpenNode(const Key &key)
remove and return the open node specified by a key
Definition nodelist.hpp:113
NodeList::FindOpenNode
Titem * FindOpenNode(const Key &key)
return the open node specified by a key or nullptr if not found
Definition nodelist.hpp:107
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition debug.h:37
valid
uint8_t valid
Bits indicating what variable is valid (for each bit, 0 is invalid, 1 is valid).
Definition newgrf_station.cpp:247
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:57
DumpTarget
Class that represents the dump-into-string target.
Definition dbg_helpers.h:95
DumpTarget::WriteValue
void WriteValue(const std::string &name, int value)
Write 'name = value' with indent and new-line.
Definition dbg_helpers.cpp:115
DumpTarget::WriteStructT
void WriteStructT(const std::string &name, const S *s)
Dump nested object (or only its name if this instance is already known).
Definition dbg_helpers.h:147
YAPFSettings
Settings related to the yet another pathfinder.
Definition settings_type.h:425
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:67
TrackdirBits
TrackdirBits
Allow incrementing of Trackdir variables.
Definition track_type.h:98
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:99
UnitID
uint16_t UnitID
Type for the company global vehicle unit number.
Definition transport_type.h:16
VehicleType
VehicleType
Available vehicle types.
Definition vehicle_type.h:21
yapf_type.hpp
Types used by YAPF.