1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use crate::{
    layer::wildlife::{self, DensityFn, SpawnEntry},
    site::{economy::TradeInformation, Site},
    Colors, Features,
};
use common::{
    assets::{AssetExt, AssetHandle},
    store::Store,
    trade::{SiteId, SitePrices},
};
use core::ops::Deref;
use noise::{Fbm, MultiFractal, Perlin, SuperSimplex};
use std::sync::Arc;

const WORLD_COLORS_MANIFEST: &str = "world.style.colors";
const WORLD_FEATURES_MANIFEST: &str = "world.features";

pub struct Index {
    pub seed: u32,
    pub time: f32,
    pub noise: Noise,
    pub sites: Store<Site>,
    pub trade: TradeInformation,
    pub wildlife_spawns: Vec<(AssetHandle<SpawnEntry>, DensityFn)>,
    colors: AssetHandle<Arc<Colors>>,
    features: AssetHandle<Arc<Features>>,
}

/// An owned reference to indexed data.
///
/// The data are split out so that we can replace the colors without disturbing
/// the rest of the index, while also keeping all the data within a single
/// indirection.
#[derive(Clone)]
pub struct IndexOwned {
    colors: Arc<Colors>,
    features: Arc<Features>,
    index: Arc<Index>,
}

impl Deref for IndexOwned {
    type Target = Index;

    fn deref(&self) -> &Self::Target { &self.index }
}

/// A shared reference to indexed data.
///
/// This is copyable and can be used from either style of index.
#[derive(Clone, Copy)]
pub struct IndexRef<'a> {
    pub colors: &'a Colors,
    pub features: &'a Features,
    pub index: &'a Index,
}

impl<'a> Deref for IndexRef<'a> {
    type Target = Index;

    fn deref(&self) -> &Self::Target { self.index }
}

impl Index {
    /// NOTE: Panics if the color manifest cannot be loaded.
    pub fn new(seed: u32) -> Self {
        let colors = Arc::<Colors>::load_expect(WORLD_COLORS_MANIFEST);
        let features = Arc::<Features>::load_expect(WORLD_FEATURES_MANIFEST);
        let wildlife_spawns = wildlife::spawn_manifest()
            .into_iter()
            .map(|(e, f)| (SpawnEntry::load_expect(e), f))
            .collect();

        Self {
            seed,
            time: 0.0,
            noise: Noise::new(seed),
            sites: Store::default(),
            trade: Default::default(),
            wildlife_spawns,
            colors,
            features,
        }
    }

    pub fn colors(&self) -> impl Deref<Target = Arc<Colors>> + '_ { self.colors.read() }

    pub fn features(&self) -> impl Deref<Target = Arc<Features>> + '_ { self.features.read() }

    pub fn get_site_prices(&self, site_id: SiteId) -> Option<SitePrices> {
        self.sites
            .recreate_id(site_id)
            .map(|i| self.sites.get(i))
            .map(|s| s.economy.get_site_prices())
    }
}

impl IndexOwned {
    pub fn new(index: Index) -> Self {
        let colors = index.colors.cloned();
        let features = index.features.cloned();

        Self {
            index: Arc::new(index),
            colors,
            features,
        }
    }

    /// NOTE: Callback is called only when colors actually have to be reloaded.
    /// The server is responsible for making sure that all affected chunks are
    /// reloaded; a naive approach will just regenerate every chunk on the
    /// server, but it is possible that eventually we can find a better
    /// solution.
    ///
    /// Ideally, this should be called about once per tick.
    pub fn reload_if_changed<R>(&mut self, reload: impl FnOnce(&mut Self) -> R) -> Option<R> {
        let reloaded = self.index.colors.reloaded_global() || self.index.features.reloaded_global();
        reloaded.then(move || {
            // Reload the fields from the asset handle, which is updated automatically
            self.colors = self.index.colors.cloned();
            self.features = self.index.features.cloned();
            // Update wildlife spawns which is based on base_density in features
            reload(self)
        })
    }

    pub fn as_index_ref(&self) -> IndexRef {
        IndexRef {
            colors: &self.colors,
            features: &self.features,
            index: &self.index,
        }
    }
}

pub struct Noise {
    pub cave_nz: SuperSimplex,
    pub scatter_nz: SuperSimplex,
    pub cave_fbm_nz: Fbm<Perlin>,
}

impl Noise {
    fn new(seed: u32) -> Self {
        Self {
            cave_nz: SuperSimplex::new(seed + 0),
            scatter_nz: SuperSimplex::new(seed + 1),
            cave_fbm_nz: Fbm::new(seed + 2).set_octaves(5),
        }
    }
}