veloren/world/src/lib.rs
Christof Petig 15b11d9154 Implement /price_list (work in progress), stub for /buy and /sell
remove outdated economic simulation code

remove old values, document

add natural resources to economy

Remove NaturalResources from Place (now in Economy)

find closest site to each chunk

implement natural resources (the distance scale is wrong)

cargo fmt

working distance calculation

this collection of natural resources seem to make sense, too much Wheat though

use natural resources and controlled area to replenish goods

increase the amount of chunks controlled by one guard to 50

add new professions and goods to the list

implement multiple products per worker

remove the old code and rename the new code to the previous name

correctly determine which goods guards will give you access to

correctly estimate the amount of natural resources controlled

adapt to new server API

instrument tooltips

Now I just need to figure out how to store a (reference to) a closure

closures for tooltip content generation

pass site/cave id to the client

Add economic information to the client structure
(not yet exchanged with the server)

Send SiteId to the client, prepare messages for economy request
Make client::sites a HashMap

Specialize the Crafter into Brewer,Bladesmith and Blacksmith

working server request for economic info from within tooltip

fully operational economic tooltips
I need to fix the id clash between caves and towns though

fix overlapping ids between caves and sites

display stock amount

correctly handle invalid (cave) ids in the request

some initial balancing, turn off most info logging

less intrusive way of implementing the dynamic tool tips in map

further tooltip cleanup

further cleanup, dynamic tooltip not fully working as intended

correctly working tooltip visibility logic

cleanup, display labor value

separate economy info request in a separate translation unit

display values as well

nicer display format for economy

add last_exports and coin to the new economy

do not allocate natural resources to Dungeons (making town so much larger)

balancing attempt

print town size statistics

cargo fmt (dead code)

resource tweaks, csv debugging

output a more interesting town (and then all sites)

fix the labor value logic (now we have meaningful prices)

load professions from ron (WIP)

use assets manager in economy

loading professions works

use professions from ron file

fix Labor debug logic

count chunks per type separately
(preparing for better resource control)

better structured resource data

traders, more professions (WIP)

fix exception when starting the simulation

fix replenish function
TODO:
- use area_ratio for resource usage (chunks should be added to stock, ratio on usage?)
- fix trading

documentation clean up

fix merge artifact

Revise trader mechanic

start Coin with a reasonable default

remove the outdated economy code

preserve documentation from removed old structure

output neighboring sites (preparation)

pass list of neighbors to economy

add trade structures

trading stub

Description of purpose by zesterer on Discord

remember prices (needed for planning)

avoid growing the order vector unboundedly

into_iter doesn't clear the Vec, so clear it manually

use drain to process Vecs, avoid clone

fix the test server

implement a test stub (I need to get it faster than 30 seconds to be more useful)

enable info output in test

debug missing and extra goods

use the same logging extension as water, activate feature

update dependencies

determine good prices, good exchange goods

a working set of revisions

a cozy world which economy tests in 2s

first order planning version

fun with package version

buy according to value/priority, not missing amount

introduce min price constant, fix order priority

in depth debugging

with a correct sign the trading plans start to make sense

move the trade planning to a separate function

rename new function

reorganize code into subroutines (much cleaner)

each trading step now has its own function

cut down the number of debugging output

introduce RoadSecurity and Transportation

transport capacity bookkeeping

only plan to pay with valuable goods, you can no longer stockpile unused options
(which interestingly shows a huge impact, to be investigated)

Coin is now listed as a payment (although not used)

proper transportation estimation (although 0)

remove more left overs uncovered by viewing the code in a merge request

