Skip to content

Apply clang-tidy fixes #384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions misc/scripts/exp_lut_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#!/usr/bin/env python
import decimal
import os
from argparse import ArgumentParser
from math import e
from typing import List

BIT_COUNT = 64
MAX_VALUE = 2**BIT_COUNT

DEFAULT_DIVISOR_BASE = 2
DEFAULT_DIVISOR_POWER = 16
DEFAULT_EXP_BASE = e


def generate_exp_lut(divisor_base: int, divisor_power: int, exp_base: decimal.Decimal):
divisor: int = divisor_base**divisor_power

exp_lut: List[int] = []

for index in range(BIT_COUNT):
exponent: decimal.Decimal = (2**index) / divisor
value: int = int(decimal.Decimal(exp_base**exponent) * decimal.Decimal(divisor) + decimal.Decimal(0.5))
if value > MAX_VALUE:
break
exp_lut.append(value)

lut_identifier: str = (
f"LUT_{divisor_base}_{divisor_power}_EXP_{'e' if exp_base == e else ('%g' % exp_base).replace('.', 'p')}"
)
lut_size: int = len(exp_lut)

generated_options = ""
if (
DEFAULT_DIVISOR_BASE is not divisor_base
or DEFAULT_DIVISOR_POWER is not divisor_power
or DEFAULT_EXP_BASE is not exp_base
):
generated_options += " with `"

if DEFAULT_DIVISOR_BASE is not divisor_base:
generated_options += f"-b {divisor_base}"
if DEFAULT_DIVISOR_POWER is not divisor_power or DEFAULT_EXP_BASE is not exp_base:
generated_options += " "

if DEFAULT_DIVISOR_POWER is not divisor_power:
generated_options += f"-p {divisor_power}"
if DEFAULT_EXP_BASE is not exp_base:
generated_options += " "

if DEFAULT_EXP_BASE is not exp_base:
generated_options += f"-e {exp_base:g}"

generated_options += "`"

source: str = f"""// This file was generated using the `misc/scripts/exp_lut_generator.py` script{generated_options}.

#pragma once

#include <array>
#include <cstddef>
#include <cstdint>

static constexpr uint64_t {lut_identifier}_DIVISOR = {divisor};
static constexpr size_t {lut_identifier}_SIZE = {lut_size};

static constexpr std::array<int64_t, {lut_identifier}_SIZE> {lut_identifier} {{
"""

for value in exp_lut[:-1]:
source += f"\t{value},\n"

source += f"\t{exp_lut[-1]}\n"
source += "};\n"

fixed_point_lut_path: str = os.path.join(
os.path.dirname(__file__), f"../../src/openvic-simulation/types/fixed_point/FixedPoint{lut_identifier}.hpp"
)
with open(fixed_point_lut_path, "w", newline="\n") as file:
file.write(source)

print(f"`FixedPoint{lut_identifier}.hpp` generated successfully.")


if __name__ == "__main__":
parser = ArgumentParser(
prog="Fixed Point Exp LUT Generator", description="Fixed-Point Exponential Look-Up Table generator"
)
parser.add_argument(
"-b",
"--base",
type=int,
default=DEFAULT_DIVISOR_BASE,
choices=range(2, 65),
help="The base of the fixed point divisor",
)
parser.add_argument(
"-p",
"--power",
type=int,
default=DEFAULT_DIVISOR_POWER,
choices=range(1, 65),
help="The power of the fixed point divisor",
)
parser.add_argument(
"-e",
"--exp",
type=float,
default=DEFAULT_EXP_BASE,
help="The base of the exponential function the look-up table represents",
)
args = parser.parse_args()

generate_exp_lut(args.base, args.power, args.exp)
exit(0)
152 changes: 152 additions & 0 deletions misc/scripts/sin_lut_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env python
import decimal
import os
from argparse import ArgumentParser

DEFAULT_PRECISION = 16
DEFAULT_COUNT = 9


