Debian Codegraph @

universe/Universe.h

raw symbols SCIP
1 #ifndef _Universe_h_
2 #define _Universe_h_
3
4
5 #include <list>
6 #include <map>
7 #include <memory>
8 #include <set>
9 #include <span>
10 #include <string>
11 #include <unordered_map>
12 #include <unordered_set>
13 #include <vector>
14 #include "../util/boost_fix.h"
15 #include <boost/container/flat_map.hpp>
16 #include <boost/signals2/signal.hpp>
17 #include <boost/thread/shared_mutex.hpp>
18 #include "ConstantsFwd.h"
19 #include "EnumsFwd.h"
20 #include "ObjectMap.h"
21 #include "UnlockableItem.h"
22 #include "UniverseObject.h"
23 #include "../util/Export.h"
24 #include "../util/Pending.h"
25
26
27 class Empire;
28 class EmpireManager;
29 class XMLElement;
30 class ShipDesign;
31 class System;
32 class Pathfinder;
33 class IDAllocator;
34 class FleetPlan;
35 class MonsterFleetPlan;
36 struct ScriptingContext;
37
38
39 namespace Condition {
40 struct Condition;
41 using ObjectSet = std::vector<const UniverseObject*>;
42 }
43
44 namespace Effect {
45 struct AccountingInfo;
46 struct TargetsAndCause; // struct TargetsAndCause { TargetSet target_set; EffectCause effect_cause; };
47 struct SourcedEffectsGroup; // struct SourcedEffectsGroup { int source_object_id; const EffectsGroup* effects_group; };
48 class EffectsGroup;
49 using TargetSet = std::vector<UniverseObject*>;
50 using AccountingMap = std::unordered_map<int, boost::container::flat_map<MeterType, std::vector<AccountingInfo>>>;
51 using SourcesEffectsTargetsAndCause = std::pair<SourcedEffectsGroup, TargetsAndCause>;
52 using SourcesEffectsTargetsAndCausesVec = std::vector<SourcesEffectsTargetsAndCause>;
53 }
54
55 namespace ValueRef {
56 template <typename T>
57 struct ValueRef;
58 }
59
60
61 /** The Universe class contains the majority of FreeOrion gamestate: All the
62 * UniverseObjects in a game, and (of less importance) all ShipDesigns in a
63 * game. (Other gamestate is contained in the Empire class.)
64 * The Universe class also provides functions with which to access objects in
65 * it, information about the objects, and information about the objects'
66 * relationships to each other. As well, there are functions that generate
67 * and populate new Universe gamestates when new games are started. */
68 class FO_COMMON_API Universe {
69 public:
70 typedef std::map<int, ObjectMap> EmpireObjectMap; ///< Known information each empire had about objects in the Universe; keyed by empire id
71 typedef std::map<Visibility, int> VisibilityTurnMap; ///< Most recent turn number on which a something, such as a Universe object, was observed at various Visibility ratings or better
72 typedef std::map<int, VisibilityTurnMap> ObjectVisibilityTurnMap; ///< Most recent turn number on which the objects were observed at various Visibility ratings; keyed by object id
73 typedef std::map<int, ObjectVisibilityTurnMap> EmpireObjectVisibilityTurnMap; ///< Each empire's most recent turns on which object information was known; keyed by empire id
74 using IDSet = UniverseObject::IDSet;
75
76 private:
77 typedef std::map<int, std::unordered_set<int>> ObjectKnowledgeMap; ///< IDs of Empires which know information about an object (or deleted object); keyed by object id
78
79 typedef const ValueRef::ValueRef<Visibility>* VisValRef;
80 typedef std::vector<std::pair<int, VisValRef>> SrcVisValRefVec;
81 typedef std::map<int, SrcVisValRefVec> ObjSrcVisValRefVecMap;
82 typedef std::map<int, ObjSrcVisValRefVecMap> EmpireObjectVisValueRefMap;
83
84 /** Discrepancy between meter's value at start of turn, and the value that
85 * this client calculate that the meter should have with the knowledge
86 * available -> the unknown factor affecting the meter. This is used
87 * when generating effect accounting, in the case where the expected
88 * and actual meter values don't match. */
89 typedef std::unordered_map<int, boost::container::flat_map<MeterType, double>> DiscrepancyMap;
90
91 public:
92 typedef std::map<int, Visibility> ObjectVisibilityMap; ///< map from object id to Visibility level for a particular empire
93 typedef std::map<int, ObjectVisibilityMap> EmpireObjectVisibilityMap; ///< map from empire id to ObjectVisibilityMap for that empire
94
95 typedef std::map<int, std::set<std::string>> ObjectSpecialsMap; ///< map from object id to names of specials on an object
96 typedef std::map<int, ObjectSpecialsMap> EmpireObjectSpecialsMap; ///< map from empire id to ObjectSpecialsMap of known specials for objects for that empire
97
98 typedef std::map<int, ShipDesign> ShipDesignMap; ///< ShipDesigns in universe; keyed by design id
99 typedef ShipDesignMap::const_iterator ship_design_iterator; ///< const iterator over ship designs created by players that are known by this client
100
101 /** emitted just before the UniverseObject is deleted */
102 typedef boost::signals2::signal<void (std::shared_ptr<const UniverseObject>)> UniverseObjectDeleteSignalType;
103
104 Universe();
105 Universe& operator=(Universe&& other) noexcept;
106 ~Universe();
107
108
109 /** Returns objects in this Universe. */
110 [[nodiscard]] const ObjectMap& Objects() const noexcept { return *m_objects; }
111 [[nodiscard]] ObjectMap& Objects() noexcept { return *m_objects; }
112
113 /** Returns latest known state of objects for the Empire with
114 * id \a empire_id or the true / complete state of all objects in this
115 * Universe (the same as calling Objects()) if \a empire_id is
116 * ALL_EMPIRES*/
117 [[nodiscard]] const ObjectMap& EmpireKnownObjects(int empire_id = ALL_EMPIRES) const;
118 [[nodiscard]] ObjectMap& EmpireKnownObjects(int empire_id = ALL_EMPIRES);
119
120 /** Returns IDs of objects that the Empire with id \a empire_id has vision
121 * of on the current turn, or objects that at least one empire has vision
122 * of on the current turn if \a empire_id = ALL_EMPIRES */
123 [[nodiscard]] IDSet EmpireVisibleObjectIDs(int empire_id, const EmpireManager& empires) const;
124
125 /** Returns IDs of objects that have been destroyed. */
126 [[nodiscard]] auto& DestroyedObjectIds() const noexcept { return m_destroyed_object_ids; }
127 [[nodiscard]] int HighestDestroyedObjectID() const;
128
129 /** Returns IDs of objects that the Empire with id \a empire_id knows have
130 * been destroyed. Each empire's latest known objects data contains the
131 * last known information about each object, whether it has been destroyed
132 * or not. If \a empire_id = ALL_EMPIRES an empty set of IDs is
133 * returned. */
134 [[nodiscard]] const std::unordered_set<int>& EmpireKnownDestroyedObjectIDs(int empire_id) const;
135
136 /** Returns IDs of objects that the Empire with id \a empire_id has stale
137 * knowledge of in its latest known objects. The latest known data about
138 * these objects suggests that they should be visible, but they are not. */
139 [[nodiscard]] const std::unordered_set<int>& EmpireStaleKnowledgeObjectIDs(int empire_id) const;
140
141 [[nodiscard]] const ShipDesign* GetShipDesign(int ship_design_id) const; ///< returns the ship design with id \a ship_design id, or 0 if non exists
142
143 void RenameShipDesign(int design_id, std::string name = "", std::string description = "");
144
145 [[nodiscard]] const auto& ShipDesigns() const noexcept { return m_ship_designs; }
146
147 [[nodiscard]] const ShipDesign* GetGenericShipDesign(std::string_view name) const;
148
149 /** Returns IDs of ship designs that the Empire with id \a empire_id has
150 * seen during the game. If \a empire_id = ALL_EMPIRES an empty set of
151 * ids is returned */
152 [[nodiscard]] const std::set<int>& EmpireKnownShipDesignIDs(int empire_id) const;
153
154 /** Returns the Visibility level of empire with id \a empire_id of UniverseObject with
155 * id \a object_id as determined by calling UpdateEmpireObjectVisibilities.
156 * Monsters/neutrals are treated as an empire with id ALL_EMPIRES. */
157 [[nodiscard]] Visibility GetObjectVisibilityByEmpire(int object_id, int empire_id) const;
158
159 /* Return the map from empire id to (map from id to that empire's current
160 * visibility of that object) */
161 [[nodiscard]] auto& GetEmpireObjectVisibility() const noexcept { return m_empire_object_visibility; }
162
163 /* Returns the map from empire id to (map from object id to (map from
164 * visibility level to turn number on which the empire last detected that
165 * object at that visibility level)). */
166 [[nodiscard]] auto& GetEmpireObjectVisibilityTurnMap() const noexcept { return m_empire_object_visibility_turns; }
167
168 /** Returns the map from Visibility level to turn number on which the empire
169 * with id \a empire_id last had the various Visibility levels of the
170 * UniverseObject with id \a object_id . The returned map may be empty or
171 * not have entries for all visibility levels, if the empire has not seen
172 * the object at that visibility level yet. */
173 [[nodiscard]] const VisibilityTurnMap& GetObjectVisibilityTurnMapByEmpire(int object_id, int empire_id) const;
174
175 /** Returns the set of specials attached to the object with id \a object_id
176 * that the empire with id \a empire_id can see this turn. */
177 [[nodiscard]] std::set<std::string> GetObjectVisibleSpecialsByEmpire(int object_id, int empire_id) const;
178
179 /** Returns map from empire ID to map from location (X, Y) to detection range
180 * that empire has at that location. */
181 [[nodiscard]] std::map<int, std::map<std::pair<double, double>, float>>
182 GetEmpiresAndNeutralPositionDetectionRanges(const ObjectMap& objects) const;
183
184 [[nodiscard]] std::map<int, std::map<std::pair<double, double>, float>>
185 GetEmpiresAndNeutralPositionDetectionRanges(const ObjectMap& objects,
186 const std::unordered_set<int>& exclude_ids) const;
187
188 /** Returns map from empire ID to map from location (X, Y) to detection range
189 * that empire is expected to have at that location after the next turn's
190 * fleet movement. */
191 [[nodiscard]] std::map<int, std::map<std::pair<double, double>, float>>
192 GetEmpiresPositionNextTurnFleetDetectionRanges(const ScriptingContext& context) const;
193
194 /** Return the Pathfinder */
195 [[nodiscard]] const auto& GetPathfinder() const noexcept { return m_pathfinder; }
196
197 /** Returns map, indexed by object id, to map, indexed by MeterType,
198 * to vector of EffectAccountInfo for the meter, in order effects
199 * were applied to the meter. */
200 [[nodiscard]] const Effect::AccountingMap& GetEffectAccountingMap() const noexcept { return m_effect_accounting_map; }
201 [[nodiscard]] Effect::AccountingMap& GetEffectAccountingMap() noexcept { return m_effect_accounting_map; }
202
203 [[nodiscard]] const auto& GetStatRecords() const noexcept { return m_stat_records; }
204
205 [[nodiscard]] std::size_t SizeInMemory() const;
206
207 mutable UniverseObjectDeleteSignalType UniverseObjectDeleteSignal; ///< the state changed signal object for this UniverseObject
208
209 /** Inserts \a ship_design into the universe. Return the design's assigned
210 * ID on success, or INVALID_DESIGN_ID on failure.
211 * \note Universe gains ownership of \a ship_design once inserted. */
212 int InsertShipDesign(ShipDesign ship_design);
213
214 /** Inserts \a ship_design into the universe with given \a id; returns true
215 * on success, or false on failure. An empire id of none indicates that
216 * the server is allocating an id on behalf of itself. This can be removed
217 * when no longer supporting legacy id allocation in pending Orders. \note
218 * Universe gains ownership of \a ship_design once inserted. */
219 bool InsertShipDesignID(ShipDesign ship_design, boost::optional<int> empire_id, int id);
220
221 /** Reset object and ship design id allocation for a new game. */
222 void ResetAllIDAllocation(const std::vector<int>& empire_ids = std::vector<int>());
223
224 /** Clears main ObjectMap, empires' latest known objects map, and
225 * ShipDesign map. */
226 void Clear();
227
228 /** Resets meters */
229 void ResetAllObjectMeters(bool target_max_unpaired = true, bool active = true);
230
231 /** Determines all effectsgroups' target sets, then resets meters and
232 * executes all effects on all objects. Then clamps meter values so
233 * target and max meters are within a reasonable range and any current
234 * meters with associated max meters are limited by their max. */
235 void ApplyAllEffectsAndUpdateMeters(ScriptingContext& context, bool do_accounting = true);
236
237 /** Determines all effectsgroups' target sets, then resets meters and
238 * executes only SetMeter effects on all objects whose ids are listed in
239 * \a object_ids. Then clamps meter values so target and max meters are
240 * within a reasonable range and any current meters with associated max
241 * meters are limited by their max. */
242 void ApplyMeterEffectsAndUpdateMeters(const std::vector<int>& object_ids, ScriptingContext& context,
243 bool do_accounting = true);
244
245 /** Calls above ApplyMeterEffectsAndUpdateMeters() function on all objects.*/
246 void ApplyMeterEffectsAndUpdateMeters(ScriptingContext& context, bool do_accounting = true);
247
248 /** Executes effects that modify objects' appearance in the human client. */
249 void ApplyAppearanceEffects(const std::vector<int>& object_ids, ScriptingContext& context);
250
251 /** Executes effects that modify objects' apperance for all objects. */
252 void ApplyAppearanceEffects(ScriptingContext& context);
253
254 /** Executes effects that modify objects' apperance for all objects. */
255 void ApplyGenerateSitRepEffects(ScriptingContext& context);
256
257 /** For all objects and meters, determines discrepancies between actual meter
258 * maxes and what the known universe should produce, and and stores in
259 * m_effect_discrepancy_map. */
260 void InitMeterEstimatesAndDiscrepancies(ScriptingContext& context);
261
262 /** Based on (known subset of, if in a client) universe and any orders
263 * given so far this turn, updates estimated meter maxes for next turn
264 * for the objects with ids indicated in \a objects_vec. */
265 void UpdateMeterEstimates(const std::vector<int>& objects_vec, ScriptingContext& context);
266
267 /** Updates indicated object's meters, and if applicable, the
268 * meters of objects contained within the indicated object.
269 * If \a object_id is INVALID_OBJECT_ID, then all
270 * objects' meters are updated. */
271 void UpdateMeterEstimates(int object_id, ScriptingContext& context, bool update_contained_objects = false);
272
273 /** Updates all meters for all (known) objects */
274 void UpdateMeterEstimates(ScriptingContext& context);
275 void UpdateMeterEstimates(ScriptingContext& context, bool do_accounting);
276
277 /** Sets all objects' meters' initial values to their current values. */
278 void BackPropagateObjectMeters();
279
280 /** Determines which empires, or neutrals, can see which objects at what visibility
281 * level, based on detection strengths and ranges and any applicable overrides to that. */
282 void UpdateEmpireObjectVisibilities(const ScriptingContext& context);
283
284 /** Sets visibility by empires of objects with specified ids. */
285 void SetObjectVisibilityOverrides(std::map<int, std::vector<int>> empires_ids);
286 void ApplyObjectVisibilityOverrides();
287
288 /** Sets a special record of visibility that overrides the standard
289 * empire-object visibility after the latter is processed. */
290 void SetEffectDerivedVisibility(int empire_id, int object_id, int source_id,
291 const ValueRef::ValueRef<Visibility>* vis);
292
293 /** Applies empire-object visibilities set by effects. */
294 void ApplyEffectDerivedVisibilities(const ScriptingContext& context);
295
296 /** If an \p empire_id can't currently see \p object_id, then remove
297 * \p object_id' object from the object map and the set of known objects. */
298 void ForgetKnownObject(int empire_id, int object_id);
299
300 /** Sets visibility for indicated \a empire_id of object with \a object_id
301 * to at least * \a vis. If visibility is already equal or higher, does nothing.
302 * For ship object ids, also sets the ship's design to be known to the empire. */
303 void SetEmpireObjectVisibility(int empire_id, int object_id, Visibility vis);
304
305 /** Sets visibility for indicated \a empire_id for the indicated \a special */
306 void SetEmpireSpecialVisibility(int empire_id, int object_id,
307 const std::string& special_name, bool visible = true);
308
309 /** Stores latest known information about each object for each empire and
310 * updates the record of the last turn on which each empire has visibility
311 * of object that can be seen on the current turn with the level of
312 * visibility that the empire has this turn. */
313 void UpdateEmpireLatestKnownObjectsAndVisibilityTurns(int current_turn);
314
315 /** Checks latest known information about each object for each empire and,
316 * in cases when the latest known state (stealth and location) suggests
317 * that the empire should be able to see the object, but the object can't
318 * be seen by the empire, updates the latest known state to note this. */
319 void UpdateEmpireStaleObjectKnowledge(EmpireManager& empires);
320
321 /** Fills pathfinding data structure and determines least jumps distances
322 * between systems based on the objects in \a objects */
323 void InitializeSystemGraph(const EmpireManager& empires, const ObjectMap& objects);
324 void InitializeSystemGraph(const EmpireManager& empires) { InitializeSystemGraph(empires, *m_objects); }
325
326 /** Regenerates per-empire system view graphs by filtering the complete
327 * system graph based on empire visibility. Does not regenerate the base
328 * graph to account for actual system-starlane connectivity changes. */
329 void UpdateEmpireVisibilityFilteredSystemGraphsWithOwnObjectMaps(const EmpireManager& empires);
330 void UpdateEmpireVisibilityFilteredSystemGraphsWithMainObjectMap(const EmpireManager& empires);
331
332 /** Adds the object ID \a object_id to the set of object ids for the empire
333 * with id \a empire_id that the empire knows have been destroyed. */
334 void SetEmpireKnowledgeOfDestroyedObject(int object_id, int empire_id);
335
336 /** Adds the ship design ID \a ship_design_id to the set of ship design ids
337 * known by the empire with id \a empire_id */
338 void SetEmpireKnowledgeOfShipDesign(int ship_design_id, int empire_id);
339
340 /** Record in statistics that \a object_id was destroyed by species/empire
341 * associated with \a source_object_id */
342 void CountDestructionInStats(int object_id, int source_object_id, const std::map<int, std::shared_ptr<Empire>>& empires);
343
344 /** Removes the object with ID number \a object_id from the universe's map
345 * of existing objects, and adds the object's id to the set of destroyed
346 * object ids. If \a update_destroyed_object_knowers is true, empires
347 * that currently have visibility of the object have its id added to
348 * their set of objects' ids that are known to have been destroyed. Older
349 * or limited versions of objects remain in empires latest known objects
350 * ObjectMap, regardless of whether the empire knows the object is
351 * destroyed. */
352 void Destroy(int object_id, const std::span<const int> empire_ids,
353 bool update_destroyed_object_knowers = true);
354
355 /** Destroys object with ID \a object_id, and destroys any associted
356 * objects, such as contained buildings of planets, contained anything of
357 * systems, or fleets if their last ship has id \a object_id and the fleet
358 * is thus empty. Returns the ids of all destroyed objects. */
359 std::vector<int> RecursiveDestroy(int object_id, const std::span<const int> empire_ids);
360
361 /** Used by the Destroy effect to mark an object for destruction later
362 * during turn processing. (objects can't be destroyed immediately as
363 * other effects might depend on their existence) */
364 void EffectDestroy(int object_id, int source_object_id = INVALID_OBJECT_ID);
365
366 /** Permanently deletes object with ID number \a object_id. no
367 * information about this object is retained in the Universe. Can be
368 * performed on objects whether or not the have been destroyed. Returns
369 * true if such an object was found, false otherwise. */
370 bool Delete(int object_id);
371
372 /** Permanently deletes the ship design with ID number \a design_id. No
373 * information about this design is retained in the Universe. */
374 bool DeleteShipDesign(int design_id);
375
376 /** Sets whether to inhibit UniverseObjectSignals. Inhibits if \a inhibit
377 * is true, and (re)enables UniverseObjectSignals if \a inhibit is false. */
378 void InhibitUniverseObjectSignals(bool inhibit = true) noexcept { m_inhibit_universe_object_signals = inhibit; }
379
380 void UpdateStatRecords(const ScriptingContext& context);
381
382 /** Returns true if UniverseOjbectSignals are inhibited, false otherwise. */
383 const bool& UniverseObjectSignalsInhibited() const noexcept { return m_inhibit_universe_object_signals; }
384
385 [[nodiscard]] double UniverseWidth() const noexcept { return m_universe_width; }
386 void SetUniverseWidth(double width) noexcept { m_universe_width = width; }
387
388 /** InsertNew constructs and inserts a UniverseObject into the object map with a new
389 id. It returns the new object. */
390 template <typename T, typename... Args>
391 std::shared_ptr<T> InsertNew(Args&&... args)
392 { return InsertID<T>(GenerateObjectID(), std::forward<Args>(args)...); }
393
394 /** InsertTemp constructs and inserts a temporary UniverseObject into the object map with a
395 temporary id. It returns the new object. */
396 template <typename T, typename... Args>
397 std::shared_ptr<T> InsertTemp(Args&&... args)
398 { return InsertID<T>(TEMPORARY_OBJECT_ID, std::forward<Args>(args)...); }
399
400 /** InsertTemp inserts the provided \a objets into the object map with a series of
401 * temporary ids. It returns the ids of the inserted objects. */
402 template <typename T>
403 std::vector<int> InsertTemp(const std::vector<std::shared_ptr<T>>& objects)
404 {
405 auto ID = TEMPORARY_OBJECT_ID;
406 std::vector<int> retval;
407 retval.reserve(objects.size());
408 for (auto& obj : objects) {
409 if (!obj)
410 continue;
411 retval.push_back(ID);
412 obj->SetID(ID); // assign and decrement temporary ID
413 m_objects->insert(std::move(obj)); // directly insert into objects, skipping ID validation
414 ID--;
415 }
416 return retval;
417 }
418
419 /** \p empire_id inserts object \p obj into the universe with the given \p id.
420 This is provided for use with Orders which are run once on the client
421 and receive a new id and then are run a second time on the server using
422 the id assigned on the client. */
423 template <typename T, typename... Args>
424 std::shared_ptr<T> InsertByEmpireWithID(int empire_id, int id, Args&&... args)
425 {
426 if (!VerifyUnusedObjectID(empire_id, id))
427 return nullptr;
428 return InsertID<T>(id, std::forward<Args>(args)...);
429 }
430
431 //! Set items unlocked before turn 1 from \p future.
432 void SetInitiallyUnlockedItems(Pending::Pending<std::vector<UnlockableItem>>&& future);
433 //! Items unlocked before turn 1.
434 const std::vector<UnlockableItem>& InitiallyUnlockedItems() const;
435
436 //! Set buildings unlocked before turn 1 from \p future.
437 void SetInitiallyUnlockedBuildings(Pending::Pending<std::vector<UnlockableItem>>&& future);
438 //! Buildings unlocked before turn 1.
439 const std::vector<UnlockableItem>& InitiallyUnlockedBuildings() const;
440
441 /** Set fleets unlocked before turn 1 from \p future.*/
442 void SetInitiallyUnlockedFleetPlans(Pending::Pending<std::vector<std::unique_ptr<FleetPlan>>>&& future);
443 /** Fleets unlocked before turn 1.*/
444 std::vector<const FleetPlan*> InitiallyUnlockedFleetPlans() const;
445
446 /** Set items unlocked before turn 1 from \p future..*/
447 void SetMonsterFleetPlans(Pending::Pending<std::vector<std::unique_ptr<MonsterFleetPlan>>>&& future);
448 /** Items unlocked before turn 1.*/
449 std::vector<const MonsterFleetPlan*> MonsterFleetPlans() const;
450
451 /** Set the empire stats from \p future. */
452 using EmpireStatsMap = std::map<std::string, std::unique_ptr<ValueRef::ValueRef<double>>>;
453 void SetEmpireStats(Pending::Pending<EmpireStatsMap> future);
454 private:
455 const EmpireStatsMap& EmpireStats() const;
456 public:
457 /** ObfuscateIDGenerator applies randomization to the IDAllocator to prevent clients from
458 inferring too much information about other client's id generation activities. */
459 void ObfuscateIDGenerator();
460
461 private:
462 /* Pathfinder setup for the viewing empire
463 */
464 std::shared_ptr<Pathfinder> m_pathfinder;
465
466 /** Generates an object ID for a future object. Usually used by the server
467 * to service new ID requests. */
468 int GenerateObjectID();
469
470 /** Generates design ID for a new (ship) design. Usually used by the
471 * server to service new ID requests. */
472 int GenerateDesignID();
473
474 /** Verify that an object ID \p id could be generated by \p empire_id. */
475 bool VerifyUnusedObjectID(const int empire_id, const int id);
476
477 /** Inserts object \p obj into the universe with the given \p id. */
478 template <typename T, typename... Args>
479 std::shared_ptr<T> InsertID(int id, Args&&... args) {
480 static_assert(std::is_base_of_v<UniverseObject, T>);
481 static_assert(!std::is_same_v<UniverseObject, T>);
482 auto obj = std::make_shared<T>(std::forward<Args>(args)...);
483 InsertIDCore(obj, id);
484 return obj;
485 }
486
487 /** Inserts object \p obj into the universe with the given \p id. */
488 void InsertIDCore(std::shared_ptr<UniverseObject> obj, int id);
489
490 /** Clears \a source_effects_targets_causes, and then populates with all
491 * EffectsGroups and their targets in the known universe. */
492 void GetEffectsAndTargets(std::map<int, Effect::SourcesEffectsTargetsAndCausesVec>& source_effects_targets_causes,
493 const ScriptingContext& context,
494 bool only_meter_effects = false) const;
495
496 /** Removes entries in \a source_effects_targets_causes about effects groups acting
497 * on objects in \a target_objects, and then repopulates for EffectsGroups
498 * that act on at least one of the objects in \a target_objects. If
499 * \a target_objects is empty then default target candidates will be used. */
500 void GetEffectsAndTargets(std::map<int, Effect::SourcesEffectsTargetsAndCausesVec>& source_effects_targets_causes,
501 const std::vector<int>& target_objects,
502 const ScriptingContext& context,
503 bool only_meter_effects = false) const;
504
505 /** Executes all effects. For use on server when processing turns.
506 * If \a only_meter_effects is true, then only SetMeter effects are
507 * executed. This is useful on server or clients to update meter
508 * values after the rest of effects (including non-meter effects) have
509 * been executed. */
510 void ExecuteEffects(std::map<int, Effect::SourcesEffectsTargetsAndCausesVec>& source_effects_targets_causes,
511 ScriptingContext& context,
512 bool update_effect_accounting,
513 bool only_meter_effects = false,
514 bool only_appearance_effects = false,
515 bool include_empire_meter_effects = false,
516 bool only_generate_sitrep_effects = false);
517
518 /** Does actual updating of meter estimates after the public function have
519 * processed objects_vec or whatever they were passed and cleared the
520 * relevant effect accounting for those objects and meters. If an empty
521 * vector is passed, it will instead update all existing objects. */
522 void UpdateMeterEstimatesImpl(const std::vector<int>& objects_vec, ScriptingContext& context, bool do_accounting);
523
524 std::unique_ptr<ObjectMap> m_objects; ///< map from object id to UniverseObjects in the universe. for the server: all of them, up to date and true information about object is stored; for clients, only limited information based on what the client knows about is sent.
525 EmpireObjectMap m_empire_latest_known_objects; ///< map from empire id to (map from object id to latest known information about each object by that empire)
526
527 std::unordered_set<int> m_destroyed_object_ids; ///< all ids of objects that have been destroyed (on server) or that a player knows were destroyed (on clients)
528
529 EmpireObjectVisibilityMap m_empire_object_visibility; ///< map from empire id to (map from object id to visibility of that object for that empire)
530 EmpireObjectVisibilityTurnMap m_empire_object_visibility_turns; ///< map from empire id to (map from object id to (map from Visibility rating to turn number on which the empire last saw the object at the indicated Visibility rating or higher)
531
532 std::map<int, std::vector<int>> m_fleet_blockade_ship_visibility_overrides; // map from empire id to (list of ship ids that are visibile to that empire due to being revealed by participating in a blockade)
533 EmpireObjectVisValueRefMap m_effect_specified_empire_object_visibilities;
534
535 EmpireObjectSpecialsMap m_empire_object_visible_specials; ///< map from empire id to (map from object id to (set of names of specials that empire can see are on that object) )
536
537 ObjectKnowledgeMap m_empire_known_destroyed_object_ids;///< map from empire id to (set of object ids that the empire knows have been destroyed)
538 ObjectKnowledgeMap m_empire_stale_knowledge_object_ids;///< map from empire id to (set of object ids that the empire has previously observed but has subsequently been unable to detect at its last known location despite expecting to be able to detect it based on stealth of the object and having detectors in range)
539
540 ShipDesignMap m_ship_designs; ///< ship designs in the universe
541 std::map<int, std::set<int>> m_empire_known_ship_design_ids; ///< ship designs known to each empire
542
543 Effect::AccountingMap m_effect_accounting_map; ///< map from target object id, to map from target meter, to orderered list of structs with details of an effect and what it does to the meter
544
545 /// map from target object id, to map from target meter, to discrepancy
546 /// between meter's actual initial value, and the initial value that this
547 /// meter should have as far as the client can tell: the unknown factor
548 /// affecting the meter.
549 DiscrepancyMap m_effect_discrepancy_map;
550
551 std::map<int, std::set<int>> m_marked_destroyed; ///< used while applying effects to cache objects that have been destroyed. this allows to-be-destroyed objects to remain undestroyed until all effects have been processed, which ensures that to-be-destroyed objects still exist when other effects need to access them as a source object. key is destroyed object, and value set are the ids of objects that caused the destruction (may be multiples destroying a single target on a given turn)
552
553 double m_universe_width = 1000.0;
554 bool m_inhibit_universe_object_signals = false;
555
556 std::map<std::string, std::map<int, std::map<int, double>>>
557 m_stat_records; ///< storage for statistics calculated for empires. Indexed by stat name (string), contains a map indexed by empire id, contains a map from turn number (int) to stat value (double).
558
559 //! @name Parsed items
560 //! Various unlocked items are kept as a Pending::Pending while being parsed and
561 //! then transfered. They are mutable to allow processing in const accessors.
562 //! @{
563 mutable boost::optional<Pending::Pending<std::vector<UnlockableItem>>> m_pending_items = boost::none;
564 mutable boost::optional<Pending::Pending<std::vector<UnlockableItem>>> m_pending_buildings = boost::none;
565 mutable boost::optional<Pending::Pending<std::vector<std::unique_ptr<FleetPlan>>>> m_pending_fleet_plans = boost::none;
566 mutable boost::optional<Pending::Pending<std::vector<std::unique_ptr<MonsterFleetPlan>>>> m_pending_monster_fleet_plans = boost::none;
567 mutable boost::optional<Pending::Pending<EmpireStatsMap>> m_pending_empire_stats = boost::none;
568
569 mutable std::vector<UnlockableItem> m_unlocked_items;
570 mutable std::vector<UnlockableItem> m_unlocked_buildings;
571 mutable std::vector<std::unique_ptr<FleetPlan>> m_unlocked_fleet_plans;
572 mutable std::vector<std::unique_ptr<MonsterFleetPlan>> m_monster_fleet_plans;
573 mutable EmpireStatsMap m_empire_stats;
574 //! @}
575
576 /** Fills \a designs_to_serialize with ShipDesigns known to the empire with
577 * the ID \a encoding empire. If encoding_empire is ALL_EMPIRES, then all
578 * designs are included. */
579 const ShipDesignMap& GetShipDesignsToSerialize(ShipDesignMap& designs_to_serialize, int encoding_empire) const;
580
581 /** Fills \a objects with copies of UniverseObjects that should be sent
582 * to the empire with id \a encoding_empires */
583 void GetObjectsToSerialize(ObjectMap& objects, int encoding_empire) const;
584
585 /** Fills \a destroyed_object_ids with ids of objects known to be destroyed
586 * by the empire with ID \a encoding empire. If encoding_empire is
587 * ALL_EMPIRES, then all destroyed objects are included. */
588 void GetDestroyedObjectsToSerialize(std::set<int>& destroyed_object_ids, int encoding_empire) const;
589
590 /** Fills \a empire_latest_known_objects map with the latest known data
591 * about UniverseObjects for the empire with id \a encoding_empire. If
592 * the encoding empire is ALL_EMPIRES then all stored empire object
593 * knowledge is included. */
594 void GetEmpireKnownObjectsToSerialize(EmpireObjectMap& empire_latest_known_objects, int encoding_empire) const;
595
596 /***/
597 void GetEmpireObjectVisibilityMap(EmpireObjectVisibilityMap& empire_object_visibility, int encoding_empire) const;
598
599 /***/
600 void GetEmpireObjectVisibilityTurnMap(EmpireObjectVisibilityTurnMap& empire_object_visibility_turns, int encoding_empire) const;
601
602 /***/
603 //void GetEffectSpecifiedVisibilities(EmpireObjectVisibilityMap& effect_specified_empire_object_visibilities, int encoding_empire) const;
604
605 /***/
606 void GetEmpireKnownDestroyedObjects(ObjectKnowledgeMap& empire_known_destroyed_object_ids, int encoding_empire) const;
607
608 /***/
609 void GetEmpireStaleKnowledgeObjects(ObjectKnowledgeMap& empire_stale_knowledge_object_ids, int encoding_empire) const;
610
611 /** Manages allocating and verifying new object ids.*/
612 std::unique_ptr<IDAllocator> m_object_id_allocator;
613
614 /** Manages allocating and verifying new ship design ids.*/
615 std::unique_ptr<IDAllocator> m_design_id_allocator;
616
617 template <typename Archive>
618 friend void serialize(Archive&, Universe&, unsigned int const);
619 };
620
621 class SpeciesManager;
622
623 /** Compute a checksum for each of the universe's content managers. Each value will be of the form
624 ("BuildingManager", <checksum>) */
625 FO_COMMON_API std::map<std::string, unsigned int> CheckSumContent(const SpeciesManager& species);
626
627
628 #endif