use the old default values, handle non-pileable stocks directly before increasing it
(as economy is based on last year's products)

don't order the missing good multiple times
also it uses coin to buy things!

fix warnings and use the transportation from stock again

cargo fmt

prepare evaluation of trade

don't count transportation multiple times

fix merge artifact

operational trade planning
trade itself is still misleading

make clippy happy

clean up

correct labor ratio of merchants (no need to multiply with amount produced)

incomplete merchant labor_value computation

correct last commit

make economy of scale more explicit

make clippy happy (and code cleaner)

more merchant tweaks (more pop=better)

beginning of real trading code

revert the update of dependencies

remove stale comments/unused code

trading implementation complete (but untested)

something is still strange ...

fix sign in trading

another sign fix

some bugfixes and plenty of debugging code

another bug fixed, more to go

fix another invariant (rounding will lead to very small negative value)

introduce Terrain and Territory

fix merge mistakes
2021-03-14 03:18:32 +00:00

378 lines
12 KiB
Rust

#![deny(unsafe_code)]
#![allow(incomplete_features)]
#![allow(
clippy::option_map_unit_fn,
clippy::blocks_in_if_conditions,
clippy::too_many_arguments
)]
#![deny(clippy::clone_on_ref_ptr)]
#![feature(
arbitrary_enum_discriminant,
bool_to_option,
const_generics,
const_panic,
label_break_value,
or_patterns,
array_value_iter,
array_map
)]
mod all;
mod block;
pub mod canvas;
pub mod civ;
mod column;
pub mod config;
pub mod index;
pub mod land;
pub mod layer;
pub mod pathfinding;
pub mod sim;
pub mod sim2;
pub mod site;
pub mod site2;
pub mod util;
// Reexports
pub use crate::{
canvas::{Canvas, CanvasInfo},
config::CONFIG,
land::Land,
};
pub use block::BlockGen;
pub use column::ColumnSample;
pub use index::{IndexOwned, IndexRef};
use crate::{
column::ColumnGen,
index::Index,
util::{Grid, Sampler},
};
use common::{
assets,
generation::{ChunkSupplement, EntityInfo},
terrain::{Block, BlockKind, SpriteKind, TerrainChunk, TerrainChunkMeta, TerrainChunkSize},
vol::{ReadVol, RectVolSize, WriteVol},
};
use common_net::msg::{world_msg, WorldMapMsg};
use rand::Rng;
use serde::Deserialize;
use std::time::Duration;
use vek::*;
#[derive(Debug)]
pub enum Error {
Other(String),
}
pub struct World {
sim: sim::WorldSim,
civs: civ::Civs,
}
#[derive(Deserialize)]
pub struct Colors {
pub deep_stone_color: (u8, u8, u8),
pub block: block::Colors,
pub column: column::Colors,
pub layer: layer::Colors,
pub site: site::Colors,
}
impl assets::Asset for Colors {
type Loader = assets::RonLoader;
const EXTENSION: &'static str = "ron";
}
impl World {
pub fn generate(seed: u32, opts: sim::WorldOpts) -> (Self, IndexOwned) {
// NOTE: Generating index first in order to quickly fail if the color manifest
// is broken.
let mut index = Index::new(seed);
let mut sim = sim::WorldSim::generate(seed, opts);
let civs = civ::Civs::generate(seed, &mut sim, &mut index);
sim2::simulate(&mut index, &mut sim);
(Self { sim, civs }, IndexOwned::new(index))
}
pub fn sim(&self) -> &sim::WorldSim { &self.sim }
pub fn civs(&self) -> &civ::Civs { &self.civs }
pub fn tick(&self, _dt: Duration) {
// TODO
}
pub fn get_map_data(&self, index: IndexRef) -> WorldMapMsg {
// we need these numbers to create unique ids for cave ends
let num_sites = self.civs().sites().count() as u64;
let num_caves = self.civs().caves.values().count() as u64;
WorldMapMsg {
sites: self
.civs()
.sites
.iter()
.map(|(_, site)| {
world_msg::SiteInfo {
id: site.site_tmp.map(|i| i.id()).unwrap_or_default(),
name: site.site_tmp.map(|id| index.sites[id].name().to_string()),
// TODO: Probably unify these, at some point
kind: match &site.kind {
civ::SiteKind::Settlement => world_msg::SiteKind::Town,
civ::SiteKind::Dungeon => world_msg::SiteKind::Dungeon {
difficulty: match site.site_tmp.map(|id| &index.sites[id].kind) {
Some(site::SiteKind::Dungeon(d)) => d.difficulty(),
_ => 0,
},
},
civ::SiteKind::Castle => world_msg::SiteKind::Castle,
civ::SiteKind::Refactor => world_msg::SiteKind::Town,
civ::SiteKind::Tree => world_msg::SiteKind::Tree,
},
wpos: site.center * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
}
})
.chain(
self.civs()
.caves
.iter()
.map(|(id, info)| {
// separate the two locations, combine with name
std::iter::once((id.id()+num_sites, info.name.clone(), info.location.0))
// unfortunately we have to introduce a fake id (as it gets stored in a map in the client)
.chain(std::iter::once((id.id()+num_sites+num_caves, info.name.clone(), info.location.1)))
})
.flatten() // unwrap inner iteration
.map(|(id, name, pos)| world_msg::SiteInfo {
id,
name: Some(name),
kind: world_msg::SiteKind::Cave,
wpos: pos,
}),
)
.collect(),
..self.sim.get_map(index)
}
}
pub fn sample_columns(
&self,
) -> impl Sampler<Index = (Vec2<i32>, IndexRef), Sample = Option<ColumnSample>> + '_ {
ColumnGen::new(&self.sim)
}
pub fn sample_blocks(&self) -> BlockGen { BlockGen::new(ColumnGen::new(&self.sim)) }
#[allow(clippy::or_fun_call)] // TODO: Pending review in #587
#[allow(clippy::eval_order_dependence)]
#[allow(clippy::result_unit_err)]
pub fn generate_chunk(
&self,
index: IndexRef,
chunk_pos: Vec2<i32>,
// TODO: misleading name
mut should_continue: impl FnMut() -> bool,
) -> Result<(TerrainChunk, ChunkSupplement), ()> {
let mut sampler = self.sample_blocks();
let chunk_wpos2d = chunk_pos * TerrainChunkSize::RECT_SIZE.map(|e| e as i32);
let chunk_center_wpos2d = chunk_wpos2d + TerrainChunkSize::RECT_SIZE.map(|e| e as i32 / 2);
let grid_border = 4;
let zcache_grid = Grid::populate_from(
TerrainChunkSize::RECT_SIZE.map(|e| e as i32) + grid_border * 2,
|offs| sampler.get_z_cache(chunk_wpos2d - grid_border + offs, index),
);
let air = Block::air(SpriteKind::Empty);
let stone = Block::new(
BlockKind::Rock,
zcache_grid
.get(grid_border + TerrainChunkSize::RECT_SIZE.map(|e| e as i32) / 2)
.and_then(|zcache| zcache.as_ref())
.map(|zcache| zcache.sample.stone_col)
.unwrap_or(index.colors.deep_stone_color.into()),
);
let water = Block::new(BlockKind::Water, Rgb::zero());
let (base_z, sim_chunk) = match self
.sim
/*.get_interpolated(
chunk_pos.map2(chunk_size2d, |e, sz: u32| e * sz as i32 + sz as i32 / 2),
|chunk| chunk.get_base_z(),
)
.and_then(|base_z| self.sim.get(chunk_pos).map(|sim_chunk| (base_z, sim_chunk))) */
.get_base_z(chunk_pos)
{
Some(base_z) => (base_z as i32, self.sim.get(chunk_pos).unwrap()),
// Some((base_z, sim_chunk)) => (base_z as i32, sim_chunk),
None => {
return Ok((
TerrainChunk::new(
CONFIG.sea_level as i32,
water,
air,
TerrainChunkMeta::void(),
),
ChunkSupplement::default(),
));
},
};
let meta = TerrainChunkMeta::new(
sim_chunk
.sites
.iter()
.filter(|id| {
index.sites[**id]
.get_origin()
.distance_squared(chunk_center_wpos2d) as f32
<= index.sites[**id].radius().powi(2)
})
.min_by_key(|id| {
index.sites[**id]
.get_origin()
.distance_squared(chunk_center_wpos2d)
})
.map(|id| index.sites[*id].name().to_string()),
sim_chunk.get_biome(),
sim_chunk.alt,
sim_chunk.tree_density,
sim_chunk.cave.1.alt != 0.0,
sim_chunk.river.is_river(),
sim_chunk.temp,
);
let mut chunk = TerrainChunk::new(base_z, stone, air, meta);
for y in 0..TerrainChunkSize::RECT_SIZE.y as i32 {
for x in 0..TerrainChunkSize::RECT_SIZE.x as i32 {
if should_continue() {
return Err(());
};
let offs = Vec2::new(x, y);
let z_cache = match zcache_grid.get(grid_border + offs) {
Some(Some(z_cache)) => z_cache,
_ => continue,
};
let (min_z, max_z) = z_cache.get_z_limits();
(base_z..min_z as i32).for_each(|z| {
let _ = chunk.set(Vec3::new(x, y, z), stone);
});
(min_z as i32..max_z as i32).for_each(|z| {
let lpos = Vec3::new(x, y, z);
let wpos = Vec3::from(chunk_wpos2d) + lpos;
if let Some(block) = sampler.get_with_z_cache(wpos, Some(&z_cache)) {
let _ = chunk.set(lpos, block);
}
});
}
}
let sample_get = |offs| {
zcache_grid
.get(grid_border + offs)
.map(Option::as_ref)
.flatten()
.map(|zc| &zc.sample)
};
// Only use for rng affecting dynamic elements like chests and entities!
let mut dynamic_rng = rand::thread_rng();
// Apply layers (paths, caves, etc.)
let mut canvas = Canvas {
info: CanvasInfo {
wpos: chunk_pos * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
column_grid: &zcache_grid,
column_grid_border: grid_border,
chunks: &self.sim,
index,
chunk: sim_chunk,
},
chunk: &mut chunk,
};
layer::apply_caves_to(&mut canvas, &mut dynamic_rng);
layer::apply_trees_to(&mut canvas, &mut dynamic_rng);
layer::apply_scatter_to(&mut canvas, &mut dynamic_rng);
layer::apply_paths_to(&mut canvas);
// layer::apply_coral_to(&mut canvas);
// Apply site generation
sim_chunk
.sites
.iter()
.for_each(|site| index.sites[*site].apply_to(&mut canvas, &mut dynamic_rng));
let gen_entity_pos = |dynamic_rng: &mut rand::rngs::ThreadRng| {
let lpos2d = TerrainChunkSize::RECT_SIZE
.map(|sz| dynamic_rng.gen::<u32>().rem_euclid(sz) as i32);
let mut lpos = Vec3::new(
lpos2d.x,
lpos2d.y,
sample_get(lpos2d).map(|s| s.alt as i32 - 32).unwrap_or(0),
);
while let Some(block) = chunk.get(lpos).ok().copied().filter(Block::is_solid) {
lpos.z += block.solid_height().ceil() as i32;
}
(Vec3::from(chunk_wpos2d) + lpos).map(|e: i32| e as f32) + 0.5
};
let mut supplement = ChunkSupplement {
entities: Vec::new(),
};
if sim_chunk.contains_waypoint {
supplement.add_entity(EntityInfo::at(gen_entity_pos(&mut dynamic_rng)).into_waypoint());
}
// Apply layer supplement
layer::apply_caves_supplement(
&mut dynamic_rng,
chunk_wpos2d,
sample_get,
&chunk,
index,
&mut supplement,
);
// Apply layer supplement
layer::wildlife::apply_wildlife_supplement(
&mut dynamic_rng,
chunk_wpos2d,
sample_get,
&chunk,
index,
sim_chunk,
&mut supplement,
);
// Apply site supplementary information
sim_chunk.sites.iter().for_each(|site| {
index.sites[*site].apply_supplement(
&mut dynamic_rng,
chunk_wpos2d,
sample_get,
&mut supplement,
site.id(),
)
});
// Finally, defragment to minimize space consumption.
chunk.defragment();
Ok((chunk, supplement))
}
}