diff --git a/src/headless/main.cpp b/src/headless/main.cpp index afba914f8..9769be4c0 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -261,44 +261,42 @@ static bool run_headless(fs::path const& root, memory::vector& m print_memory_usage("Game Session Post-Start"); // TODO - REMOVE TEST CODE + InstanceManager& instance_manager = *game_manager.get_instance_manager(); SPDLOG_INFO("===== Ranking system test... ====="); - if (game_manager.get_instance_manager()) { - const auto print_ranking_list = [ // - ](std::string_view title, OpenVic::forwardable_span> countries) -> void { - memory::string countries_str; - for (CountryInstance& country : countries) { - countries_str += fmt::format( - "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", // - country, // - country.get_total_rank(), country.total_score.get_untracked(), // - country.get_prestige_rank(), country.get_prestige_untracked(), - country.get_industrial_rank(), country.get_industrial_power_untracked(), - country.get_military_rank(), country.military_power.get_untracked() - ); - } - SPDLOG_INFO("{}:{}", title, countries_str); - }; - - CountryInstanceManager const& country_instance_manager = game_manager.get_instance_manager()->get_country_instance_manager(); - - OpenVic::forwardable_span> great_powers = country_instance_manager.get_great_powers(); - print_ranking_list("Great Powers", great_powers); - print_ranking_list("Secondary Powers", country_instance_manager.get_secondary_powers()); - print_ranking_list("All countries", country_instance_manager.get_total_ranking()); - - SPDLOG_INFO("===== RGO test... ====="); - for (size_t i = 0; i < std::min(3, great_powers.size()); ++i) { - CountryInstance const& great_power = great_powers[i]; - ProvinceInstance const* const capital_province = great_power.get_capital(); - if (capital_province == nullptr) { - spdlog::warn_s("{} has no capital ProvinceInstance set.", great_power); - } else { - print_rgo(*capital_province); - } + const auto print_ranking_list = []( + std::string_view title, + OpenVic::forwardable_span> countries + ) -> void { + memory::string countries_str; + for (CountryInstance& country : countries) { + countries_str += fmt::format( + "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", // + country, // + country.get_total_rank(), country.total_score.get_untracked(), // + country.get_prestige_rank(), country.get_prestige_untracked(), + country.get_industrial_rank(), country.get_industrial_power_untracked(), + country.get_military_rank(), country.military_power.get_untracked() + ); + } + SPDLOG_INFO("{}:{}", title, countries_str); + }; + + CountryInstanceManager const& country_instance_manager = game_manager.get_instance_manager()->get_country_instance_manager(); + + OpenVic::forwardable_span> great_powers = country_instance_manager.get_great_powers(); + print_ranking_list("Great Powers", great_powers); + print_ranking_list("Secondary Powers", country_instance_manager.get_secondary_powers()); + print_ranking_list("All countries", country_instance_manager.get_total_ranking()); + + SPDLOG_INFO("===== RGO test... ====="); + for (size_t i = 0; i < std::min(3, great_powers.size()); ++i) { + CountryInstance const& great_power = great_powers[i]; + ProvinceInstance const* const capital_province = great_power.get_capital(); + if (capital_province == nullptr) { + spdlog::warn_s("{} has no capital ProvinceInstance set.", great_power); + } else { + print_rgo(*capital_province); } - } else { - spdlog::error_s("Instance manager not available!"); - ret = false; } if (ret) { @@ -308,7 +306,7 @@ static bool run_headless(fs::path const& root, memory::vector& m using test_time_units_t = std::chrono::milliseconds; - MapInstance& map_instance = game_manager.get_instance_manager()->get_map_instance(); + MapInstance& map_instance = instance_manager.get_map_instance(); SPDLOG_INFO("===== Land Pathfinding test... ====="); test_duration_t duration = std::chrono::duration_cast( // diff --git a/src/openvic-simulation/InstanceManager.cpp b/src/openvic-simulation/InstanceManager.cpp index a98f0cc7b..64cb30f90 100644 --- a/src/openvic-simulation/InstanceManager.cpp +++ b/src/openvic-simulation/InstanceManager.cpp @@ -5,6 +5,7 @@ #include "openvic-simulation/misc/GameAction.hpp" #include "openvic-simulation/types/TypedSpan.hpp" #include "openvic-simulation/utility/Logger.hpp" +#include "openvic-simulation/utility/ThreadDeps.hpp" using namespace OpenVic; @@ -168,8 +169,8 @@ void InstanceManager::update_gamestate() { update_modifier_sums(); // Update gamestate... - map_instance.update_gamestate(*this); - country_instance_manager.update_gamestate(today, map_instance); + map_instance.update_gamestate(); + country_instance_manager.update_gamestate_after_map(today); unit_instance_manager.update_gamestate(); gamestate_updated(); @@ -234,12 +235,19 @@ bool InstanceManager::setup() { } thread_pool.initialise_threadpool( - game_rules_manager, - good_instance_manager, - definition_manager.get_modifier_manager().get_modifier_effect_cache(), - definition_manager.get_define_manager().get_pops_defines(), - definition_manager.get_economy_manager().get_production_type_manager(), - strata_index_t(definition_manager.get_pop_manager().get_strata_count()), + ThreadDeps{ + game_rules_manager, + good_instance_manager, + map_instance, + definition_manager.get_define_manager().get_military_defines(), + definition_manager.get_modifier_manager().get_modifier_effect_cache(), + definition_manager.get_define_manager().get_pops_defines(), + definition_manager.get_economy_manager().get_production_type_manager(), + definition_manager.get_modifier_manager().get_static_modifier_cache(), + country_index_t(definition_manager.get_country_definition_manager().get_country_definition_count()), + good_index_t(definition_manager.get_economy_manager().get_good_definition_manager().get_good_definition_count()), + strata_index_t(definition_manager.get_pop_manager().get_strata_count()) + }, good_instance_manager.get_good_instances(), country_instance_manager.get_country_instances(), map_instance.get_province_instances() @@ -305,8 +313,8 @@ bool InstanceManager::load_bookmark(Bookmark const& new_bookmark) { OV_ERR_FAIL_COND_V_MSG(!all_has_state, false, "At least one land province has no state"); update_modifier_sums(); - map_instance.initialise_for_new_game(*this); - country_instance_manager.update_gamestate(today, map_instance); + map_instance.initialise_for_new_game(); + country_instance_manager.update_gamestate_after_map(today); market_instance.execute_orders(); return ret; @@ -359,12 +367,9 @@ void InstanceManager::update_modifier_sums() { // full copy of all the modifiers affecting them in their modifier sum, but provinces only having their directly/locally // applied modifiers in their modifier sum, hence requiring owner country modifier effect values to be looked up when // determining the value of a global effect on the province. - country_instance_manager.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); - map_instance.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); + country_instance_manager.update_modifier_sums_before_map(); + map_instance.update_modifier_sums(today); + country_instance_manager.update_modifier_sums_after_map(); } bool InstanceManager::queue_game_action(game_action_t&& game_action) { diff --git a/src/openvic-simulation/core/BulkInsertWrapper.hpp b/src/openvic-simulation/core/BulkInsertWrapper.hpp new file mode 100644 index 000000000..cd31e8bdf --- /dev/null +++ b/src/openvic-simulation/core/BulkInsertWrapper.hpp @@ -0,0 +1,201 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "openvic-simulation/core/Assert.hpp" + +namespace OpenVic { + // not thread safe + template + struct bulk_insert_wrapper { + public: + // Member types based on std::vector + using container_type = Container; + using value_type = typename container_type::value_type; + using allocator_type = typename container_type::allocator_type; + using size_type = typename container_type::size_type; + using difference_type = typename container_type::difference_type; + using reference = typename container_type::reference; + using const_reference = typename container_type::const_reference; + using pointer = typename container_type::pointer; + using const_pointer = typename container_type::const_pointer; + using iterator = typename container_type::iterator; + using const_iterator = typename container_type::const_iterator; + using reverse_iterator = typename container_type::reverse_iterator; + using const_reverse_iterator = typename container_type::const_reverse_iterator; + + static_assert(std::is_default_constructible_v); + static_assert(std::is_trivially_destructible_v); + + private: + Container container; + std::atomic pending_extra_size {}; + + constexpr void flush_pending_room() { + if (pending_extra_size > size_type{}) { + size_type valid_size { size() }; + container.resize(valid_size + pending_extra_size); + container.resize(valid_size); + pending_extra_size = size_type{}; + } + } + + public: + constexpr allocator_type get_allocator() const { + return container.get_allocator(); + } + + constexpr bulk_insert_wrapper() noexcept {}; + + // Forwarding constructor for custom allocators or initial capacities + template + constexpr explicit bulk_insert_wrapper(Args&&... args) + : container(std::forward(args)...) {} + + // thread safe + constexpr void make_room_for(const size_type count) noexcept { + pending_extra_size += count; + } + + // Element access based on std::vector + constexpr reference operator[](const size_type pos) { + OV_HARDEN_ASSERT_ACCESS(pos, "operator[]"); + return container[pos]; + } + constexpr const_reference operator[](const size_type pos) const { + OV_HARDEN_ASSERT_ACCESS(pos, "operator[]"); + return container[pos]; + } + + constexpr reference front() { + OV_HARDEN_ASSERT_NONEMPTY("front"); + return container[0]; + } + constexpr const_reference front() const { + OV_HARDEN_ASSERT_NONEMPTY("front"); + return container[0]; + } + + constexpr reference back() { + OV_HARDEN_ASSERT_NONEMPTY("back"); + return container[size()-1]; + } + constexpr const_reference back() const { + OV_HARDEN_ASSERT_NONEMPTY("back"); + return container[size()-1]; + } + + constexpr value_type* data() noexcept { return container.data(); } + constexpr value_type const* data() const noexcept { return container.data(); } + + // Iterators based on std::vector + constexpr iterator begin() noexcept { + return container.begin(); + } + constexpr const_iterator begin() const noexcept { + return container.begin(); + } + constexpr const_iterator cbegin() const noexcept { + return container.cbegin(); + } + + constexpr iterator end() noexcept { + return container.end(); + } + constexpr const_iterator end() const noexcept { + return container.end(); + } + constexpr const_iterator cend() const noexcept { + return container.cend(); + } + + constexpr reverse_iterator rbegin() noexcept { + return container.rbegin(); + } + constexpr const_reverse_iterator rbegin() const noexcept { + return container.rbegin(); + } + constexpr const_reverse_iterator crbegin() const noexcept { + return container.crbegin(); + } + + constexpr reverse_iterator rend() noexcept { + return container.rend(); + } + constexpr const_reverse_iterator rend() const noexcept { + return container.rend(); + } + constexpr const_reverse_iterator crend() const noexcept { + return container.crend(); + } + + // Capacity based on std::vector + constexpr bool empty() const noexcept { return size() <= size_type{}; } + constexpr size_type size() const noexcept { return container.size(); } + constexpr size_type max_size() const noexcept { return container.max_size(); } + // reserve() is omitted as we manage that via make_room_for + constexpr size_type capacity() const noexcept { return container.capacity(); } + constexpr void shrink_to_fit() { + pending_extra_size = size_type{}; + container.shrink_to_fit(); + } + + // Modifiers based on std::vector + constexpr void clear() noexcept { + pending_extra_size = size_type{}; + container.clear(); + } + + // the following could be implemented: + // - insert + // - insert_range + // - emplace + // - erase + // - append_range (C++23) + // - pop_back + // - swap + + constexpr void push_back(value_type const& value) { + flush_pending_room(); + container.push_back(value); + + } + constexpr void push_back(value_type&& value) { + flush_pending_room(); + container.push_back(std::move(value)); + } + + template + requires std::is_trivially_destructible_v + constexpr reference emplace_back(Args&&... args) { + return container.emplace_back(std::forward(args)...); + } + + template + constexpr void append_range(OtherContainerT const& other) { + append_range(other.begin(), other.end()); + } + + template + constexpr void append_range(const InputIt first, const InputIt last) { + flush_pending_room(); + + const size_type new_valid_size = size() + std::distance(first, last); + if (new_valid_size > container.capacity()) { + assert(!"append_range called without make_room_for"); + container.reserve(new_valid_size); + } + + std::uninitialized_copy(first, last, end()); + container.resize(new_valid_size); + } + + // resize() is omitted as we manage that via make_room_for + }; +} \ No newline at end of file diff --git a/src/openvic-simulation/core/Hash.hpp b/src/openvic-simulation/core/Hash.hpp index 2224dead1..3a6ef924b 100644 --- a/src/openvic-simulation/core/Hash.hpp +++ b/src/openvic-simulation/core/Hash.hpp @@ -47,9 +47,11 @@ namespace OpenVic { s = h(v) << (sizeof(T) * CHAR_BIT); ( [&] { - // If args is not last pointer of args - if (static_cast(&(std::get(arg_tuple))) != - static_cast(&args)) { + void const* const args_ptr = static_cast(&args); + void const* const last_pointer_of_args = static_cast( + &(std::get(arg_tuple)) + ); + if (args_ptr != last_pointer_of_args) { s <<= sizeof(Args) * CHAR_BIT; } s |= std::hash {}(args); diff --git a/src/openvic-simulation/core/portable/Deque.hpp b/src/openvic-simulation/core/portable/Deque.hpp index 95f80dcd1..3b40113c8 100644 --- a/src/openvic-simulation/core/portable/Deque.hpp +++ b/src/openvic-simulation/core/portable/Deque.hpp @@ -1022,8 +1022,10 @@ namespace OpenVic::utility::_detail::deque { // (_Myoff() + _Mysize() - 1) is for the last element, i.e. the back() of the deque. // Divide by _Block_size to get the unmasked index of the last used block. // Add 1 to get the unmasked index of the first unused block. - const auto _Unmasked_first_unused_block_idx = - static_cast(((_Myoff() + _Mysize() - 1) / _Block_size) + 1); + const auto _Unmasked_first_unused_block_idx = static_cast( + ((_Myoff() + _Mysize() - 1) / _Block_size) + + 1 + ); const auto _First_unused_block_idx = static_cast(_Unmasked_first_unused_block_idx & _Mask); @@ -1037,8 +1039,10 @@ namespace OpenVic::utility::_detail::deque { } } - const auto _Used_block_count = - static_cast(_Unmasked_first_unused_block_idx - _Unmasked_first_used_block_idx); + const auto _Used_block_count = static_cast( + _Unmasked_first_unused_block_idx + - _Unmasked_first_used_block_idx + ); size_type _New_block_count = _Minimum_map_size; // should be power of 2 @@ -1818,8 +1822,12 @@ namespace OpenVic::utility::_detail::deque { _EXPORT_STD template _NODISCARD bool operator==(const deque<_Ty, _Alloc>& _Left, const deque<_Ty, _Alloc>& _Right) { - return _Left.size() == _Right.size() && - _STD equal(_Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin()); + return _Left.size() == _Right.size() + && _STD equal( + _Left._Unchecked_begin(), + _Left._Unchecked_end(), + _Right._Unchecked_begin() + ); } #if _HAS_CXX20 diff --git a/src/openvic-simulation/core/portable/ForwardableSpan.hpp b/src/openvic-simulation/core/portable/ForwardableSpan.hpp index fe117bc0f..a4414860a 100644 --- a/src/openvic-simulation/core/portable/ForwardableSpan.hpp +++ b/src/openvic-simulation/core/portable/ForwardableSpan.hpp @@ -46,12 +46,12 @@ namespace OpenVic::_detail::forwardable_span { concept span_array_convertible = std::is_convertible_v; template - concept span_compatible_iterator = - std::contiguous_iterator && span_array_convertible>, T>; + concept span_compatible_iterator = std::contiguous_iterator + && span_array_convertible>, T>; template - concept span_compatible_sentinel_for = - std::sized_sentinel_for && !std::is_convertible_v; + concept span_compatible_sentinel_for = std::sized_sentinel_for + && !std::is_convertible_v; template struct extent_storage { diff --git a/src/openvic-simulation/core/random/RandomGenerator.hpp b/src/openvic-simulation/core/random/RandomGenerator.hpp index a010c146a..cae5294f3 100644 --- a/src/openvic-simulation/core/random/RandomGenerator.hpp +++ b/src/openvic-simulation/core/random/RandomGenerator.hpp @@ -15,10 +15,16 @@ namespace OpenVic { struct RandomGenerator { using generator_type = T; - using state_type = - std::conditional_t; - using result_type = - std::conditional_t; + using state_type = std::conditional_t< + requires { typename generator_type::state_type; }, + typename generator_type::state_type, + void + >; + using result_type = std::conditional_t< + requires { typename generator_type::result_type; }, + typename generator_type::result_type, + void + >; [[nodiscard]] OV_ALWAYS_INLINE explicit constexpr RandomGenerator() requires requires { diff --git a/src/openvic-simulation/core/template/Concepts.hpp b/src/openvic-simulation/core/template/Concepts.hpp index d21d92c12..dc856af0e 100644 --- a/src/openvic-simulation/core/template/Concepts.hpp +++ b/src/openvic-simulation/core/template/Concepts.hpp @@ -41,15 +41,16 @@ namespace OpenVic { concept not_same_as = !std::same_as; template> - concept move_insertable_allocator_for = - requires(Allocator& alloc, Value* value, T move) { std::allocator_traits::construct(alloc, value, move); }; + concept move_insertable_allocator_for = requires(Allocator& alloc, Value* value, T move) { + std::allocator_traits::construct(alloc, value, move); + }; template struct enable_copy_insertable : std::false_type {}; template - concept copy_insertable_allocator = enable_copy_insertable::value || - move_insertable_allocator_for; + concept copy_insertable_allocator = enable_copy_insertable::value + || move_insertable_allocator_for; template struct enable_copy_insertable> : std::is_copy_constructible {}; @@ -58,8 +59,8 @@ namespace OpenVic { struct enable_move_insertable : std::false_type {}; template - concept move_insertable_allocator = - enable_move_insertable::value || move_insertable_allocator_for; + concept move_insertable_allocator = enable_move_insertable::value + || move_insertable_allocator_for; template struct enable_move_insertable> : std::is_move_constructible {}; @@ -111,8 +112,9 @@ namespace OpenVic { concept is_strongly_typed = derived_from_specialization_of; template - concept has_index = requires { typename T::index_t; } && - is_strongly_typed && requires { + concept has_index = requires { typename T::index_t; } + && is_strongly_typed + && requires { static_cast( static_cast().index)>>(std::declval().index) ); diff --git a/src/openvic-simulation/country/CountryInstance.cpp b/src/openvic-simulation/country/CountryInstance.cpp index 14bfe7a3d..e0fbb21a1 100644 --- a/src/openvic-simulation/country/CountryInstance.cpp +++ b/src/openvic-simulation/country/CountryInstance.cpp @@ -1541,9 +1541,9 @@ void CountryInstance::_update_technology(const Date today) { } daily_research_points += get_modifier_effect_value(*modifier_effect_cache.get_research_points()); - daily_research_points *= fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_research_points_modifier()) + - get_modifier_effect_value(*modifier_effect_cache.get_increase_research()); + daily_research_points *= fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_research_points_modifier()) + + get_modifier_effect_value(*modifier_effect_cache.get_increase_research()); if (daily_research_points.get_untracked() < 0) { daily_research_points.set(0); @@ -1692,8 +1692,8 @@ void CountryInstance::_update_military() { // Mobilisation calculations mobilisation_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilization_impact()); - mobilisation_economy_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_tech()) + - get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_country()); + mobilisation_economy_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_tech()) + + get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_country()); // TODO - use country_defines.get_min_mobilize_limit(); (wiki: "lowest maximum of brigades you can mobilize. (by default 3)") @@ -1712,9 +1712,9 @@ void CountryInstance::_update_military() { get_modifier_effect_value(*modifier_effect_cache.get_max_war_exhaustion()), fixed_point_t::_0 ); - organisation_regain = fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + - get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); + organisation_regain = fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + + get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); land_organisation = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_land_organisation()); naval_organisation = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_naval_organisation()); @@ -1730,8 +1730,8 @@ void CountryInstance::_update_military() { get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()) ); dig_in_cap = get_modifier_effect_value(*modifier_effect_cache.get_dig_in_cap()).floor(); - military_tactics = military_defines.get_base_military_tactics() + - get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); + military_tactics = military_defines.get_base_military_tactics() + + get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); if (leadership_point_stockpile < 0) { leadership_point_stockpile = 0; @@ -1739,8 +1739,8 @@ void CountryInstance::_update_military() { create_leader_count = (leadership_point_stockpile / military_defines.get_leader_recruit_cost()).floor(); monthly_leadership_points += get_modifier_effect_value(*modifier_effect_cache.get_leadership()); - monthly_leadership_points *= fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); + monthly_leadership_points *= fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); if (monthly_leadership_points < 0) { monthly_leadership_points = 0; @@ -1782,7 +1782,7 @@ static constexpr Modifier const& get_country_status_static_effect( } } -void CountryInstance::update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache) { +void CountryInstance::update_modifier_sum_before_map(Date today, StaticModifierCache const& static_modifier_cache) { // Update sum of national modifiers modifier_sum.clear(); @@ -1856,15 +1856,23 @@ void CountryInstance::update_modifier_sum(Date today, StaticModifierCache const& // TODO - calculate stats for each unit type (locked and unlocked) } -void CountryInstance::contribute_province_modifier_sum(ModifierSum const& province_modifier_sum) { - modifier_sum.add_modifier_sum(province_modifier_sum); +void CountryInstance::update_modifier_sum_after_map(Date today) { + for (ProvinceInstance const* const province_ptr : controlled_provinces) { + if (OV_likely(province_ptr != nullptr)) { + modifier_sum.add_modifier_sum(province_ptr->get_modifier_sum()); + } + } +} + +void CountryInstance::make_room_for_province_modifier_sum(ModifierSum const& province_modifier_sum) { + modifier_sum.make_room_for(province_modifier_sum); } fixed_point_t CountryInstance::get_modifier_effect_value(ModifierEffect const& effect) const { return modifier_sum.get_modifier_effect_value(effect); } -void CountryInstance::update_gamestate(const Date today, MapInstance& map_instance) { +void CountryInstance::update_gamestate_after_map(const Date today) { if (is_civilised()) { civilisation_progress = 0; } else { @@ -1928,14 +1936,14 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan province->set_connected_to_capital(false); province->set_is_overseas(province_definition.get_continent() != capital_continent); - for (ProvinceDefinition::adjacency_t const& adjacency : province_definition.get_adjacencies()) { - // TODO - should we limit based on adjacency type? Straits and impassable still work in game, - // and water provinces don't have an owner so they'll get caught by the later checks anyway. - CountryInstance* neighbour = map_instance.get_province_instance_by_definition(adjacency.get_to()).get_owner(); - if (neighbour != nullptr && neighbour != this) { - neighbouring_countries.insert(neighbour); - } - } + // for (ProvinceDefinition::adjacency_t const& adjacency : province_definition.get_adjacencies()) { + // // TODO - should we limit based on adjacency type? Straits and impassable still work in game, + // // and water provinces don't have an owner so they'll get caught by the later checks anyway. + // CountryInstance* neighbour = map_instance.get_province_instance_by_definition(adjacency.get_to()).get_owner(); + // if (neighbour != nullptr && neighbour != this) { + // neighbouring_countries.insert(neighbour); + // } + // } } if (occupied_provinces_proportion != 0) { @@ -1945,21 +1953,21 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan if (capital != nullptr) { capital->set_connected_to_capital(true); - memory::vector> province_checklist { *capital }; + // memory::vector> province_checklist { *capital }; - for (size_t index = 0; index < province_checklist.size(); ++index) { - ProvinceInstance const& province = province_checklist[index]; + // for (size_t index = 0; index < province_checklist.size(); ++index) { + // ProvinceInstance const& province = province_checklist[index]; - for (ProvinceDefinition::adjacency_t const& adjacency : province.province_definition.get_adjacencies()) { - ProvinceInstance& adjacent_province = map_instance.get_province_instance_by_definition(adjacency.get_to()); + // for (ProvinceDefinition::adjacency_t const& adjacency : province.province_definition.get_adjacencies()) { + // ProvinceInstance& adjacent_province = map_instance.get_province_instance_by_definition(adjacency.get_to()); - if (adjacent_province.get_owner() == this && !adjacent_province.get_connected_to_capital()) { - adjacent_province.set_connected_to_capital(true); - adjacent_province.set_is_overseas(false); - province_checklist.emplace_back(adjacent_province); - } - } - } + // if (adjacent_province.get_owner() == this && !adjacent_province.get_connected_to_capital()) { + // adjacent_province.set_connected_to_capital(true); + // adjacent_province.set_is_overseas(false); + // province_checklist.emplace_back(adjacent_province); + // } + // } + // } } // Order of updates might need to be changed/functions split up to account for dependencies @@ -1977,8 +1985,8 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan _update_politics(); _update_diplomacy(); - const CountryDefinition::government_colour_map_t::const_iterator it = - country_definition.get_alternative_colours().find(government_type.get_untracked()); + using const_it_t = typename CountryDefinition::government_colour_map_t::const_iterator; + const const_it_t it = country_definition.get_alternative_colours().find(government_type.get_untracked()); if (it != country_definition.get_alternative_colours().end()) { colour = it.value(); diff --git a/src/openvic-simulation/country/CountryInstance.hpp b/src/openvic-simulation/country/CountryInstance.hpp index c9404f043..7d44c2ca9 100644 --- a/src/openvic-simulation/country/CountryInstance.hpp +++ b/src/openvic-simulation/country/CountryInstance.hpp @@ -685,8 +685,9 @@ namespace OpenVic { bool update_rule_set(); public: - void update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache); - void contribute_province_modifier_sum(ModifierSum const& province_modifier_sum); + void update_modifier_sum_before_map(Date today, StaticModifierCache const& static_modifier_cache); + void update_modifier_sum_after_map(Date today); + void make_room_for_province_modifier_sum(ModifierSum const& province_modifier_sum); fixed_point_t get_modifier_effect_value(ModifierEffect const& effect) const; constexpr void for_each_contributing_modifier( ModifierEffect const& effect, ContributingModifierCallback auto callback @@ -694,7 +695,7 @@ namespace OpenVic { return modifier_sum.for_each_contributing_modifier(effect, std::move(callback)); } - void update_gamestate(const Date today, MapInstance& map_instance); + void update_gamestate_after_map(const Date today); void country_tick_before_map( TypedSpan reusable_goods_mask, forwardable_span< diff --git a/src/openvic-simulation/country/CountryInstanceManager.cpp b/src/openvic-simulation/country/CountryInstanceManager.cpp index 090745d07..c0fd67c49 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.cpp +++ b/src/openvic-simulation/country/CountryInstanceManager.cpp @@ -197,8 +197,9 @@ CountryInstance const& CountryInstanceManager::get_country_instance_by_definitio } bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instance_manager) { - CountryHistoryManager const& history_manager = - instance_manager.definition_manager.get_history_manager().get_country_manager(); + CountryHistoryManager const& history_manager = instance_manager.definition_manager + .get_history_manager() + .get_country_manager(); bool ret = true; @@ -292,16 +293,16 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc return ret; } -void CountryInstanceManager::update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache) { - for (CountryInstance& country : country_instances) { - country.update_modifier_sum(today, static_modifier_cache); - } +void CountryInstanceManager::update_modifier_sums_before_map() { + thread_pool.process(work_t::COUNTRY_UPDATE_MODIFIER_SUMS_BEFORE_MAP); } -void CountryInstanceManager::update_gamestate(const Date today, MapInstance& map_instance) { - for (CountryInstance& country : country_instances) { - country.update_gamestate(today, map_instance); - } +void CountryInstanceManager::update_modifier_sums_after_map() { + thread_pool.process(work_t::COUNTRY_UPDATE_MODIFIER_SUMS_AFTER_MAP); +} + +void CountryInstanceManager::update_gamestate_after_map(const Date today) { + thread_pool.process(work_t::COUNTRY_UPDATE_GAMESTATE_AFTER_MAP); // TODO - work out how to have ranking effects applied (e.g. static modifiers) applied at game start // we can't just move update_rankings to the top of this function as it will choose initial GPs based on @@ -311,10 +312,10 @@ void CountryInstanceManager::update_gamestate(const Date today, MapInstance& map } void CountryInstanceManager::country_manager_tick_before_map() { - thread_pool.process_country_ticks_before_map(); + thread_pool.process(work_t::COUNTRY_TICK_BEFORE_MAP); } void CountryInstanceManager::country_manager_tick_after_map() { - thread_pool.process_country_ticks_after_map(); + thread_pool.process(work_t::COUNTRY_TICK_AFTER_MAP); shared_country_values.update_costs(); } diff --git a/src/openvic-simulation/country/CountryInstanceManager.hpp b/src/openvic-simulation/country/CountryInstanceManager.hpp index 3a589642b..c0230b7b4 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.hpp +++ b/src/openvic-simulation/country/CountryInstanceManager.hpp @@ -18,10 +18,8 @@ namespace OpenVic { struct CountryHistoryManager; struct GoodInstanceManager; struct InstanceManager; - struct MapInstance; struct PopsDefines; struct PopType; - struct StaticModifierCache; struct ThreadPool; struct CountryInstanceManager { @@ -71,8 +69,9 @@ namespace OpenVic { bool apply_history_to_countries(InstanceManager& instance_manager); - void update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache); - void update_gamestate(const Date today, MapInstance& map_instance); + void update_modifier_sums_before_map(); + void update_modifier_sums_after_map(); + void update_gamestate_after_map(const Date today); void country_manager_tick_before_map(); void country_manager_tick_after_map(); }; diff --git a/src/openvic-simulation/dataloader/Dataloader.cpp b/src/openvic-simulation/dataloader/Dataloader.cpp index 8fe7603e8..236bd99f4 100644 --- a/src/openvic-simulation/dataloader/Dataloader.cpp +++ b/src/openvic-simulation/dataloader/Dataloader.cpp @@ -15,6 +15,8 @@ #include "openvic-simulation/core/string/Utility.hpp" #include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/history/Bookmark.hpp" +#include "openvic-simulation/history/HistoryManager.hpp" #include "openvic-simulation/interface/UI.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/misc/SoundEffect.hpp" @@ -378,9 +380,10 @@ bool Dataloader::_load_pop_types(DefinitionManager& definition_manager) { bool ret = pop_manager.setup_stratas(); - GoodDefinitionManager const& good_definition_manager = - definition_manager.get_economy_manager().get_good_definition_manager(); - IdeologyManager const& ideology_manager = definition_manager.get_politics_manager().get_ideology_manager(); + EconomyManager const& economy_manager = definition_manager.get_economy_manager(); + GoodDefinitionManager const& good_definition_manager = economy_manager.get_good_definition_manager(); + PoliticsManager const& politics_manager = definition_manager.get_politics_manager(); + IdeologyManager const& ideology_manager = politics_manager.get_ideology_manager(); static constexpr std::string_view pop_type_directory = "poptypes"; @@ -585,8 +588,10 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse DeploymentManager& deployment_manager = definition_manager.get_military_manager().get_deployment_manager(); static constexpr std::string_view country_history_directory = "history/countries"; - const path_vector_t country_history_files = - lookup_basic_identifier_prefixed_files_in_dir(country_history_directory, ".txt"); + const path_vector_t country_history_files = lookup_basic_identifier_prefixed_files_in_dir( + country_history_directory, + ".txt" + ); country_history_manager.reserve_more_country_histories(country_history_files.size()); deployment_manager.reserve_more_deployments(country_history_files.size()); @@ -597,8 +602,10 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse const memory::string filename = file.stem().string(memory::string::allocator_type{}); const std::string_view country_id = extract_basic_identifier_prefix(filename); - CountryDefinition const* country = - definition_manager.get_country_definition_manager().get_country_definition_by_identifier(country_id); + CountryDefinitionManager const& country_definition_manager = definition_manager.get_country_definition_manager(); + CountryDefinition const* country = country_definition_manager.get_country_definition_by_identifier( + country_id + ); if (country == nullptr) { if (unused_history_file_warnings) { spdlog::warn_s("Found history file for non-existent country: {}", country_id); @@ -623,14 +630,17 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse } } + HistoryManager& history_manager = definition_manager.get_history_manager(); { /* Province History */ ProvinceHistoryManager& province_history_manager = definition_manager.get_history_manager().get_province_manager(); MapDefinition const& map_definition = definition_manager.get_map_definition(); static constexpr std::string_view province_history_directory = "history/provinces"; - const path_vector_t province_history_files = - lookup_basic_identifier_prefixed_files_in_dir_recursive(province_history_directory, ".txt"); + const path_vector_t province_history_files = lookup_basic_identifier_prefixed_files_in_dir_recursive( + province_history_directory, + ".txt" + ); province_history_manager.reserve_more_province_histories(province_history_files.size()); @@ -660,8 +670,8 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse static constexpr std::string_view pop_history_directory = "history/pops/"; const string_set_t pop_history_dirs = lookup_dirs_in_dir(pop_history_directory); - const Date last_bookmark_date = - definition_manager.get_history_manager().get_bookmark_manager().get_last_bookmark_date(); + BookmarkManager const& bookmark_manager = history_manager.get_bookmark_manager(); + const Date last_bookmark_date = bookmark_manager.get_last_bookmark_date(); for (memory::string const& dir : pop_history_dirs) { Date::from_chars_result result; @@ -692,8 +702,7 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse { /* Diplomacy History */ - DiplomaticHistoryManager& diplomatic_history_manager = - definition_manager.get_history_manager().get_diplomacy_manager(); + DiplomaticHistoryManager& diplomatic_history_manager = history_manager.get_diplomacy_manager(); static constexpr std::string_view diplomacy_history_directory = "history/diplomacy"; diff --git a/src/openvic-simulation/dataloader/NodeTools.hpp b/src/openvic-simulation/dataloader/NodeTools.hpp index 343be7659..60ba1ec42 100644 --- a/src/openvic-simulation/dataloader/NodeTools.hpp +++ b/src/openvic-simulation/dataloader/NodeTools.hpp @@ -162,8 +162,9 @@ using namespace std::string_view_literals; template NodeCallback auto expect_int(callback_t& callback, int base = 10) { return expect_int64([callback](int64_t val) mutable -> bool { - if (static_cast(std::numeric_limits::lowest()) <= val && - val <= static_cast(std::numeric_limits::max())) { + if (static_cast(std::numeric_limits::lowest()) <= val + && val <= static_cast(std::numeric_limits::max()) + ) { return callback(val); } spdlog::error_s( diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp index 3b169d6ea..279a80edb 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp @@ -130,8 +130,11 @@ static fs::path _search_for_game_path(fs::path hint_path) { if (hint_empty) { #if defined(_WIN32) - static const fs::path registry_path = - Windows::ReadRegValue(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); + static const fs::path registry_path = Windows::ReadRegValue( + HKEY_LOCAL_MACHINE, + "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", + "path" + ); if (!registry_path.empty()) { return registry_path; @@ -214,8 +217,12 @@ static fs::path _search_for_game_path(fs::path hint_path) { bool vic2_install_confirmed = false; // if current_path is not a regular file, this is a non-default Steam Library, skip this parser evaluation - if (fs::is_regular_file(current_path, error_code) && - (is_libraryfolders_vdf || filename_equals(libraryfolders, current_path))) { + if (fs::is_regular_file(current_path, error_code) + && ( + is_libraryfolders_vdf + || filename_equals(libraryfolders, current_path) + ) + ) { lexy_vdf::Parser parser; memory::string buffer; @@ -349,13 +356,20 @@ static fs::path _search_for_game_path(fs::path hint_path) { } bool is_Victoria_2_folder = false; - if ((is_common_folder || filename_equals(common_folder, vic2_steam_lib_directory)) && - fs::is_directory(vic2_steam_lib_directory, error_code)) { + if (( + is_common_folder + || filename_equals(common_folder, vic2_steam_lib_directory) + ) && fs::is_directory(vic2_steam_lib_directory, error_code) + ) { vic2_steam_lib_directory /= Victoria_2_folder; is_Victoria_2_folder = true; } - if ((is_Victoria_2_folder || filename_equals(Victoria_2_folder, vic2_steam_lib_directory)) && - fs::is_regular_file(vic2_steam_lib_directory / v2_game_exe, error_code)) { + + if (( + is_Victoria_2_folder + || filename_equals(Victoria_2_folder, vic2_steam_lib_directory) + ) && fs::is_regular_file(vic2_steam_lib_directory / v2_game_exe, error_code) + ) { return vic2_steam_lib_directory; } diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp index f84d8002a..b3fc80d0e 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp @@ -88,11 +88,11 @@ namespace OpenVic::Windows { } bool is_predefined() const { - return (_key_handle == HKEY_CURRENT_USER) || (_key_handle == HKEY_LOCAL_MACHINE) || - (_key_handle == HKEY_CLASSES_ROOT) || (_key_handle == HKEY_CURRENT_CONFIG) || - (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (_key_handle == HKEY_PERFORMANCE_DATA) || - (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || (_key_handle == HKEY_PERFORMANCE_TEXT) || - (_key_handle == HKEY_USERS); + return (_key_handle == HKEY_CURRENT_USER) || (_key_handle == HKEY_LOCAL_MACHINE) + || (_key_handle == HKEY_CLASSES_ROOT) || (_key_handle == HKEY_CURRENT_CONFIG) + || (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (_key_handle == HKEY_PERFORMANCE_DATA) + || (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || (_key_handle == HKEY_PERFORMANCE_TEXT) + || (_key_handle == HKEY_USERS); } LSTATUS close_key() { diff --git a/src/openvic-simulation/diplomacy/CountryRelation.hpp b/src/openvic-simulation/diplomacy/CountryRelation.hpp index 6780ae663..364adbbe8 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.hpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.hpp @@ -222,8 +222,10 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& - operator%=(influence_value_type& lhs, influence_value_type const& rhs) { + friend inline constexpr influence_value_type& operator%=( + influence_value_type& lhs, + influence_value_type const& rhs + ) { return lhs %= rhs.value; } diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp index 92f7ea98c..689dea62a 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp @@ -78,122 +78,109 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { result &= add_diplomatic_action( "form_alliance", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_country_alliance( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( "end_alliance", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // - arg.sender, arg.receiver, false - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_country_alliance( // + arg.sender, arg.receiver, false + ); + }, } ); result &= add_diplomatic_action( "call_ally", { .commit = [](Argument& arg) {}, - .allowed = - [](Argument const& arg) { - return false; - }, - .get_acceptance = - [](Argument const& arg) { - return 1; - }, + .allowed = [](Argument const& arg) { + return false; + }, + .get_acceptance = [](Argument const& arg) { + return 1; + }, } ); result &= add_diplomatic_action( "request_military_access", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( // "give_military_access", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( "increase_relations", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( - arg.sender, arg.receiver - ) += 25; // TODO: implement defines.diplomacy.INCREASERELATION_RELATION_ON_ACCEPT - }, - .allowed = - [](Argument const& arg) { - return false; - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) += 25; // TODO: implement defines.diplomacy.INCREASERELATION_RELATION_ON_ACCEPT + }, + .allowed = [](Argument const& arg) { + return false; + }, } ); result &= add_diplomatic_action( "decrease_relations", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( - arg.sender, arg.receiver - ) -= 25; // TODO: implement defines.diplomacy.DECREASERELATION_RELATION_ON_ACCEPT - }, - .allowed = - [](Argument const& arg) { - return false; - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) -= 25; // TODO: implement defines.diplomacy.DECREASERELATION_RELATION_ON_ACCEPT + }, + .allowed = [](Argument const& arg) { + return false; + }, } ); result &= add_diplomatic_action( "war_subsidies", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( "end_war_subsidies", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // - arg.sender, arg.receiver, false - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // + arg.sender, arg.receiver, false + ); + }, } ); result &= add_diplomatic_action( "declare_war", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_at_war_with( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_at_war_with( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( @@ -205,24 +192,22 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { result &= add_diplomatic_action( "command_units", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( // - arg.sender, arg.receiver - ) = true; - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( // + arg.sender, arg.receiver + ) = true; + }, } ); result &= add_diplomatic_action( "discredit", { .influence_cost = 25, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_discredited_date( // - arg.sender, arg.receiver, arg.instance_manager.get_today() + 180 - ); // TODO: implement defines.diplomacy.DISCREDIT_DAYS - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_discredited_date( // + arg.sender, arg.receiver, arg.instance_manager.get_today() + 180 + ); // TODO: implement defines.diplomacy.DISCREDIT_DAYS + }, } ); result &= add_diplomatic_action( @@ -236,99 +221,88 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { "ban_embassy", { .influence_cost = 65, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( // - arg.sender, arg.receiver, arg.instance_manager.get_today() + Timespan::from_years(1) - ); // TODO: implement defines.diplomacy.BANEMBASSY_DAYS - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( // + arg.sender, arg.receiver, arg.instance_manager.get_today() + Timespan::from_years(1) + ); // TODO: implement defines.diplomacy.BANEMBASSY_DAYS + }, } ); result &= add_diplomatic_action( "increase_opinion", { .influence_cost = 50, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - )++; - }, - .allowed = - [](Argument const& arg) { - return true; - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + arg.sender, arg.receiver + )++; + }, + .allowed = [](Argument const& arg) { + return true; + }, } ); result &= add_diplomatic_action( "decrease_opinion", { .influence_cost = 50, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - std::any_cast(arg.context_data), arg.receiver - ); - }, - .allowed = - [](Argument const& arg) { - return true; - }, + .commit = [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + std::any_cast(arg.context_data), arg.receiver + ); + }, + .allowed = [](Argument const& arg) { + return true; + }, } ); result &= add_diplomatic_action( "add_to_sphere", { .influence_cost = 100, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - ) = CountryRelationManager::OpinionType::Sphere; - }, - .allowed = - [](Argument const& arg) { - return true; - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + arg.sender, arg.receiver + ) = CountryRelationManager::OpinionType::Sphere; + }, + .allowed = [](Argument const& arg) { + return true; + }, } ); result &= add_diplomatic_action( "remove_from_foreign_sphere", { .influence_cost = 100, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - std::any_cast(arg.context_data), arg.receiver - ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // - arg.sender, arg.receiver - ) -= 10; - }, - .allowed = - [](Argument const& arg) { - return true; - }, + .commit = [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + std::any_cast(arg.context_data), arg.receiver + ); + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // + arg.sender, arg.receiver + ) -= 10; + }, + .allowed = [](Argument const& arg) { + return true; + }, } ); result &= add_diplomatic_action( "remove_from_own_sphere", { .influence_cost = 100, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // - arg.sender, arg.receiver - ) -= 10; - // TODO: implement REMOVEFROMSPHERE_PRESTIGE_COST and REMOVEFROMSPHERE_INFAMY_COST - }, - .allowed = - [](Argument const& arg) { - return true; - }, + .commit = [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + arg.sender, arg.receiver + ); + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // + arg.sender, arg.receiver + ) -= 10; + // TODO: implement REMOVEFROMSPHERE_PRESTIGE_COST and REMOVEFROMSPHERE_INFAMY_COST + }, + .allowed = [](Argument const& arg) { + return true; + }, } ); result &= add_diplomatic_action( @@ -340,23 +314,21 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { result &= add_diplomatic_action( "give_vision", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // - arg.sender, arg.receiver, true - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_vision( // + arg.sender, arg.receiver, true + ); + }, } ); result &= add_diplomatic_action( "remove_vision", { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // - arg.sender, arg.receiver, false - ); - }, + .commit = [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_vision( // + arg.sender, arg.receiver, false + ); + }, } ); diplomatic_action_types.lock(); diff --git a/src/openvic-simulation/economy/GoodDefinition.cpp b/src/openvic-simulation/economy/GoodDefinition.cpp index 1d733593c..e2ee127c4 100644 --- a/src/openvic-simulation/economy/GoodDefinition.cpp +++ b/src/openvic-simulation/economy/GoodDefinition.cpp @@ -137,7 +137,7 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager using enum ModifierEffect::format_t; using enum ModifierEffect::target_t; - memory::FixedVector& good_effects = modifier_manager.modifier_effect_cache.good_effects; + decltype(ModifierEffectCache::good_effects)& good_effects = modifier_manager.modifier_effect_cache.good_effects; good_effects = std::move( decltype(ModifierEffectCache::good_effects) { generate_values, diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp index 8bc0435ba..eb1ee0c43 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp @@ -290,8 +290,9 @@ fixed_point_t ResourceGatheringOperation::produce() { + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_output()); if (production_type.get_is_farm_for_tech()) { - const fixed_point_t farm_rgo_throughput_and_output = - location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_throughput_and_output()); + const fixed_point_t farm_rgo_throughput_and_output = location.get_modifier_effect_value( + *modifier_effect_cache.get_farm_rgo_throughput_and_output() + ); throughput_multiplier += farm_rgo_throughput_and_output; output_multiplier += farm_rgo_throughput_and_output; } @@ -302,8 +303,9 @@ fixed_point_t ResourceGatheringOperation::produce() { } if (production_type.get_is_mine_for_tech()) { - const fixed_point_t mine_rgo_throughput_and_output = - location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_throughput_and_output()); + const fixed_point_t mine_rgo_throughput_and_output = location.get_modifier_effect_value( + *modifier_effect_cache.get_mine_rgo_throughput_and_output() + ); throughput_multiplier += mine_rgo_throughput_and_output; output_multiplier += mine_rgo_throughput_and_output; } @@ -331,9 +333,16 @@ fixed_point_t ResourceGatheringOperation::produce() { const fixed_point_t effect_multiplier = job.effect_multiplier; const fixed_point_t amount = job.amount; const fixed_point_t effect = effect_multiplier != fixed_point_t::_1 - && fp::from_fraction(employees_of_type, max_employee_count_cache) > amount - ? effect_multiplier * amount //special Vic2 logic - : fp::mul_div(effect_multiplier, employees_of_type, max_employee_count_cache); + && fp::from_fraction( + employees_of_type, + max_employee_count_cache + ) > amount + ? effect_multiplier * amount //special Vic2 logic + : fp::mul_div( + effect_multiplier, + employees_of_type, + max_employee_count_cache + ); switch (job.effect_type) { case Job::effect_t::OUTPUT: diff --git a/src/openvic-simulation/economy/trading/MarketInstance.cpp b/src/openvic-simulation/economy/trading/MarketInstance.cpp index b39cea789..e18b9d52b 100644 --- a/src/openvic-simulation/economy/trading/MarketInstance.cpp +++ b/src/openvic-simulation/economy/trading/MarketInstance.cpp @@ -78,7 +78,7 @@ void MarketInstance::place_market_sell_order(MarketSellOrder&& market_sell_order } void MarketInstance::execute_orders() { - thread_pool.process_good_execute_orders(); + thread_pool.process(work_t::GOOD_EXECUTE_ORDERS); } void MarketInstance::record_price_history() { diff --git a/src/openvic-simulation/history/CountryHistory.cpp b/src/openvic-simulation/history/CountryHistory.cpp index 8a523256e..46baea2ce 100644 --- a/src/openvic-simulation/history/CountryHistory.cpp +++ b/src/openvic-simulation/history/CountryHistory.cpp @@ -343,10 +343,16 @@ bool CountryHistoryManager::load_country_history_file( decltype(country_histories)::iterator it = country_histories.find(&country); if (it == country_histories.end()) { - const std::pair result = - country_histories.emplace(&country, CountryHistoryMap { country, ideology_keys, government_type_keys }); - if (result.second) { - it = result.first; + auto const [new_it, result] = country_histories.emplace( + &country, + CountryHistoryMap { + country, + ideology_keys, + government_type_keys + } + ); + if (result) { + it = new_it; } else { spdlog::error_s("Failed to create country history map for country {}", country); return false; diff --git a/src/openvic-simulation/history/ProvinceHistory.cpp b/src/openvic-simulation/history/ProvinceHistory.cpp index 530c3698e..b9033d7a8 100644 --- a/src/openvic-simulation/history/ProvinceHistory.cpp +++ b/src/openvic-simulation/history/ProvinceHistory.cpp @@ -40,8 +40,8 @@ bool ProvinceHistoryMap::_load_history_entry( ) { BuildingTypeManager const& building_type_manager = definition_manager.get_economy_manager().get_building_type_manager(); CountryDefinitionManager const& country_definition_manager = definition_manager.get_country_definition_manager(); - GoodDefinitionManager const& good_definition_manager = - definition_manager.get_economy_manager().get_good_definition_manager(); + EconomyManager const& economy_manager = definition_manager.get_economy_manager(); + GoodDefinitionManager const& good_definition_manager = economy_manager.get_good_definition_manager(); IdeologyManager const& ideology_manager = definition_manager.get_politics_manager().get_ideology_manager(); TerrainTypeManager const& terrain_type_manager = definition_manager.get_map_definition().get_terrain_type_manager(); @@ -276,16 +276,19 @@ ProvinceHistoryMap const* ProvinceHistoryManager::get_province_history(ProvinceD ProvinceHistoryMap* ProvinceHistoryManager::_get_or_make_province_history(ProvinceDefinition const& province) { decltype(province_histories)::iterator it = province_histories.find(&province); if (it == province_histories.end()) { - const std::pair result = - province_histories.emplace( - &province, - ProvinceHistoryMap { - province, - definition_manager.get_economy_manager().get_building_type_manager() - } - ); - if (result.second) { - it = result.first; + const auto [ + new_it, + was_emplaced + ] = province_histories.emplace( + &province, + ProvinceHistoryMap { + province, + definition_manager.get_economy_manager().get_building_type_manager() + } + ); + + if (was_emplaced) { + it = new_it; } else { spdlog::error_s("Failed to create province history map for province {}", province); return nullptr; diff --git a/src/openvic-simulation/map/MapDefinition.cpp b/src/openvic-simulation/map/MapDefinition.cpp index 8e021edce..075c6ebf2 100644 --- a/src/openvic-simulation/map/MapDefinition.cpp +++ b/src/openvic-simulation/map/MapDefinition.cpp @@ -739,8 +739,12 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) for (const auto& neighbour : neighbours) { ivec2_t neighbour_pos = { segment.point.x + neighbour.offset.x, segment.point.y + neighbour.offset.y }; - if (neighbour_pos.x < 0 || neighbour_pos.y < 0 || neighbour_pos.x >= rivers_bmp.get_width() || - neighbour_pos.y >= rivers_bmp.get_height() || segment.direction == neighbour.old_direction) { + if (neighbour_pos.x < 0 + || neighbour_pos.y < 0 + || neighbour_pos.x >= rivers_bmp.get_width() + || neighbour_pos.y >= rivers_bmp.get_height() + || segment.direction == neighbour.old_direction + ) { continue; } @@ -848,10 +852,10 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons return false; } - if (province_bmp.get_width() != terrain_bmp.get_width() || - province_bmp.get_height() != terrain_bmp.get_height() || - province_bmp.get_width() != rivers_bmp.get_width() || - province_bmp.get_height() != rivers_bmp.get_height() + if (province_bmp.get_width() != terrain_bmp.get_width() + || province_bmp.get_height() != terrain_bmp.get_height() + || province_bmp.get_width() != rivers_bmp.get_width() + || province_bmp.get_height() != rivers_bmp.get_height() ) { spdlog::error_s( "Mismatched map BMP dims: provinces:{}x{}, terrain: {}x{}, rivers: {}x{}", diff --git a/src/openvic-simulation/map/MapInstance.cpp b/src/openvic-simulation/map/MapInstance.cpp index 4b8cc6286..0df33026d 100644 --- a/src/openvic-simulation/map/MapInstance.cpp +++ b/src/openvic-simulation/map/MapInstance.cpp @@ -82,82 +82,109 @@ bool MapInstance::is_canal_enabled(canal_index_t canal_index) const { return enabled_canals.contains(canal_index); } -bool MapInstance::apply_history_to_provinces( +bool MapInstance::apply_history_to_province( ProvinceHistoryManager const& history_manager, const Date date, CountryInstanceManager& country_manager, MilitaryDefines const& military_defines, PopDeps const& pop_deps, TypedSpan pop_types, - TypedSpan reforms + TypedSpan reforms, + ProvinceInstance& province ) { + ProvinceDefinition const& province_definition = province.province_definition; + if (province_definition.is_water()) { + return true; + } + + ProvinceHistoryMap const* history_map = history_manager.get_province_history(&province_definition); + + if (history_map == nullptr) { + return true; + } + bool ret = true; + ProvinceHistoryEntry const* pop_history_entry = nullptr; + ProductionType const* rgo_production_type_nullable = nullptr; - for (ProvinceInstance& province : get_province_instances()) { - ProvinceDefinition const& province_definition = province.province_definition; - if (!province_definition.is_water()) { - ProvinceHistoryMap const* history_map = history_manager.get_province_history(&province_definition); - - if (history_map != nullptr) { - ProvinceHistoryEntry const* pop_history_entry = nullptr; - ProductionType const* rgo_production_type_nullable = nullptr; - - for (auto const& [entry_date, entry] : history_map->get_entries()) { - if (entry_date > date) { - if (pop_history_entry != nullptr) { - break; - } - } else { - province.apply_history_to_province(*entry, country_manager); - std::optional const& rgo_production_type_nullable_optional = - entry->get_rgo_production_type_nullable(); - if (rgo_production_type_nullable_optional.has_value()) { - rgo_production_type_nullable = rgo_production_type_nullable_optional.value(); - } - } - - if (!entry->get_pops().empty()) { - pop_history_entry = entry.get(); - } - } - - if (pop_history_entry == nullptr) { - spdlog::warn_s("No pop history entry for province {} for date {}", province, date); - } else { - ret &= province.add_pop_vec( - pop_history_entry->get_pops(), - pop_deps - ); - province.setup_pop_test_values(reforms); - - //update pops so OOB can use up to date max_supported_regiments - province._update_pops(military_defines); - } - - ret &= province.set_rgo_production_type_nullable( - pop_types, - rgo_production_type_nullable - ); + for (auto const& [entry_date, entry] : history_map->get_entries()) { + if (entry_date > date) { + if (pop_history_entry != nullptr) { + break; } + } else { + province.apply_history_to_province(*entry, country_manager); + std::optional const& rgo_production_type_nullable_optional = + entry->get_rgo_production_type_nullable(); + if (rgo_production_type_nullable_optional.has_value()) { + rgo_production_type_nullable = rgo_production_type_nullable_optional.value(); + } + } + + if (!entry->get_pops().empty()) { + pop_history_entry = entry.get(); } } + if (pop_history_entry == nullptr) { + spdlog::warn_s("No pop history entry for province {} for date {}", province, date); + } else { + ret &= province.add_pop_vec( + pop_history_entry->get_pops(), + pop_deps + ); + province.setup_pop_test_values(reforms); + + //update pops so OOB can use up to date max_supported_regiments + province._update_pops(military_defines); + } + + ret &= province.set_rgo_production_type_nullable( + pop_types, + rgo_production_type_nullable + ); + return ret; } -void MapInstance::update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache) { +bool MapInstance::apply_history_to_provinces( + ProvinceHistoryManager const& history_manager, + const Date date, + CountryInstanceManager& country_manager, + MilitaryDefines const& military_defines, + PopDeps const& pop_deps, + TypedSpan pop_types, + TypedSpan reforms +) { + bool ret = true; + for (ProvinceInstance& province : get_province_instances()) { - province.update_modifier_sum(today, static_modifier_cache); + apply_history_to_province( + history_manager, + date, + country_manager, + military_defines, + pop_deps, + pop_types, + reforms, + province + ); } + + return ret; } -void MapInstance::update_gamestate(InstanceManager const& instance_manager) { +void MapInstance::update_modifier_sums(const Date today) { + thread_pool.process(work_t::PROVINCE_UPDATE_MODIFIER_SUMS); +} + +void MapInstance::update_gamestate() { highest_province_population = 0; total_map_population = 0; - for (ProvinceInstance& province : get_province_instances()) { - province.update_gamestate(instance_manager); + thread_pool.process(work_t::PROVINCE_UPDATE_GAMESTATE); + for (ProvinceInstance& province : get_province_instances()) { // Update population stats const pop_sum_t province_population = province.get_total_population(); if (highest_province_population < province_population) { @@ -170,13 +197,13 @@ void MapInstance::update_gamestate(InstanceManager const& instance_manager) { } void MapInstance::map_tick() { - thread_pool.process_province_ticks(); + thread_pool.process(work_t::PROVINCE_TICK); //state tick //after province tick as province tick sets pop employment to 0 //state tick will update pop employment via factories } -void MapInstance::initialise_for_new_game(InstanceManager const& instance_manager) { - update_gamestate(instance_manager); - thread_pool.process_province_initialise_for_new_game(); +void MapInstance::initialise_for_new_game() { + update_gamestate(); + thread_pool.process(work_t::PROVINCE_INITIALISE_FOR_NEW_GAME); } \ No newline at end of file diff --git a/src/openvic-simulation/map/MapInstance.hpp b/src/openvic-simulation/map/MapInstance.hpp index 0c37d5589..9835beb20 100644 --- a/src/openvic-simulation/map/MapInstance.hpp +++ b/src/openvic-simulation/map/MapInstance.hpp @@ -1,5 +1,6 @@ #pragma once +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/map/State.hpp" @@ -42,6 +43,17 @@ namespace OpenVic { ArmyAStarPathing PROPERTY_REF(land_pathing); NavyAStarPathing PROPERTY_REF(sea_pathing); + OV_SPEED_INLINE bool apply_history_to_province( + ProvinceHistoryManager const& history_manager, + const Date date, + CountryInstanceManager& country_manager, + MilitaryDefines const& military_defines, + PopDeps const& pop_deps, + TypedSpan pop_types, + TypedSpan reforms, + ProvinceInstance& province + ); + public: MapInstance( MapDefinition const& new_map_definition, @@ -85,9 +97,9 @@ namespace OpenVic { TypedSpan reforms ); - void update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache); - void update_gamestate(InstanceManager const& instance_manager); + void update_modifier_sums(const Date today); + void update_gamestate(); void map_tick(); - void initialise_for_new_game(InstanceManager const& instance_manager); + void initialise_for_new_game(); }; } diff --git a/src/openvic-simulation/map/Mapmode.cpp b/src/openvic-simulation/map/Mapmode.cpp index 7b4d75767..d4bdd5890 100644 --- a/src/openvic-simulation/map/Mapmode.cpp +++ b/src/openvic-simulation/map/Mapmode.cpp @@ -346,46 +346,47 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin ret &= add_mapmode( "mapmode_adjacencies", []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, ProvinceInstance const& scoped_prov_instance, + CountryInstance const* player_country, ProvinceInstance const* selected_prov_instance_ptr ) -> Mapmode::base_stripe_t { - if (selected_province != nullptr) { - ProvinceDefinition const& selected_province_definition = selected_province->province_definition; + if (selected_prov_instance_ptr == nullptr) { + return colour_argb_t::null(); + } - if (*selected_province == province) { - return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); - } + ProvinceDefinition const& selected_prov_definition = selected_prov_instance_ptr->province_definition; - ProvinceDefinition const& province_definition = province.province_definition; - - colour_argb_t base = colour_argb_t::null(), stripe = colour_argb_t::null(); - ProvinceDefinition::adjacency_t const* adj = - selected_province_definition.get_adjacency_to(province_definition); - - if (adj != nullptr) { - colour_argb_t::integer_type base_int; - switch (adj->get_type()) { - using enum ProvinceDefinition::adjacency_t::type_t; - case LAND: base_int = 0x00FF00; break; - case WATER: base_int = 0x0000FF; break; - case COASTAL: base_int = 0xF9D199; break; - case IMPASSABLE: base_int = 0x8B4513; break; - case STRAIT: base_int = 0x00FFFF; break; - case CANAL: base_int = 0x888888; break; - default: base_int = 0xFF0000; break; - } - base = colour_argb_t::from_integer(base_int).with_alpha(ALPHA_VALUE); - stripe = base; - } + if (*selected_prov_instance_ptr == scoped_prov_instance) { + return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); + } + + ProvinceDefinition const& scoped_prov_definition = scoped_prov_instance.province_definition; + + colour_argb_t base = colour_argb_t::null(), stripe = colour_argb_t::null(); + ProvinceDefinition::adjacency_t const* adj = selected_prov_definition.get_adjacency_to( + scoped_prov_definition + ); - if (selected_province_definition.has_adjacency_going_through(province_definition)) { - stripe = (0xFFFF00_argb).with_alpha(ALPHA_VALUE); + if (adj != nullptr) { + colour_argb_t::integer_type base_int; + switch (adj->get_type()) { + using enum ProvinceDefinition::adjacency_t::type_t; + case LAND: base_int = 0x00FF00; break; + case WATER: base_int = 0x0000FF; break; + case COASTAL: base_int = 0xF9D199; break; + case IMPASSABLE: base_int = 0x8B4513; break; + case STRAIT: base_int = 0x00FFFF; break; + case CANAL: base_int = 0x888888; break; + default: base_int = 0xFF0000; break; } + base = colour_argb_t::from_integer(base_int).with_alpha(ALPHA_VALUE); + stripe = base; + } - return { base, stripe }; + if (selected_prov_definition.has_adjacency_going_through(scoped_prov_definition)) { + stripe = (0xFFFF00_argb).with_alpha(ALPHA_VALUE); } - return colour_argb_t::null(); + return { base, stripe }; } ); } diff --git a/src/openvic-simulation/map/ProvinceInstance.cpp b/src/openvic-simulation/map/ProvinceInstance.cpp index b10a92072..22bfdbcb8 100644 --- a/src/openvic-simulation/map/ProvinceInstance.cpp +++ b/src/openvic-simulation/map/ProvinceInstance.cpp @@ -4,18 +4,26 @@ #include -#include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" +#include "openvic-simulation/country/CountryInstanceManager.hpp" #include "openvic-simulation/defines/MilitaryDefines.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/economy/BuildingInstance.hpp" #include "openvic-simulation/economy/BuildingType.hpp" #include "openvic-simulation/economy/production/Employee.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" -#include "openvic-simulation/InstanceManager.hpp" +#include "openvic-simulation/history/ProvinceHistory.hpp" +#include "openvic-simulation/map/Crime.hpp" +#include "openvic-simulation/map/MapInstance.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" +#include "openvic-simulation/map/Region.hpp" +#include "openvic-simulation/map/TerrainType.hpp" +#include "openvic-simulation/military/UnitInstanceGroup.hpp" +#include "openvic-simulation/military/UnitType.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/modifier/StaticModifierCache.hpp" +#include "openvic-simulation/politics/Reform.hpp" +#include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" #include "openvic-simulation/types/TypedIndices.hpp" @@ -42,6 +50,8 @@ ProvinceInstance::ProvinceInstance( } } { + adjacencies.reserve(new_province_definition.get_adjacencies().size()); + adjacent_nonempty_land_provinces.reserve(new_province_definition.get_adjacencies().size()); modifier_sum.set_this_source(this); rgo.setup_location_ptr(*this); } @@ -216,10 +226,16 @@ void ProvinceInstance::_update_pops(MilitaryDefines const& military_defines) { using enum colony_status_t; - const fixed_point_t pop_size_per_regiment_multiplier = - colony_status == PROTECTORATE ? military_defines.get_pop_size_per_regiment_protectorate_multiplier() - : colony_status == COLONY ? military_defines.get_pop_size_per_regiment_colony_multiplier() - : is_owner_core() ? fixed_point_t::_1 : military_defines.get_pop_size_per_regiment_non_core_multiplier(); + fixed_point_t pop_size_per_regiment_multiplier; + if (colony_status == PROTECTORATE) { + pop_size_per_regiment_multiplier = military_defines.get_pop_size_per_regiment_protectorate_multiplier(); + } else if (colony_status == COLONY) { + pop_size_per_regiment_multiplier = military_defines.get_pop_size_per_regiment_colony_multiplier(); + } else if (is_owner_core()) { + pop_size_per_regiment_multiplier = fixed_point_t::_1; + } else { + pop_size_per_regiment_multiplier = military_defines.get_pop_size_per_regiment_non_core_multiplier(); + } for (Pop& pop : pops) { pops_cache_by_type[pop.get_type().index].push_back(pop); @@ -233,7 +249,7 @@ void ProvinceInstance::_update_pops(MilitaryDefines const& military_defines) { normalise_pops_aggregate(); } -void ProvinceInstance::update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache) { +void ProvinceInstance::update_modifier_sum(const Date today, StaticModifierCache const& static_modifier_cache) { // Update sum of direct province modifiers modifier_sum.clear(); @@ -284,7 +300,21 @@ void ProvinceInstance::update_modifier_sum(Date today, StaticModifierCache const } if (controller != nullptr) { - controller->contribute_province_modifier_sum(modifier_sum); + controller->make_room_for_province_modifier_sum(modifier_sum); + } +} + +void ProvinceInstance::update_adjecencies() { + has_empty_adjacent_province = false; + // We assume there are no duplicate province adjacencies, so each adjacency.get_to() is unique in the loop below + adjacent_nonempty_land_provinces.clear(); + for (const std::reference_wrapper adjacency_wrapper : get_adjacencies()) { + ProvinceInstance const& adjacency = adjacency_wrapper.get(); + if (adjacency.is_empty()) { + has_empty_adjacent_province = true; + } else if (!adjacency.province_definition.is_water()) { + adjacent_nonempty_land_provinces.emplace_back(adjacency); + } } } @@ -326,23 +356,8 @@ bool ProvinceInstance::convert_rgo_worker_pops_to_equivalent( return is_valid_operation; } -void ProvinceInstance::update_gamestate(InstanceManager const& instance_manager) { - has_empty_adjacent_province = false; - // We assume there are no duplicate province adjacencies, so each adjacency.get_to() is unique in the loop below - adjacent_nonempty_land_provinces.clear(); - - MapInstance const& map_instance = instance_manager.get_map_instance(); - for (ProvinceDefinition::adjacency_t const& adjacency : province_definition.get_adjacencies()) { - ProvinceDefinition const& adjacent_to_definition = adjacency.get_to(); - ProvinceInstance const& adjacent_to_instance = map_instance.get_province_instance_by_definition(adjacent_to_definition); - - if (adjacent_to_instance.is_empty()) { - has_empty_adjacent_province = true; - } else if (!adjacent_to_definition.is_water()) { - adjacent_nonempty_land_provinces.emplace_back(adjacent_to_instance); - } - } - +void ProvinceInstance::update_gamestate(const Date today, MilitaryDefines const& military_defines) { + update_adjecencies(); land_regiment_count = 0; for (ArmyInstance const& army : armies) { land_regiment_count += army.get_unit_count(); @@ -357,12 +372,10 @@ void ProvinceInstance::update_gamestate(InstanceManager const& instance_manager) occupation_duration = 0; } - const Date today = instance_manager.get_today(); - for (BuildingInstance& building : buildings) { building.update_gamestate(today); } - _update_pops(instance_manager.definition_manager.get_define_manager().get_military_defines()); + _update_pops(military_defines); } void ProvinceInstance::province_tick( @@ -498,6 +511,7 @@ bool ProvinceInstance::apply_history_to_province(ProvinceHistoryEntry const& ent void ProvinceInstance::initialise_for_new_game( const Date today, + MapInstance const& map_instance, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, TypedSpan reusable_goods_mask, @@ -506,6 +520,12 @@ void ProvinceInstance::initialise_for_new_game( VECTORS_FOR_PROVINCE_TICK > reusable_vectors ) { + for (ProvinceDefinition::adjacency_t const& adjacency : province_definition.get_adjacencies()) { + ProvinceDefinition const& adjacent_to_definition = adjacency.get_to(); + ProvinceInstance const& adjacent_to_instance = map_instance.get_province_instance_by_definition(adjacent_to_definition); + adjacencies.emplace_back(adjacent_to_instance); + } + update_adjecencies(); initialise_rgo(); province_tick( today, diff --git a/src/openvic-simulation/map/ProvinceInstance.hpp b/src/openvic-simulation/map/ProvinceInstance.hpp index 7e6038a60..8cb248c2c 100644 --- a/src/openvic-simulation/map/ProvinceInstance.hpp +++ b/src/openvic-simulation/map/ProvinceInstance.hpp @@ -95,6 +95,7 @@ namespace OpenVic { bool PROPERTY_RW(connected_to_capital, false); bool PROPERTY_RW(is_overseas, false); bool PROPERTY(has_empty_adjacent_province, false); + memory::vector> SPAN_PROPERTY(adjacencies); memory::vector> SPAN_PROPERTY(adjacent_nonempty_land_provinces); Crime const* PROPERTY_RW(crime, nullptr); ResourceGatheringOperation PROPERTY(rgo); @@ -123,6 +124,7 @@ namespace OpenVic { ProductionType const& production_type ); void initialise_rgo(); + void update_adjecencies(); memory::FixedVector< memory::vector>, @@ -188,8 +190,8 @@ namespace OpenVic { PopDeps const& pop_deps ); size_t get_pop_count() const; + void update_modifier_sum(const Date today, StaticModifierCache const& static_modifier_cache); - void update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache); fixed_point_t get_modifier_effect_value(ModifierEffect const& effect) const; void for_each_contributing_modifier(ModifierEffect const& effect, ContributingModifierCallback auto callback) const { @@ -204,7 +206,7 @@ namespace OpenVic { get_owner_modifier_sum().for_each_contributing_modifier(effect, std::move(callback)); } } - void update_gamestate(InstanceManager const& instance_manager); + void update_gamestate(const Date today, MilitaryDefines const& military_defines); static constexpr size_t VECTORS_FOR_PROVINCE_TICK = std::max( ResourceGatheringOperation::VECTORS_FOR_RGO_TICK, Pop::VECTORS_FOR_POP_TICK @@ -221,6 +223,7 @@ namespace OpenVic { ); void initialise_for_new_game( const Date today, + MapInstance const& map_instance, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, TypedSpan reusable_goods_mask, diff --git a/src/openvic-simulation/map/TerrainType.cpp b/src/openvic-simulation/map/TerrainType.cpp index 329a40ffa..8a7988c87 100644 --- a/src/openvic-simulation/map/TerrainType.cpp +++ b/src/openvic-simulation/map/TerrainType.cpp @@ -42,8 +42,10 @@ TerrainTypeMapping::TerrainTypeMapping( bool TerrainTypeManager::generate_modifiers(ModifierManager& modifier_manager) const { using enum ModifierEffect::format_t; - memory::FixedVector& unit_terrain_effects = - modifier_manager.modifier_effect_cache.unit_terrain_effects; + memory::FixedVector< + ModifierEffectCache::unit_terrain_effects_t, + terrain_type_index_t + >& unit_terrain_effects = modifier_manager.modifier_effect_cache.unit_terrain_effects; unit_terrain_effects = std::move( decltype(ModifierEffectCache::unit_terrain_effects) { diff --git a/src/openvic-simulation/military/Deployment.cpp b/src/openvic-simulation/military/Deployment.cpp index dfeba572d..1e91aa3ca 100644 --- a/src/openvic-simulation/military/Deployment.cpp +++ b/src/openvic-simulation/military/Deployment.cpp @@ -64,8 +64,10 @@ bool DeploymentManager::load_oob_file( static constexpr std::string_view oob_directory = "history/units/"; - const fs::path lookedup_path = - dataloader.lookup_file(append_string_views(oob_directory, history_path), false); + const fs::path lookedup_path = dataloader.lookup_file( + append_string_views(oob_directory, history_path), + false + ); if (lookedup_path.empty()) { missing_oob_files.emplace(history_path); diff --git a/src/openvic-simulation/military/LeaderTrait.cpp b/src/openvic-simulation/military/LeaderTrait.cpp index 972fd6131..9bff5c2e5 100644 --- a/src/openvic-simulation/military/LeaderTrait.cpp +++ b/src/openvic-simulation/military/LeaderTrait.cpp @@ -115,10 +115,10 @@ bool LeaderTraitManager::load_leader_traits_file(ModifierManager const& modifier using enum LeaderTrait::trait_type_t; - ret &= - expect_dictionary_keys("personality", ONE_EXACTLY, trait_callback(PERSONALITY), "background", ONE_EXACTLY, trait_callback(BACKGROUND))( - root - ); + ret &= expect_dictionary_keys( + "personality", ONE_EXACTLY, trait_callback(PERSONALITY), + "background", ONE_EXACTLY, trait_callback(BACKGROUND) + )(root); lock_leader_traits(); diff --git a/src/openvic-simulation/military/UnitInstanceGroup.cpp b/src/openvic-simulation/military/UnitInstanceGroup.cpp index 08e336d85..f4fb7bf4f 100644 --- a/src/openvic-simulation/military/UnitInstanceGroup.cpp +++ b/src/openvic-simulation/military/UnitInstanceGroup.cpp @@ -564,8 +564,8 @@ bool UnitInstanceManager::create_leader( } // TODO - make starting prestige a random proportion of the maximum random prestige - const fixed_point_t starting_prestige = - military_defines.get_leader_max_random_prestige() * static_cast(item_selection_counter++ % 11) / 10; + const fixed_point_t starting_prestige = military_defines.get_leader_max_random_prestige() + * static_cast(item_selection_counter++ % 11) / 10; generate_leader(country, LeaderBase{ name, diff --git a/src/openvic-simulation/military/UnitType.cpp b/src/openvic-simulation/military/UnitType.cpp index 1225cc763..ba16ce6cb 100644 --- a/src/openvic-simulation/military/UnitType.cpp +++ b/src/openvic-simulation/military/UnitType.cpp @@ -384,8 +384,10 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons generate_stat_modifiers(modifier_manager.modifier_effect_cache.army_base_effects, "army_base"); - memory::FixedVector& regiment_type_effects = - modifier_manager.modifier_effect_cache.regiment_type_effects; + memory::FixedVector< + ModifierEffectCache::regiment_type_effects_t, + regiment_type_index_t + >& regiment_type_effects = modifier_manager.modifier_effect_cache.regiment_type_effects; regiment_type_effects = std::move( decltype(ModifierEffectCache::regiment_type_effects) { @@ -400,8 +402,10 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons generate_stat_modifiers(modifier_manager.modifier_effect_cache.navy_base_effects, "navy_base"); - memory::FixedVector& ship_type_effects = - modifier_manager.modifier_effect_cache.ship_type_effects; + memory::FixedVector< + ModifierEffectCache::ship_type_effects_t, + ship_type_index_t + >& ship_type_effects = modifier_manager.modifier_effect_cache.ship_type_effects; ship_type_effects = std::move( decltype(ModifierEffectCache::ship_type_effects) { diff --git a/src/openvic-simulation/modifier/ModifierSum.cpp b/src/openvic-simulation/modifier/ModifierSum.cpp index 1c4daba47..442a4e8e7 100644 --- a/src/openvic-simulation/modifier/ModifierSum.cpp +++ b/src/openvic-simulation/modifier/ModifierSum.cpp @@ -1,17 +1,20 @@ #include "ModifierSum.hpp" -#include "openvic-simulation/modifier/Modifier.hpp" +#include -#include "openvic-simulation/country/CountryInstance.hpp" -#include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/country/CountryInstance.hpp" // IWYU pragma: keep for modifier_source_t +#include "openvic-simulation/map/ProvinceInstance.hpp" // IWYU pragma: keep for modifier_source_t +#include "openvic-simulation/modifier/Modifier.hpp" using namespace OpenVic; std::string_view modifier_entry_t::source_to_string(modifier_source_t const& source) { return std::visit( [](has_get_identifier auto const* has_identifier) -> std::string_view { - return has_identifier->get_identifier(); + return has_identifier == nullptr + ? "" + : has_identifier->get_identifier(); }, source ); @@ -20,7 +23,9 @@ std::string_view modifier_entry_t::source_to_string(modifier_source_t const& sou memory::string modifier_entry_t::to_string() const { return memory::fmt::format( "[{}, {}, {}, {}]", - modifier, multiplier, source_to_string(source), + ovfmt::validate(modifier), + multiplier, + source_to_string(source), ModifierEffect::target_to_string(excluded_targets) ); } @@ -30,10 +35,6 @@ void ModifierSum::clear() { value_sum.clear(); } -bool ModifierSum::empty() { - return modifiers.empty(); -} - fixed_point_t ModifierSum::get_modifier_effect_value(ModifierEffect const& effect, bool* effect_found) const { return value_sum.get_effect(effect, effect_found); } @@ -55,21 +56,10 @@ void ModifierSum::add_modifier( modifier_entry_t::source_or_null_fallback(source, this_source), excluded_targets | this_excluded_targets ); - value_sum.multiply_add_exclude_targets(new_entry.modifier, new_entry.multiplier, new_entry.excluded_targets); - } -} - -void ModifierSum::add_modifier_sum(ModifierSum const& modifier_sum) { - reserve_more(modifiers, modifier_sum.modifiers.size()); - - // We could test that excluded_targets != ALL_TARGETS, but in practice it's always - // called with an explcit/hardcoded value and so won't ever exclude everything. - for (modifier_entry_t const& modifier_entry : modifier_sum.modifiers) { - add_modifier( - modifier_entry.modifier, - modifier_entry.multiplier, - modifier_entry.source, - modifier_entry.excluded_targets + value_sum.multiply_add_exclude_targets( + *new_entry.modifier, + new_entry.multiplier, + new_entry.excluded_targets ); } } diff --git a/src/openvic-simulation/modifier/ModifierSum.hpp b/src/openvic-simulation/modifier/ModifierSum.hpp index 72b2459c2..4be964469 100644 --- a/src/openvic-simulation/modifier/ModifierSum.hpp +++ b/src/openvic-simulation/modifier/ModifierSum.hpp @@ -1,8 +1,11 @@ #pragma once +#include #include +#include "openvic-simulation/core/BulkInsertWrapper.hpp" #include "openvic-simulation/core/memory/Vector.hpp" +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/modifier/ModifierValue.hpp" #include "openvic-simulation/modifier/Modifier.hpp" @@ -31,23 +34,40 @@ namespace OpenVic { ); } - Modifier const& modifier; + Modifier const* modifier; fixed_point_t multiplier; modifier_source_t source; ModifierEffect::target_t excluded_targets; + //invalid but required fore resizing to work + constexpr modifier_entry_t() + : modifier {nullptr}, + multiplier {fixed_point_t::_0}, + source {static_cast>(nullptr)}, + excluded_targets {} {} + + // constexpr modifier_entry_t( Modifier const& new_modifier, fixed_point_t new_multiplier, modifier_source_t const& new_source, ModifierEffect::target_t new_excluded_targets - ) : modifier { new_modifier }, + ) : modifier { &new_modifier }, multiplier { new_multiplier }, source { new_source }, excluded_targets { new_excluded_targets } {} + constexpr bool is_valid() const { + return multiplier != fixed_point_t::_0 + && modifier != nullptr + && ( + get_source_country() != nullptr + || get_source_province() != nullptr + ); + } + constexpr bool operator==(modifier_entry_t const& other) const { - return &modifier == &other.modifier + return modifier == other.modifier && multiplier == other.multiplier && source == other.source && excluded_targets == other.excluded_targets; @@ -67,14 +87,18 @@ namespace OpenVic { constexpr fixed_point_t get_modifier_effect_value( ModifierEffect const& effect, bool* effect_found = nullptr ) const { + if (!is_valid()) { + return fixed_point_t::_0; + } + if (ModifierEffect::excludes_targets(effect.targets, excluded_targets)) { - return modifier.get_effect(effect, effect_found) * multiplier; + return modifier->get_effect(effect, effect_found) * multiplier; } if (effect_found != nullptr) { *effect_found = false; } - return 0; + return fixed_point_t::_0; } }; @@ -94,18 +118,22 @@ namespace OpenVic { // Targets to be excluded from all modifiers added to the sum, combined with any explicit exclusions. ModifierEffect::target_t PROPERTY_RW(this_excluded_targets, ModifierEffect::target_t::NO_TARGETS); - memory::vector SPAN_PROPERTY(modifiers); + bulk_insert_wrapper< + memory::vector + > SPAN_PROPERTY(modifiers); ModifierValue PROPERTY(value_sum); public: ModifierSum() {}; - ModifierSum(ModifierSum const&) = default; ModifierSum(ModifierSum&&) = default; - ModifierSum& operator=(ModifierSum const&) = default; - ModifierSum& operator=(ModifierSum&&) = default; + constexpr std::size_t size() const { + return modifiers.size(); + } + constexpr bool empty() const { + return modifiers.empty(); + } void clear(); - bool empty(); fixed_point_t get_modifier_effect_value(ModifierEffect const& effect, bool* effect_found = nullptr) const; bool has_modifier_effect(ModifierEffect const& effect) const; @@ -116,17 +144,34 @@ namespace OpenVic { modifier_entry_t::modifier_source_t const& source = {}, ModifierEffect::target_t excluded_targets = ModifierEffect::target_t::NO_TARGETS ); - // Reserves space for the number of modifier entries in the given sum and adds each of them using add_modifier + + constexpr void make_room_for(ModifierSum const& modifier_sum) { + modifiers.make_room_for(modifier_sum.size()); + } + + // Inserts modifiers directly via std::ranges::copy. Requires resizing beforehand! // with the modifier entries' attributes as arguments. This means non-null sources are preserved (null ones are // replaced with this_source, but in practice the other sum should've set them itself already) and exclusion targets // are combined with this_excluded_targets. - void add_modifier_sum(ModifierSum const& modifier_sum); + constexpr void add_modifier_sum(ModifierSum const& modifier_sum) { + // We could test that excluded_targets != ALL_TARGETS, but in practice it's always + // called with an explcit/hardcoded value and so won't ever exclude everything. + modifiers.append_range(modifier_sum.modifiers); + + for (modifier_entry_t const& m : modifier_sum.get_modifiers()) { + value_sum.multiply_add_exclude_targets( + *m.modifier, + m.multiplier, + m.excluded_targets + ); + } + } // TODO - help calculate value_sum[effect]? Early return if lookup in value_sum fails? constexpr void for_each_contributing_modifier( ModifierEffect const& effect, ContributingModifierCallback auto callback ) const { - for (modifier_entry_t const& modifier_entry : modifiers) { + for (modifier_entry_t const& modifier_entry : get_modifiers()) { const fixed_point_t contribution = modifier_entry.get_modifier_effect_value(effect); if (contribution != 0) { diff --git a/src/openvic-simulation/pathfinding/AStarPathing.cpp b/src/openvic-simulation/pathfinding/AStarPathing.cpp index 062966390..1c84861d2 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.cpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.cpp @@ -40,9 +40,13 @@ bool AStarPathing::_solve(search_iterator begin_point, search_iterator end_point search_iterator p = open_list.front(); // The currently processed point. // Find point closer to end_point, or same distance to end_point but closer to begin_point. - if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // - last_closest_point.value().g_score > p.value().g_score)) { + if (last_closest_point == search.end() + || last_closest_point.value().abs_f_score > p.value().abs_f_score + || ( + last_closest_point.value().abs_f_score >= p.value().abs_f_score + && last_closest_point.value().g_score > p.value().g_score + ) + ) { last_closest_point = p; } diff --git a/src/openvic-simulation/pathfinding/FringePathing.cpp b/src/openvic-simulation/pathfinding/FringePathing.cpp index 67c9e1abc..280a67370 100644 --- a/src/openvic-simulation/pathfinding/FringePathing.cpp +++ b/src/openvic-simulation/pathfinding/FringePathing.cpp @@ -56,9 +56,13 @@ bool FringePathing::_solve(search_iterator begin_point, search_iterator end_poin } // Find point closer to end_point, or same distance to end_point but closer to begin_point. - if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // - last_closest_point.value().g_score > p.value().g_score)) { + if (last_closest_point == search.end() + || last_closest_point.value().abs_f_score > p.value().abs_f_score + || ( + last_closest_point.value().abs_f_score >= p.value().abs_f_score + && last_closest_point.value().g_score > p.value().g_score + ) + ) { last_closest_point = p; } diff --git a/src/openvic-simulation/pathfinding/PathingBase.hpp b/src/openvic-simulation/pathfinding/PathingBase.hpp index ca7b73f34..6f3f4f44e 100644 --- a/src/openvic-simulation/pathfinding/PathingBase.hpp +++ b/src/openvic-simulation/pathfinding/PathingBase.hpp @@ -21,12 +21,15 @@ namespace OpenVic { using search_key_type = KeyT; using search_value_type = ValueT; using search_pair_type = std::pair; - using search_allocator_type = - foonathan::memory::std_allocator>; + using search_allocator_type = foonathan::memory::std_allocator< + search_pair_type, + memory::tracker + >; using search_container_type = std::vector; using search_map_type = tsl::ordered_map< search_key_type, search_value_type, // - std::hash, std::equal_to, search_allocator_type, search_container_type>; + std::hash, std::equal_to, search_allocator_type, search_container_type + >; using search_iterator = search_map_type::iterator; using search_const_iterator = search_map_type::const_iterator; diff --git a/src/openvic-simulation/pathfinding/PointMap.hpp b/src/openvic-simulation/pathfinding/PointMap.hpp index b4fee3665..aa0000e6a 100644 --- a/src/openvic-simulation/pathfinding/PointMap.hpp +++ b/src/openvic-simulation/pathfinding/PointMap.hpp @@ -22,12 +22,15 @@ namespace OpenVic { using points_key_type = uint64_t; using points_value_type = Point; using points_pair_type = std::pair; - using points_allocator_type = - foonathan::memory::std_allocator>; + using points_allocator_type = foonathan::memory::std_allocator< + points_pair_type, + memory::tracker + >; using points_container_type = std::vector; using points_map_type = tsl::ordered_map< points_key_type, points_value_type, // - std::hash, std::equal_to, points_allocator_type, points_container_type>; + std::hash, std::equal_to, points_allocator_type, points_container_type + >; using points_iterator = points_map_type::iterator; using points_const_iterator = points_map_type::const_iterator; @@ -63,15 +66,17 @@ namespace OpenVic { struct SegmentHash { inline constexpr std::size_t operator()(Segment const& segment) const { - return hash_murmur3(hash_murmur3(segment.key.first) << 32) | - hash_murmur3(segment.key.second); + return hash_murmur3(hash_murmur3(segment.key.first) << 32) + | hash_murmur3(segment.key.second); } }; using segments_type = Segment; using segments_hash_type = SegmentHash; - using segments_allocator_type = - foonathan::memory::std_allocator>; + using segments_allocator_type = foonathan::memory::std_allocator< + segments_type, + memory::tracker + >; using segments_container_type = std::vector; using segments_set_type = tsl::ordered_set< segments_type, segments_hash_type, std::equal_to, segments_allocator_type, segments_container_type>; @@ -80,13 +85,16 @@ namespace OpenVic { struct Point { using neighbor_point_id_type = points_key_type; - using neighbors_allocator_type = - foonathan::memory::std_allocator>; + using neighbors_allocator_type = foonathan::memory::std_allocator< + neighbor_point_id_type, + memory::tracker + >; using neighbors_container_type = std::vector; using neighbors_type = tsl::ordered_set< neighbor_point_id_type, // std::hash, std::equal_to, neighbors_allocator_type, - neighbors_container_type>; + neighbors_container_type + >; using neighbors_iterator = neighbors_type::iterator; using neighbors_const_iterator = neighbors_type::const_iterator; diff --git a/src/openvic-simulation/population/Culture.cpp b/src/openvic-simulation/population/Culture.cpp index 3880ee4a0..7c53d4330 100644 --- a/src/openvic-simulation/population/Culture.cpp +++ b/src/openvic-simulation/population/Culture.cpp @@ -271,9 +271,16 @@ bool CultureManager::find_cultural_leader_pictures(Dataloader const& dataloader) unit_branch_t branch, leader_count_t& leader_count ) -> void { while ( - leader_count < std::numeric_limits::max() && - !dataloader.lookup_file( - make_leader_picture_path(make_leader_picture_name(cultural_type, branch, leader_count)), false + leader_count < std::numeric_limits::max() + && !dataloader.lookup_file( + make_leader_picture_path( + make_leader_picture_name( + cultural_type, + branch, + leader_count + ) + ), + false ).empty() ) { leader_count++; diff --git a/src/openvic-simulation/population/Pop.cpp b/src/openvic-simulation/population/Pop.cpp index d49673f7e..9fb8be96a 100644 --- a/src/openvic-simulation/population/Pop.cpp +++ b/src/openvic-simulation/population/Pop.cpp @@ -98,8 +98,12 @@ void Pop::setup_pop_test_values(TypedSpan reforms) num_migrated_external = test_size(1); num_migrated_colonial = test_size(2); - total_change = - num_grown + num_promoted + num_demoted + num_migrated_internal + num_migrated_external + num_migrated_colonial; + total_change = num_grown + + num_promoted + + num_demoted + + num_migrated_internal + + num_migrated_external + + num_migrated_colonial; /* Generates a number between 0 and max (inclusive) and sets map[&key] to it if it's at least min. */ static auto fill_span_with_test_weights = [](std::span span, int32_t min, int32_t max) -> void { @@ -242,9 +246,12 @@ void Pop::update_gamestate( consciousness = std::clamp(consciousness, MIN_CONSCIOUSNESS, MAX_CONSCIOUSNESS); literacy = std::clamp(literacy, MIN_LITERACY, MAX_LITERACY); - if ( - size < military_defines.get_min_pop_size_for_regiment() || owner == nullptr || - !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status) + if (size < military_defines.get_min_pop_size_for_regiment() + || owner == nullptr + || !is_culture_status_allowed( + owner->get_allowed_regiment_cultures(), + culture_status + ) ) { max_supported_regiments = 0; } else { diff --git a/src/openvic-simulation/population/PopManager.cpp b/src/openvic-simulation/population/PopManager.cpp index 5210c84ef..b2e150f4b 100644 --- a/src/openvic-simulation/population/PopManager.cpp +++ b/src/openvic-simulation/population/PopManager.cpp @@ -507,8 +507,10 @@ bool PopManager::generate_modifiers(ModifierManager& modifier_manager) const { static constexpr bool HAS_NO_EFFECT = true; - memory::FixedVector& strata_effects = - modifier_manager.modifier_effect_cache.strata_effects; + memory::FixedVector< + ModifierEffectCache::strata_effects_t, + strata_index_t + >& strata_effects = modifier_manager.modifier_effect_cache.strata_effects; strata_effects = std::move( decltype(ModifierEffectCache::strata_effects) { diff --git a/src/openvic-simulation/research/Technology.cpp b/src/openvic-simulation/research/Technology.cpp index 628d4894a..11a855184 100644 --- a/src/openvic-simulation/research/Technology.cpp +++ b/src/openvic-simulation/research/Technology.cpp @@ -247,8 +247,10 @@ bool TechnologyManager::generate_modifiers(ModifierManager& modifier_manager) co using enum ModifierEffect::format_t; using enum ModifierEffect::target_t; - memory::FixedVector& research_bonus_effects = - modifier_manager.modifier_effect_cache.research_bonus_effects; + memory::FixedVector< + ModifierEffect const*, + technology_folder_index_t + >& research_bonus_effects = modifier_manager.modifier_effect_cache.research_bonus_effects; research_bonus_effects = std::move( decltype(ModifierEffectCache::research_bonus_effects) { diff --git a/src/openvic-simulation/scripts/ConditionalWeight.cpp b/src/openvic-simulation/scripts/ConditionalWeight.cpp index c5a72da35..2b7409f10 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.cpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.cpp @@ -130,9 +130,9 @@ bool ConditionalWeight::parse_scripts(DefinitionManager const& definition_ template bool ConditionalWeight::operator==(ConditionalWeight const& other) const { - return initial_scope == other.initial_scope && - this_scope == other.this_scope && - from_scope == other.from_scope; + return initial_scope == other.initial_scope + && this_scope == other.this_scope + && from_scope == other.from_scope; } template struct OpenVic::ConditionalWeight; diff --git a/src/openvic-simulation/types/Colour.hpp b/src/openvic-simulation/types/Colour.hpp index beb4a224c..d77b3d4a2 100644 --- a/src/openvic-simulation/types/Colour.hpp +++ b/src/openvic-simulation/types/Colour.hpp @@ -362,8 +362,9 @@ namespace OpenVic { template requires( - _ColourTraits::has_alpha && std::same_as && - std::same_as + _ColourTraits::has_alpha + && std::same_as + && std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t(basic_colour_t const& colour) requires(colour_traits::has_alpha) @@ -371,8 +372,9 @@ namespace OpenVic { template requires( - !_ColourTraits::has_alpha && std::same_as && - std::same_as + !_ColourTraits::has_alpha + && std::same_as + && std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t( basic_colour_t const& colour, value_type a = max_value @@ -382,8 +384,8 @@ namespace OpenVic { template requires( - std::same_as && - std::same_as + std::same_as + && std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t(basic_colour_t const& colour) requires(!colour_traits::has_alpha) @@ -588,8 +590,10 @@ namespace OpenVic { constexpr double GREEN_MULTIPLIER = 0.7151522; constexpr double BLUE_MULTIPLIER = 0.0721750; - double luminance = std::pow(red / max_value, POWER) * RED_MULTIPLIER + - std::pow(green / max_value, POWER) * GREEN_MULTIPLIER + std::pow(blue, POWER) * BLUE_MULTIPLIER; + double luminance = std::pow(red / max_value, POWER) * RED_MULTIPLIER + + std::pow(green / max_value, POWER) + * GREEN_MULTIPLIER + std::pow(blue, POWER) + * BLUE_MULTIPLIER; return luminance >= LUMINANCE_FLIP ? basic_colour_t::from_floats(0, 0, 0) : basic_colour_t::from_floats(1, 1, 1); } diff --git a/src/openvic-simulation/types/CowVector.hpp b/src/openvic-simulation/types/CowVector.hpp index 38b9a62fd..94480ae48 100644 --- a/src/openvic-simulation/types/CowVector.hpp +++ b/src/openvic-simulation/types/CowVector.hpp @@ -97,8 +97,11 @@ namespace OpenVic { swap(other, *this); } else if (!other.empty()) { _data = _allocate_payload(other.size()); - _data->array_end = - uninitialized_move(other._data->array, other._data->array_end, _data->array, alloc); + _data->array_end = uninitialized_move( + other._data->array, + other._data->array_end, + _data->array, alloc + ); destroy(_data->array, _data->array_end, alloc); _data->array_end = _data->array; } @@ -128,8 +131,9 @@ namespace OpenVic { cow_vector tmp = std::move(x); writer& tmp_writer = *reinterpret_cast(&tmp); - if constexpr (allocator_traits::propagate_on_container_move_assignment::value || - allocator_traits::is_always_equal::value) { + if constexpr (allocator_traits::propagate_on_container_move_assignment::value + || allocator_traits::is_always_equal::value + ) { self_writer.swap(tmp_writer); } else if (alloc == x.alloc) { self_writer.swap(tmp_writer); @@ -449,8 +453,12 @@ namespace OpenVic { if constexpr (move_insertable_allocator) { _relocate(_data->array, _data->array_end, new_data->array, alloc); } else { - new_data->array_end = - uninitialized_move(_data->array, _data->array_end, new_data->array, alloc); + new_data->array_end = uninitialized_move( + _data->array, + _data->array_end, + new_data->array, + alloc + ); destroy(_data->array, _data->array_end, alloc); } _deallocate_payload(_data); @@ -1102,8 +1110,11 @@ namespace OpenVic { }; template - inline constexpr cow_vector::size_type cow_vector::payload::content_size = - std::max(1ul, (sizeof(payload) - sizeof(array)) / sizeof(T)); + inline constexpr cow_vector::size_type cow_vector::payload::content_size + = std::max( + 1ul, + (sizeof(payload) - sizeof(array)) / sizeof(T) + ); template [[nodiscard]] inline bool operator==(cow_vector const& x, cow_vector const& y) { diff --git a/src/openvic-simulation/types/Date.hpp b/src/openvic-simulation/types/Date.hpp index 93f4ef818..15ab0c2ff 100644 --- a/src/openvic-simulation/types/Date.hpp +++ b/src/openvic-simulation/types/Date.hpp @@ -114,8 +114,9 @@ namespace OpenVic { using month_t = uint8_t; using day_t = uint8_t; - static constexpr std::array DAYS_IN_MONTH = - std::to_array({ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }); + static constexpr std::array DAYS_IN_MONTH = std::to_array( + { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } + ); static constexpr Timespan::day_t MONTHS_IN_YEAR = DAYS_IN_MONTH.size(); static constexpr Timespan::day_t MAX_DAYS_IN_MONTH = *ranges::max_element(DAYS_IN_MONTH); @@ -348,9 +349,11 @@ namespace OpenVic { OV_SPEED_INLINE constexpr stack_string to_array(bool pad_year = false, bool pad_month = true, bool pad_day = true) const; struct stack_string final : StackString< - fmt::detail::count_digits(uint64_t(std::numeric_limits::max())) + - fmt::detail::count_digits(uint64_t(MONTHS_IN_YEAR)) + - fmt::detail::count_digits(uint64_t(MAX_DAYS_IN_MONTH)) + 4> { + fmt::detail::count_digits(uint64_t(std::numeric_limits::max())) + + fmt::detail::count_digits(uint64_t(MONTHS_IN_YEAR)) + + fmt::detail::count_digits(uint64_t(MAX_DAYS_IN_MONTH)) + + 4 + > { protected: using StackString::StackString; friend OV_SPEED_INLINE constexpr stack_string Date::to_array(bool pad_year, bool pad_month, bool pad_day) const; @@ -512,8 +515,9 @@ namespace OpenVic { Date date = from_string(str, from_chars); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && - from_chars->ptr == from_chars->type_first, + from_chars->ec == std::errc::invalid_argument + && from_chars->type == errc_type::year + && from_chars->ptr == from_chars->type_first, date, "Could not parse year value." ); OV_ERR_FAIL_COND_V_MSG( @@ -525,13 +529,15 @@ namespace OpenVic { "Only year value could be found." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && - from_chars->ptr != from_chars->type_first, + from_chars->ec == std::errc::invalid_argument + && from_chars->type == errc_type::year + && from_chars->ptr != from_chars->type_first, date, memory::fmt::format("Year value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && - from_chars->ptr == from_chars->type_first, + from_chars->ec == std::errc::invalid_argument + && from_chars->type == errc_type::month + && from_chars->ptr == from_chars->type_first, date, "Could not parse month value." ); OV_ERR_FAIL_COND_V_MSG( @@ -539,8 +545,9 @@ namespace OpenVic { "Month value cannot be 0." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::month && - from_chars->ptr == from_chars->type_first, + from_chars->ec == std::errc::value_too_large + && from_chars->type == errc_type::month + && from_chars->ptr == from_chars->type_first, date, memory::fmt::format("Month value cannot be larger than {}.", MONTHS_IN_YEAR) ); OV_ERR_FAIL_COND_V_MSG( @@ -548,21 +555,24 @@ namespace OpenVic { "Only year and month value could be found." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && - from_chars->ptr != from_chars->type_first, + from_chars->ec == std::errc::invalid_argument + && from_chars->type == errc_type::month + && from_chars->ptr != from_chars->type_first, date, memory::fmt::format("Month value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::day && - from_chars->ptr == from_chars->type_first, + from_chars->ec == std::errc::invalid_argument + && from_chars->type == errc_type::day + && from_chars->ptr == from_chars->type_first, date, "Could not parse day value." ); OV_ERR_FAIL_COND_V_MSG( from_chars->ec == std::errc::not_supported && from_chars->type == errc_type::day, date, "Day value cannot be 0." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::day && - from_chars->ptr == from_chars->type_first, + from_chars->ec == std::errc::value_too_large + && from_chars->type == errc_type::day + && from_chars->ptr == from_chars->type_first, date, memory::fmt::format("Day value cannot be larger than {} for {}.", DAYS_IN_MONTH[date.get_month() - 1], date.get_month()) ); @@ -601,8 +611,13 @@ namespace OpenVic { OV_SPEED_INLINE constexpr Date::stack_string Date::to_array(bool pad_year, bool pad_month, bool pad_day) const { stack_string str {}; - std::to_chars_result result = - to_chars(str._array.data(), str._array.data() + str._array.size(), pad_year, pad_month, pad_day); + std::to_chars_result result = to_chars( + str._array.data(), + str._array.data() + str._array.size(), + pad_year, + pad_month, + pad_day + ); str._string_size = result.ptr - str.data(); return str; } diff --git a/src/openvic-simulation/types/IdentifierRegistry.hpp b/src/openvic-simulation/types/IdentifierRegistry.hpp index 811fc6ecb..3a5b7145f 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.hpp +++ b/src/openvic-simulation/types/IdentifierRegistry.hpp @@ -113,9 +113,8 @@ namespace OpenVic { /* Registry Storage Info - how items are stored and indexed, and item-index conversion functions. */ template typename StorageInfo, typename Item> - concept RegistryStorageInfo = - std::same_as::storage_type::value_type, Item> && - requires( + concept RegistryStorageInfo = std::same_as::storage_type::value_type, Item> + && requires( typename StorageInfo::storage_type& items, typename StorageInfo::storage_type const& const_items, typename StorageInfo::index_type index ) { @@ -161,8 +160,8 @@ namespace OpenVic { string_map_case Case = StringMapCaseSensitive /* Identifier map parameters */ > requires( - RegistryItemInfo<_ItemInfo, typename ValueInfo::internal_value_type> && - RegistryStorageInfo<_StorageInfo, typename _ItemInfo::item_type> + RegistryItemInfo<_ItemInfo, typename ValueInfo::internal_value_type> + && RegistryStorageInfo<_StorageInfo, typename _ItemInfo::item_type> ) class UniqueKeyRegistry { public: @@ -582,8 +581,11 @@ namespace OpenVic { has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, string_map_case Case = StringMapCaseSensitive > - using IdentifierPointerRegistry = - ValueRegistry>, StorageInfo, Case>; + using IdentifierPointerRegistry = ValueRegistry< + RegistryValueInfoPointer>, + StorageInfo, + Case + >; template< has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, diff --git a/src/openvic-simulation/types/OrderedContainers.hpp b/src/openvic-simulation/types/OrderedContainers.hpp index a88e84720..0807a60d8 100644 --- a/src/openvic-simulation/types/OrderedContainers.hpp +++ b/src/openvic-simulation/types/OrderedContainers.hpp @@ -71,16 +71,30 @@ namespace OpenVic { class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, class Allocator = foonathan::memory::std_allocator, memory::tracker>> - using vector_ordered_map = - tsl::ordered_map, Allocator>, IndexType>; + using vector_ordered_map = tsl::ordered_map< + Key, + T, + Hash, + KeyEqual, + Allocator, + std::vector, Allocator>, + IndexType + >; // Useful for stable memory addresses (so long as you don't remove or insert values) template< class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, class Allocator = foonathan::memory::std_allocator, memory::tracker>> - using deque_ordered_map = - tsl::ordered_map, Allocator>, IndexType>; + using deque_ordered_map = tsl::ordered_map< + Key, + T, + Hash, + KeyEqual, + Allocator, + OpenVic::utility::deque, Allocator>, + IndexType + >; template< class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, @@ -100,8 +114,14 @@ namespace OpenVic { class Key, class Hash = container_hash, class KeyEqual = default_equal_to, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, class Allocator = foonathan::memory::std_allocator>> - using deque_ordered_set = - tsl::ordered_set, IndexType>; + using deque_ordered_set = tsl::ordered_set< + Key, + Hash, + KeyEqual, + Allocator, + OpenVic::utility::deque, + IndexType + >; template< class Key, class Hash = container_hash, class KeyEqual = default_equal_to, @@ -182,8 +202,14 @@ namespace OpenVic { template< class Key, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, class Allocator = foonathan::memory::std_allocator>> - using case_insensitive_deque_ordered_set = - deque_ordered_set; + using case_insensitive_deque_ordered_set = deque_ordered_set< + Key, + case_insensitive_string_hash, + case_insensitive_string_equal, + RawAllocator, + IndexType, + Allocator + >; template< class Key, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, diff --git a/src/openvic-simulation/types/RingBuffer.hpp b/src/openvic-simulation/types/RingBuffer.hpp index dee68b6a0..3f7940edb 100644 --- a/src/openvic-simulation/types/RingBuffer.hpp +++ b/src/openvic-simulation/types/RingBuffer.hpp @@ -191,8 +191,8 @@ namespace OpenVic { } RingBuffer& operator=(RingBuffer&& other) noexcept( - allocator_traits::propagate_on_container_move_assignment::value || - std::is_nothrow_move_constructible::value + allocator_traits::propagate_on_container_move_assignment::value + || std::is_nothrow_move_constructible::value ) { if (allocator_traits::propagate_on_container_move_assignment::value || _allocator == other._allocator) { // We're either getting the other's allocator or they're already the same, diff --git a/src/openvic-simulation/types/Signal.hpp b/src/openvic-simulation/types/Signal.hpp index c7bbb7709..856de6c68 100644 --- a/src/openvic-simulation/types/Signal.hpp +++ b/src/openvic-simulation/types/Signal.hpp @@ -1057,8 +1057,8 @@ namespace OpenVic::_detail::signal { */ template requires( - (Callable || Callable || MemberFunctionPointer) && - function_traits::is_disconnectable + (Callable || Callable || MemberFunctionPointer) + && function_traits::is_disconnectable ) size_t disconnect(C const& c) { return disconnect_if([&](slot_ptr const& s) { diff --git a/src/openvic-simulation/utility/ThreadDeps.hpp b/src/openvic-simulation/utility/ThreadDeps.hpp new file mode 100644 index 000000000..49eb2bfd7 --- /dev/null +++ b/src/openvic-simulation/utility/ThreadDeps.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include "openvic-simulation/types/TypedIndices.hpp" + +namespace OpenVic { + struct GameRulesManager; + struct GoodInstanceManager; + struct MapInstance; + struct MilitaryDefines; + struct ModifierEffectCache; + struct PopsDefines; + struct ProductionTypeManager; + struct StaticModifierCache; + + struct ThreadDeps { + GameRulesManager const& game_rules_manager; + GoodInstanceManager const& good_instance_manager; + MapInstance const& map_instance; + MilitaryDefines const& military_defines; + ModifierEffectCache const& modifier_effect_cache; + PopsDefines const& pop_defines; + ProductionTypeManager const& production_type_manager; + StaticModifierCache const& static_modifier_cache; + country_index_t country_count; + good_index_t good_count; + strata_index_t strata_count; + }; +} \ No newline at end of file diff --git a/src/openvic-simulation/utility/ThreadPool.cpp b/src/openvic-simulation/utility/ThreadPool.cpp index 605185d35..2ed9f229e 100644 --- a/src/openvic-simulation/utility/ThreadPool.cpp +++ b/src/openvic-simulation/utility/ThreadPool.cpp @@ -1,4 +1,5 @@ #include "ThreadPool.hpp" +#include "ThreadDeps.hpp" #include #include @@ -10,6 +11,7 @@ #include "openvic-simulation/economy/GoodInstance.hpp" #include "openvic-simulation/economy/trading/GoodMarket.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" +#include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/TypedSpan.hpp" @@ -18,20 +20,13 @@ using namespace OpenVic; void ThreadPool::loop_until_cancelled( work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - const good_index_t good_count, - const strata_index_t strata_count, + const ThreadDeps deps, forwardable_span work_bundles ) { - memory::FixedVector reusable_goods_mask { good_count, {} }; + memory::FixedVector reusable_goods_mask { deps.good_count, {} }; - memory::FixedVector reusable_country_map_0 { country_index_t(country_keys.size()), fixed_point_t::_0 }; - memory::FixedVector reusable_country_map_1 { country_index_t(country_keys.size()), fixed_point_t::_0 }; + memory::FixedVector reusable_country_map_0 { deps.country_count, fixed_point_t::_0 }; + memory::FixedVector reusable_country_map_1 { deps.country_count, fixed_point_t::_0 }; static constexpr std::size_t VECTOR_COUNT = std::max( GoodMarket::VECTORS_FOR_EXECUTE_ORDERS, @@ -44,12 +39,12 @@ void ThreadPool::loop_until_cancelled( std::span, VECTOR_COUNT> reusable_vectors_span = std::span(reusable_vectors); memory::vector reusable_good_index_vector; PopValuesFromProvince reusable_pop_values { - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - production_type_manager, - pop_defines, - strata_count + deps.game_rules_manager, + deps.good_instance_manager, + deps.modifier_effect_cache, + deps.production_type_manager, + deps.pop_defines, + deps.strata_count }; while (!is_cancellation_requested) { @@ -70,11 +65,11 @@ void ThreadPool::loop_until_cancelled( work_type = work_t::NONE; } - switch (work_type_copy) { - case work_t::NONE: - break; - case work_t::GOOD_EXECUTE_ORDERS: - for (WorkBundle& work_bundle : work_bundles) { + for (WorkBundle& work_bundle : work_bundles) { + switch (work_type_copy) { + case work_t::NONE: + break; + case work_t::GOOD_EXECUTE_ORDERS: for (GoodMarket& good : work_bundle.goods_chunk) { good.execute_orders( reusable_country_map_0, @@ -82,10 +77,8 @@ void ThreadPool::loop_until_cancelled( reusable_vectors_span.first() ); } - } - break; - case work_t::PROVINCE_TICK: - for (WorkBundle& work_bundle : work_bundles) { + break; + case work_t::PROVINCE_TICK: for (ProvinceInstance& province : work_bundle.provinces_chunk) { province.province_tick( current_date, @@ -95,23 +88,20 @@ void ThreadPool::loop_until_cancelled( reusable_vectors_span.first() ); } - } - break; - case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: - for (WorkBundle& work_bundle : work_bundles) { + break; + case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: for (ProvinceInstance& province : work_bundle.provinces_chunk) { province.initialise_for_new_game( current_date, + deps.map_instance, reusable_pop_values, work_bundle.random_number_generator, reusable_goods_mask, reusable_vectors_span.first() ); } - } - break; - case work_t::COUNTRY_TICK_BEFORE_MAP: - for (WorkBundle& work_bundle : work_bundles) { + break; + case work_t::COUNTRY_TICK_BEFORE_MAP: for (CountryInstance& country : work_bundle.countries_chunk) { country.country_tick_before_map( reusable_goods_mask, @@ -119,15 +109,47 @@ void ThreadPool::loop_until_cancelled( reusable_good_index_vector ); } - } - break; - case work_t::COUNTRY_TICK_AFTER_MAP: - for (WorkBundle& work_bundle : work_bundles) { + break; + case work_t::COUNTRY_TICK_AFTER_MAP: for (CountryInstance& country : work_bundle.countries_chunk) { country.country_tick_after_map(current_date); } - } - break; + break; + case work_t::PROVINCE_UPDATE_GAMESTATE: + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.update_gamestate( + current_date, + deps.military_defines + ); + } + break; + case work_t::COUNTRY_UPDATE_GAMESTATE_AFTER_MAP: + for (CountryInstance& country : work_bundle.countries_chunk) { + country.update_gamestate_after_map(current_date); + } + break; + case work_t::PROVINCE_UPDATE_MODIFIER_SUMS: + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.update_modifier_sum( + current_date, + deps.static_modifier_cache + ); + } + break; + case work_t::COUNTRY_UPDATE_MODIFIER_SUMS_BEFORE_MAP: + for (CountryInstance& country : work_bundle.countries_chunk) { + country.update_modifier_sum_before_map( + current_date, + deps.static_modifier_cache + ); + } + break; + case work_t::COUNTRY_UPDATE_MODIFIER_SUMS_AFTER_MAP: + for (CountryInstance& country : work_bundle.countries_chunk) { + country.update_modifier_sum_after_map(current_date); + } + break; + } } { @@ -139,7 +161,7 @@ void ThreadPool::loop_until_cancelled( } } -void ThreadPool::process_work(const work_t work_type) { +void ThreadPool::process(const work_t work_type) { { std::unique_lock thread_lock { thread_mutex }; if (is_cancellation_requested) { @@ -184,12 +206,7 @@ ThreadPool::~ThreadPool() { } void ThreadPool::initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - const strata_index_t strata_count, + ThreadDeps const& deps, forwardable_span goods, forwardable_span countries, forwardable_span provinces @@ -261,27 +278,13 @@ void ThreadPool::initialise_threadpool( [ this, &work_for_thread = work_per_thread[i], - &game_rules_manager, - &good_instance_manager, - &modifier_effect_cache, - &pop_defines, - &production_type_manager, - countries, - good_count = good_index_t(goods.size()), - strata_count, + deps, work_bundles_begin, work_bundles_end ]() -> void { loop_until_cancelled( work_for_thread, - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - pop_defines, - production_type_manager, - countries, - good_count, - strata_count, + deps, std::span{ work_bundles_begin, work_bundles_end } ); } @@ -289,24 +292,4 @@ void ThreadPool::initialise_threadpool( work_bundles_begin = work_bundles_end; } -} - -void ThreadPool::process_good_execute_orders() { - process_work(work_t::GOOD_EXECUTE_ORDERS); -} - -void ThreadPool::process_province_ticks() { - process_work(work_t::PROVINCE_TICK); -} - -void ThreadPool::process_province_initialise_for_new_game() { - process_work(work_t::PROVINCE_INITIALISE_FOR_NEW_GAME); -} - -void ThreadPool::process_country_ticks_before_map() { - process_work(work_t::COUNTRY_TICK_BEFORE_MAP); -} - -void ThreadPool::process_country_ticks_after_map(){ - process_work(work_t::COUNTRY_TICK_AFTER_MAP); } \ No newline at end of file diff --git a/src/openvic-simulation/utility/ThreadPool.hpp b/src/openvic-simulation/utility/ThreadPool.hpp index 8251857ef..75a05fdf9 100644 --- a/src/openvic-simulation/utility/ThreadPool.hpp +++ b/src/openvic-simulation/utility/ThreadPool.hpp @@ -7,24 +7,17 @@ #include #include -#include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/core/random/RandomGenerator.hpp" #include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/TypedIndices.hpp" namespace OpenVic { - struct GameRulesManager; - struct GoodDefinition; - struct GoodInstanceManager; struct CountryInstance; struct GoodInstance; - struct ModifierEffectCache; - struct PopsDefines; - struct ProductionTypeManager; - struct Strata; + struct ProvinceInstance; + struct ThreadDeps; //bundle work so they always have the same rng regardless of hardware concurrency struct WorkBundle { @@ -47,18 +40,23 @@ namespace OpenVic { provinces_chunk { new_provinces_chunk } {} }; + + enum struct work_t : uint8_t { + NONE, + GOOD_EXECUTE_ORDERS, + PROVINCE_INITIALISE_FOR_NEW_GAME, + PROVINCE_TICK, + COUNTRY_TICK_BEFORE_MAP, + COUNTRY_TICK_AFTER_MAP, + PROVINCE_UPDATE_GAMESTATE, + COUNTRY_UPDATE_GAMESTATE_AFTER_MAP, + PROVINCE_UPDATE_MODIFIER_SUMS, + COUNTRY_UPDATE_MODIFIER_SUMS_BEFORE_MAP, + COUNTRY_UPDATE_MODIFIER_SUMS_AFTER_MAP + }; struct ThreadPool { private: - enum struct work_t : uint8_t { - NONE, - GOOD_EXECUTE_ORDERS, - PROVINCE_INITIALISE_FOR_NEW_GAME, - PROVINCE_TICK, - COUNTRY_TICK_BEFORE_MAP, - COUNTRY_TICK_AFTER_MAP - }; - constexpr static std::size_t WORK_BUNDLE_COUNT = 32; std::array all_work_bundles; memory::vector threads; @@ -71,39 +69,21 @@ namespace OpenVic { void loop_until_cancelled( work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - const good_index_t good_count, - const strata_index_t strata_count, + const ThreadDeps deps, forwardable_span work_bundles ); void await_completion(); - void process_work(const work_t work_type); public: ThreadPool(Date const& new_current_date); ~ThreadPool(); void initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - const strata_index_t strata_count, + ThreadDeps const& deps, forwardable_span goods, forwardable_span countries, forwardable_span provinces ); - - void process_good_execute_orders(); - void process_province_ticks(); - void process_province_initialise_for_new_game(); - void process_country_ticks_before_map(); - void process_country_ticks_after_map(); + void process(const work_t work_type); }; } \ No newline at end of file diff --git a/tests/src/SpyAllocator.hpp b/tests/src/SpyAllocator.hpp new file mode 100644 index 000000000..22a1d21e0 --- /dev/null +++ b/tests/src/SpyAllocator.hpp @@ -0,0 +1,61 @@ +#include +#include + +// Telemetry structure remains the same +struct AllocationMetrics { + std::size_t total_allocated_bytes = 0; + std::size_t total_deallocated_bytes = 0; + std::size_t allocation_count = 0; + std::size_t deallocation_count = 0; + + void reset() { + total_allocated_bytes = 0; + total_deallocated_bytes = 0; + allocation_count = 0; + deallocation_count = 0; + } + + std::size_t active_bytes() const { + return total_allocated_bytes - total_deallocated_bytes; + } +}; + +// SpyAllocator now wraps an underlying Allocator type (defaults to std::allocator) +template > +class SpyAllocator { +public: + using value_type = T; + + // Shared telemetry state across allocator copies + std::shared_ptr metrics; + // The actual allocator doing the heavy lifting + Allocator upstream; + + // Default Constructor + SpyAllocator() + : metrics(std::make_shared()), upstream() {} + + // Explicitly pass an existing upstream allocator instance if needed + explicit SpyAllocator(const Allocator& alloc) + : metrics(std::make_shared()), upstream(alloc) {} + + value_type* allocate(const std::size_t n) { + // Delegate allocation to the upstream allocator + value_type* ptr = std::allocator_traits::allocate(upstream, n); + + if (metrics && ptr) { + metrics->total_allocated_bytes += (n * sizeof(value_type)); + metrics->allocation_count++; + } + return ptr; + } + + void deallocate(value_type* const ptr, const std::size_t n) noexcept { + if (metrics) { + metrics->total_deallocated_bytes += (n * sizeof(value_type)); + metrics->deallocation_count++; + } + // Delegate deallocation to the upstream allocator + std::allocator_traits::deallocate(upstream, ptr, n); + } +}; \ No newline at end of file diff --git a/tests/src/core/BulkInsertWrapper.cpp b/tests/src/core/BulkInsertWrapper.cpp new file mode 100644 index 000000000..7b2301ce6 --- /dev/null +++ b/tests/src/core/BulkInsertWrapper.cpp @@ -0,0 +1,162 @@ +#include +#include +#include + +#include "openvic-simulation/core/BulkInsertWrapper.hpp" + +#include + +#include "SpyAllocator.hpp" + +// A simple non-trivially destructible type to test constraint violations if needed, +// and a trivial one to satisfy emplace_back's requires clause. +struct TrivialPoint { + int x = 0; + int y = 0; +}; + +using namespace OpenVic; + +TEST_CASE("bulk_insert_wrapper Constructors", "[bulk_insert_wrapper][bulk_insert_wrapper-constructor]") { + constexpr bulk_insert_wrapper> empty; + CONSTEXPR_CHECK(empty.empty()); + CONSTEXPR_CHECK(empty.size() == 0); + CONSTEXPR_CHECK(empty.capacity() == 0); + CONSTEXPR_CHECK(empty.begin() == empty.end()); + CONSTEXPR_CHECK(empty.cbegin() == empty.cend()); + CONSTEXPR_CHECK(empty.rbegin() == empty.rend()); + + constexpr std::size_t expected_size = 3; + bulk_insert_wrapper> filled { + std::vector { 1, 2, 3 } + }; + CHECK(!filled.empty()); + CHECK(filled.size() == expected_size); + CHECK(filled.capacity() >= expected_size); + CHECK(std::distance(filled.begin(), filled.end()) == expected_size); + CHECK(std::distance(filled.cbegin(), filled.cend()) == expected_size); + CHECK(std::distance(filled.rbegin(), filled.rend()) == expected_size); + CHECK(filled[0] == 1); +} + +TEST_CASE("bulk_insert_wrapper make_room does not allocate", "[bulk_insert_wrapper][bulk_insert_wrapper-make_room]") { + SpyAllocator spy_allocator{}; + bulk_insert_wrapper< + std::vector< + int, + SpyAllocator + > + > empty { spy_allocator }; + empty.make_room_for(10); + + CHECK(empty.empty()); + CHECK(empty.size() == 0); + CHECK(empty.capacity() == 0); + CHECK(empty.begin() == empty.end()); + CHECK(empty.cbegin() == empty.cend()); + CHECK(empty.rbegin() == empty.rend()); + CHECK(spy_allocator.metrics->allocation_count == 0); +} + +// correct usage +TEST_CASE("bulk_insert_wrapper make_room + append_range", "[bulk_insert_wrapper][bulk_insert_wrapper-append_range]") { + SpyAllocator spy_allocator{}; + bulk_insert_wrapper< + std::vector< + int, + SpyAllocator + > + > wrapper { spy_allocator }; + + std::vector a { 1, 2 }; + std::vector b { 3, 4, 5 }; + + wrapper.make_room_for(a.size()); + wrapper.make_room_for(b.size()); + + wrapper.append_range(a); + CHECK(wrapper.size() == a.size()); + CHECK(wrapper.capacity() >= a.size() + b.size()); + + wrapper.append_range(b); + + CHECK(wrapper.size() == a.size() + b.size()); + CHECK(spy_allocator.metrics->allocation_count == 1); +} + +// cassert prevents testing in debug +#ifdef NDEBUG +// incorrect usage may not crash +TEST_CASE("bulk_insert_wrapper append_range without make_room", "[bulk_insert_wrapper][bulk_insert_wrapper-append_range]") { + SpyAllocator spy_allocator{}; + bulk_insert_wrapper< + std::vector< + int, + SpyAllocator + > + > wrapper { spy_allocator }; + + std::vector a { 1, 2 }; + std::vector b { 3, 4, 5 }; + + wrapper.append_range(a); + wrapper.append_range(b); + + CHECK(wrapper.size() == a.size() + b.size()); + CHECK(wrapper.capacity() >= a.size() + b.size()); + CHECK(spy_allocator.metrics->allocation_count <= 2); +} +#endif + +TEST_CASE("bulk_insert_wrapper clear", "[bulk_insert_wrapper][bulk_insert_wrapper-clear]") { + SpyAllocator spy_allocator{}; + bulk_insert_wrapper< + std::vector< + int, + SpyAllocator + > + > wrapper { spy_allocator }; + + std::vector a { 1, 2 }; + constexpr std::size_t extra_room = 1; + + wrapper.make_room_for(a.size()); + wrapper.make_room_for(extra_room); + + wrapper.append_range(a); + CHECK(wrapper.size() == a.size()); + CHECK(wrapper.capacity() >= a.size() + extra_room); + + wrapper.clear(); + CHECK(wrapper.empty()); + CHECK(spy_allocator.metrics->allocation_count == 1); +} + +TEST_CASE("bulk_insert_wrapper shrink_to_fit", "[bulk_insert_wrapper][bulk_insert_wrapper-shrink_to_fit]") { + SpyAllocator spy_allocator{}; + bulk_insert_wrapper< + std::vector< + int, + SpyAllocator + > + > wrapper { spy_allocator }; + + std::vector a { 1, 2 }; + constexpr std::size_t extra_room = 1; + + wrapper.make_room_for(a.size()); + wrapper.make_room_for(extra_room); + + wrapper.append_range(a); + CHECK(wrapper.size() == a.size()); + const std::size_t capacity_before_shrink = wrapper.capacity(); + CHECK(capacity_before_shrink >= a.size() + extra_room); + + wrapper.shrink_to_fit(); + CHECK(wrapper.size() == a.size()); + // shrink_to_fit() is non-binding, it may or may not actually shrink depending on underlying container implementation. + // just ensure we don't expand or allocate too often somehow + CHECK(wrapper.capacity() <= capacity_before_shrink); + CHECK(spy_allocator.metrics->allocation_count >= 1); + CHECK(spy_allocator.metrics->allocation_count <= 2); +} \ No newline at end of file diff --git a/tests/src/core/DualAdjacent.cpp b/tests/src/core/DualAdjacent.cpp index 88cc72954..dedf8e0fb 100644 --- a/tests/src/core/DualAdjacent.cpp +++ b/tests/src/core/DualAdjacent.cpp @@ -153,20 +153,29 @@ TEST_CASE("remove_if_dual_adjacent", "[algorithm][dual-adjacent][remove_if_dual_ remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 9)) == vector_down.end() ); CHECK( - remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 5)) == - vector_spread.end() + remove_if_dual_adjacent( + vector_spread.begin(), + vector_spread.end(), + std::bind_front(callback_bind, 5) + ) == vector_spread.end() ); CHECK( // remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 9)) == vector_up.end() - 1 ); CHECK( - remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 1)) == - vector_down.end() - 1 + remove_if_dual_adjacent( + vector_down.begin(), + vector_down.end(), + std::bind_front(callback_bind, 1) + ) == vector_down.end() - 1 ); CHECK( - remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 6)) == - vector_spread.end() - 1 + remove_if_dual_adjacent( + vector_spread.begin(), + vector_spread.end(), + std::bind_front(callback_bind, 6) + ) == vector_spread.end() - 1 ); static constexpr auto removed_vector_up = std::to_array({ 1, 2, 3, 5, 6, 7, 8, 9, 9 }); diff --git a/tests/src/pathfinding/PointMap.cpp b/tests/src/pathfinding/PointMap.cpp index 21951a1fb..99ce148a1 100644 --- a/tests/src/pathfinding/PointMap.cpp +++ b/tests/src/pathfinding/PointMap.cpp @@ -74,8 +74,9 @@ TEST_CASE("PointMap Add/Remove", "[point-map][point-map-add-remove]") { // Tests for get_closest_position_in_segment. a.connect_points(2, 3); CHECK( - a.get_closest_position_in_segment(fvec2_t { fixed_point_t::_0_50, fixed_point_t::_0_50 }) == - fvec2_t { fixed_point_t::_0_50, 1 } + a.get_closest_position_in_segment( + fvec2_t { fixed_point_t::_0_50, fixed_point_t::_0_50 } + ) == fvec2_t { fixed_point_t::_0_50, 1 } ); a.connect_points(3, 4); diff --git a/tests/src/types/FixedPoint.cpp b/tests/src/types/FixedPoint.cpp index efbbab8ba..c58e07146 100644 --- a/tests/src/types/FixedPoint.cpp +++ b/tests/src/types/FixedPoint.cpp @@ -141,13 +141,19 @@ TEST_CASE("fixed_point_t Parse methods", "[fixed_point_t][fixed_point_t-parse]") static constexpr std::string_view plus_fixed_point_str = "+4.5432"sv; fixed_point_t fp = fixed_point_t::_0; CHECK( - fp::from_chars(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()).ec == - std::errc::invalid_argument + fp::from_chars( + fp, + plus_fixed_point_str.data(), + plus_fixed_point_str.data() + plus_fixed_point_str.size() + ).ec == std::errc::invalid_argument ); CHECK(fp == 0.0_a); CHECK( - fp::from_chars_with_plus(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()).ec == - std::errc {} + fp::from_chars_with_plus( + fp, + plus_fixed_point_str.data(), + plus_fixed_point_str.data() + plus_fixed_point_str.size() + ).ec == std::errc {} ); CHECK(fp == 4.5432_a); } diff --git a/tests/src/types/Signal.cpp b/tests/src/types/Signal.cpp index cdeb6f274..8a8d31e38 100644 --- a/tests/src/types/Signal.cpp +++ b/tests/src/types/Signal.cpp @@ -16,8 +16,11 @@ using namespace OpenVic; using namespace std::string_view_literals; -using SignalTypes = - snitch::type_list, nothread::signal, basic_signal>; +using SignalTypes = snitch::type_list< + OpenVic::signal, + nothread::signal, + basic_signal +>; void test_func(int& sum, int i) { sum += i; diff --git a/tests/src/types/Vector2.cpp b/tests/src/types/Vector2.cpp index 727f51844..28a23ae09 100644 --- a/tests/src/types/Vector2.cpp +++ b/tests/src/types/Vector2.cpp @@ -143,8 +143,7 @@ TEST_CASE("fvec2_t Operators", "[vec2_t][fvec2_t][fvec2_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec2 { 1.25, 1.625 }); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec2 { + decimal1 - decimal2 == testing::approx_vec2 { (1.1_a).epsilon(testing::INACCURATE_EPSILON), // (1.5_a).epsilon(testing::INACCURATE_EPSILON) // } @@ -152,8 +151,7 @@ TEST_CASE("fvec2_t Operators", "[vec2_t][fvec2_t][fvec2_t-operators]") { CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec2 { 0.25, 1.375 }); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec2 { + decimal1 * decimal2 == testing::approx_vec2 { (2.76_a).epsilon(testing::INACCURATE_EPSILON), // (16.66_a).epsilon(testing::INACCURATE_EPSILON) // } diff --git a/tests/src/types/Vector3.cpp b/tests/src/types/Vector3.cpp index b6c4c1d9f..2b0af8e5b 100644 --- a/tests/src/types/Vector3.cpp +++ b/tests/src/types/Vector3.cpp @@ -117,9 +117,12 @@ TEST_CASE("dvec3_t Length methods", "[vec3_t][dvec3_t][dvec3_t-length]") { TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; - static constexpr fixed_point_t _7_80 = // - fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + - fixed_point_t::_0_10; + static constexpr fixed_point_t _7_80 = fixed_point_t::_4 + + fixed_point_t::_2 + + fixed_point_t::_1 + + fixed_point_t::_0_50 + + fixed_point_t::_0_20 + + fixed_point_t::_0_10; static constexpr fixed_point_t _1_20 = fixed_point_t::_0_20 * 6; static constexpr fixed_point_t _3_40 = fixed_point_t::_0_20 * 17; static constexpr fixed_point_t _5_60 = fixed_point_t::_4 + fixed_point_t::_1_50 + fixed_point_t::_0_10; @@ -138,8 +141,7 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec3(1.25, 1.625, 0.875)); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec3 { + decimal1 - decimal2 == testing::approx_vec3 { (1.1_a).epsilon(testing::INACCURATE_EPSILON), // (1.5_a).epsilon(testing::INACCURATE_EPSILON), // (2.2_a).epsilon(testing::INACCURATE_EPSILON) // @@ -148,8 +150,7 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec3(0.25, 1.375, 0.375)); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec3 { + decimal1 * decimal2 == testing::approx_vec3 { (2.76_a).epsilon(testing::INACCURATE_EPSILON), // (16.66_a).epsilon(testing::INACCURATE_EPSILON), // (43.68_a).epsilon(testing::INACCURATE_EPSILON) // diff --git a/tests/src/types/Vector4.cpp b/tests/src/types/Vector4.cpp index e5715d87f..00bf38a33 100644 --- a/tests/src/types/Vector4.cpp +++ b/tests/src/types/Vector4.cpp @@ -116,9 +116,12 @@ TEST_CASE("dvec4_t Length methods", "[vec4_t][dvec4_t][dvec4_t-length]") { TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; - static constexpr fixed_point_t _7_80 = // - fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + - fixed_point_t::_0_10; + static constexpr fixed_point_t _7_80 = fixed_point_t::_4 + + fixed_point_t::_2 + + fixed_point_t::_1 + + fixed_point_t::_0_50 + + fixed_point_t::_0_20 + + fixed_point_t::_0_10; static constexpr fixed_point_t _3_20 = fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_20; static constexpr fixed_point_t _1_20 = fixed_point_t::_0_20 * 6; static constexpr fixed_point_t _3_40 = fixed_point_t::_0_20 * 17; @@ -139,8 +142,7 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec4(1.25, 1.625, 0.875, 0.875)); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec4 { + decimal1 - decimal2 == testing::approx_vec4 { (1.1_a).epsilon(testing::INACCURATE_EPSILON), // (1.5_a).epsilon(testing::INACCURATE_EPSILON), // (2.2_a).epsilon(testing::INACCURATE_EPSILON), // @@ -151,8 +153,7 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec4(0.25, 1.375, 0.375, -0.625)); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec4 { + decimal1 * decimal2 == testing::approx_vec4 { (2.76_a).epsilon(testing::INACCURATE_EPSILON), // (16.66_a).epsilon(testing::INACCURATE_EPSILON), // (43.68_a).epsilon(testing::INACCURATE_EPSILON), // @@ -163,8 +164,12 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK(int1 / int2 == testing::approx_vec4(4, 2.5, 3, 2)); CONSTEXPR_CHECK( - decimal1 / decimal2 == - testing::approx_vec4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.88235294118) + decimal1 / decimal2 == testing::approx_vec4( + 1.91666666666666666, + 1.44117647058823529, + 1.39285714285714286, + 1.88235294118 + ) ); CONSTEXPR_CHECK(power1 / power2 == testing::approx_vec4(1.5, 12.0, 2.5, 1.0 / 6.0));