def decimal_pi() -> decimal.Decimal:
"""Compute Pi to the current precision.

>>> print(pdecimal_pii())
3.141592653589793238462643383

"""
decimal.getcontext().prec += 2 # extra digits for intermediate steps
three: decimal.Decimal = decimal.Decimal(3) # substitute "three=3.0" for regular floats
lasts: decimal.Decimal = decimal.Decimal(0)
t: decimal.Decimal = three
n, na, d, da = 1, 0, 0, 24
s: decimal.Decimal = three
while s != lasts:
lasts = s
n, na = n + na, na + 8
d, da = d + da, da + 32
t = (t * n) / d
s += decimal.Decimal(t)
decimal.getcontext().prec -= 2
return +s # unary plus applies the new precision


def decimal_sin(x: decimal.Decimal) -> decimal.Decimal:
"""Return the sine of x as measured in radians.

The Taylor series approximation works best for a small value of x.
For larger values, first compute x = x % (2 * pi).

>>> print(decimal_sin(Decimal('0.5')))
0.4794255386042030002732879352
>>> print(decimal_sin(0.5))
0.479425538604
>>> print(decimal_sin(0.5+0j))
(0.479425538604+0j)

"""
decimal.getcontext().prec += 2
i, fact, num, sign = 1, 1, x, 1
s: decimal.Decimal = x
lasts: decimal.Decimal = decimal.Decimal(0)
while s != lasts:
lasts = s
i += 2
fact *= i * (i - 1)
num *= x * x
sign *= -1
s += num / fact * sign
decimal.getcontext().prec -= 2
return +s


def generate_sin_lut(precision: int, count_log2: int):
one = 1 << precision
count = 1 << count_log2

SinLut = []

for i in range(count):
angle: decimal.Decimal = 2 * decimal_pi() * i / count

sin_value: decimal.Decimal = decimal_sin(angle) # sin(angle)
moved_sin: decimal.Decimal = sin_value * one
rounded_sin: int = (
int(moved_sin + decimal.Decimal(0.5)) if moved_sin > 0 else int(moved_sin - decimal.Decimal(0.5))
)
SinLut.append(rounded_sin)

SinLut.append(SinLut[0])

generated_options = ""
if DEFAULT_PRECISION is not precision or DEFAULT_COUNT is not count_log2:
generated_options += " with `"

if DEFAULT_PRECISION is not precision:
generated_options += f"-p {precision}"
if DEFAULT_COUNT is not count_log2:
generated_options += " "

if DEFAULT_COUNT is not count_log2:
generated_options += f"-c {count_log2}"

generated_options += "`"

source = f"""// This file was generated using the `misc/scripts/sin_lut_generator.py` script{generated_options}.

#pragma once

#include <array>
#include <cstdint>

static constexpr uint32_t SIN_LUT_PRECISION = {precision};
static constexpr uint32_t SIN_LUT_COUNT_LOG2 = {count_log2};
static constexpr int32_t SIN_LUT_SHIFT = SIN_LUT_PRECISION - SIN_LUT_COUNT_LOG2;

static constexpr std::array<int64_t, (1 << SIN_LUT_COUNT_LOG2) + 1> SIN_LUT = {{
"""

VALS_PER_LINE = 16

lines = [SinLut[i : i + VALS_PER_LINE] for i in range(0, len(SinLut), VALS_PER_LINE)]

for line in lines[:-1]:
source += f"\t{', '.join(str(value) for value in line)},\n"

source += f"\t{', '.join(str(value) for value in lines[-1])}\n"
source += "};\n"

fixed_point_sin_path: str = os.path.join(
os.path.dirname(__file__), "../../src/openvic-simulation/types/fixed_point/FixedPointLUT_sin.hpp"
)
with open(fixed_point_sin_path, "w", newline="\n") as file:
file.write(source)

print("`FixedPointLUT_sin.hpp` generated successfully.")


if __name__ == "__main__":
parser = ArgumentParser(prog="Fixed Point Sin LUT Generator", description="Fixed-Point Sin Look-Up Table generator")
parser.add_argument(
"-p",
"--precision",
type=int,
default=DEFAULT_PRECISION,
choices=range(1, 65),
help="The number of bits after the point (fractional bits)",
)
parser.add_argument(
"-c",
"--count",
type=int,
default=DEFAULT_COUNT,
choices=range(1, 65),
help="The base 2 log of the number of values in the look-up table (must be <= precision)",
)
args = parser.parse_args()

