Skip to main content

nil_core/resources/
cost.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use super::maintenance::MaintenanceRatio;
5use derive_more::{Deref, Into};
6use serde::{Deserialize, Serialize};
7use std::ops::Mul;
8
9/// Base cost of an entity, such as buildings or units.
10#[derive(Clone, Copy, Debug, Deref, Into, Deserialize, Serialize)]
11#[into(u32, f64)]
12pub struct Cost(u32);
13
14impl Cost {
15  #[inline]
16  pub const fn new(value: u32) -> Self {
17    Self(value)
18  }
19}
20
21impl From<f64> for Cost {
22  fn from(value: f64) -> Self {
23    debug_assert!(value.is_finite());
24    Self::new(value as u32)
25  }
26}
27
28impl Mul<f64> for Cost {
29  type Output = f64;
30
31  fn mul(self, rhs: f64) -> Self::Output {
32    f64::from(self) * rhs
33  }
34}
35
36impl Mul<ResourceRatio> for Cost {
37  type Output = f64;
38
39  fn mul(self, rhs: ResourceRatio) -> Self::Output {
40    self * rhs.0
41  }
42}
43
44impl Mul<MaintenanceRatio> for Cost {
45  type Output = f64;
46
47  fn mul(self, rhs: MaintenanceRatio) -> Self::Output {
48    self * f64::from(rhs)
49  }
50}
51
52/// Proportion between the total cost and a given resource.
53#[derive(Clone, Copy, Debug, Deref, Into, Deserialize, Serialize)]
54pub struct ResourceRatio(f64);
55
56impl ResourceRatio {
57  #[inline]
58  pub const fn new(value: f64) -> Self {
59    debug_assert!(value.is_finite());
60    Self(value.clamp(0.0, 1.0))
61  }
62
63  #[inline]
64  pub const fn as_f64(self) -> f64 {
65    self.0
66  }
67}
68
69/// Checks, at compile time, if the sum of the resource ratios equals 1.
70#[macro_export]
71macro_rules! check_total_resource_ratio {
72  ($first:expr, $($other:expr),+ $(,)?) => {
73    const _: () = {
74      let mut first = $first.as_f64();
75      $(first += $other.as_f64();)+
76      assert!((first - 1.0).abs() < 0.001);
77    };
78  };
79}