if args.precision < args.count:
print("ERROR: invalid count ", args.count, " - can't be greater than precision (", args.precision, ")")
exit(-1)
else:
generate_sin_lut(args.precision, args.count)
exit(0)
2 changes: 1 addition & 1 deletion src/openvic-simulation/dataloader/Dataloader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Dataloader::path_vector_t Dataloader::_lookup_files_in_dir(
path_vector_t ret;
struct file_entry_t {
fs::path file;
fs::path const* root;
fs::path const* root = nullptr;
};
string_map_t<file_entry_t> found_files;
for (fs::path const& root : roots) {
Expand Down
4 changes: 2 additions & 2 deletions src/openvic-simulation/dataloader/NodeTools.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,10 @@ using namespace std::string_view_literals;
ONE_OR_MORE = _MUST_APPEAR | _CAN_REPEAT
} expected_count;
node_callback_t callback;
size_t count;
size_t count = 0;

dictionary_entry_t(expected_count_t new_expected_count, node_callback_t&& new_callback)
: expected_count { new_expected_count }, callback { MOV(new_callback) }, count { 0 } {}
: expected_count { new_expected_count }, callback { MOV(new_callback) } {}

constexpr bool must_appear() const {
return static_cast<uint8_t>(expected_count) & static_cast<uint8_t>(expected_count_t::_MUST_APPEAR);
Expand Down
4 changes: 3 additions & 1 deletion src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#pragma once
#ifdef _WIN32

#include <concepts>
#pragma comment(lib, "advapi32.lib")
Expand Down Expand Up @@ -149,7 +150,7 @@ namespace OpenVic::Windows {
};

template<either_char_type RCHAR_T, either_char_type CHAR_T, either_char_type CHAR_T2>
std::basic_string<RCHAR_T> ReadRegValue(
std::basic_string<RCHAR_T> ReadRegValue( //
HKEY root, std::basic_string_view<CHAR_T> key, std::basic_string_view<CHAR_T2> name
) {
RegistryKey registry_key(root, key, name);
Expand All @@ -168,3 +169,4 @@ namespace OpenVic::Windows {
return ReadRegValue<RCHAR_T>(root, key_sv, name_sv);
}
}
#endif
41 changes: 1 addition & 40 deletions src/openvic-simulation/defines/AIDefines.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,7 @@
using namespace OpenVic;
using namespace OpenVic::NodeTools;

AIDefines::AIDefines()
: colony_weight {},
administrator_weight {},
industryworker_weight {},
educator_weight {},
soldier_weight {},
soldier_fraction {},
capitalist_fraction {},
production_weight {},
spam_penalty {},
one_side_max_warscore {},
pop_project_investment_max_budget_factor {},
relation_limit_no_alliance_offer {},
naval_supply_penalty_limit {},
chance_build_railroad {},
chance_build_naval_base {},
chance_build_fort {},
chance_invest_pop_proj {},
chance_foreign_invest {},
tws_awareness_score_low_cap {},
tws_awareness_score_aspect {},
peace_base_reluctance {},
peace_time_duration {},
peace_time_factor {},
peace_time_factor_no_goals {},
peace_war_exhaustion_factor {},
peace_war_direction_factor {},
peace_war_direction_winning_mult {},
peace_force_balance_factor {},
peace_ally_base_reluctance_mult {},
peace_ally_time_mult {},
peace_ally_war_exhaustion_mult {},
peace_ally_war_direction_mult {},
peace_ally_force_balance_mult {},
aggression_base {},
aggression_unciv_bonus {},
fleet_size {},
min_fleets {},
max_fleets {},
time_before_disband {} {}
AIDefines::AIDefines() {}

std::string_view AIDefines::get_name() const {
return "ai";
Expand Down
6 changes: 3 additions & 3 deletions src/openvic-simulation/defines/AIDefines.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ namespace OpenVic {
fixed_point_t PROPERTY(peace_ally_force_balance_mult);
fixed_point_t PROPERTY(aggression_base);
fixed_point_t PROPERTY(aggression_unciv_bonus);
size_t PROPERTY(fleet_size);
size_t PROPERTY(min_fleets);
size_t PROPERTY(max_fleets);
size_t PROPERTY(fleet_size, 0);
size_t PROPERTY(min_fleets, 0);
size_t PROPERTY(max_fleets, 0);
Timespan PROPERTY(time_before_disband);

AIDefines();
Expand Down
Loading