Cleaning up

This commit is contained in:
Joshua Barretto 2023-04-01 00:56:06 +01:00
parent 6035234c6e
commit ea007ff702
14 changed files with 31 additions and 127 deletions

View File

@ -526,7 +526,7 @@ impl State {
// Apply terrain changes // Apply terrain changes
pub fn apply_terrain_changes( pub fn apply_terrain_changes(
&self, &self,
mut block_update: impl FnMut(&specs::World, Vec3<i32>, Block, Block), block_update: impl FnMut(&specs::World, Vec3<i32>, Block, Block),
) { ) {
self.apply_terrain_changes_internal(false, block_update); self.apply_terrain_changes_internal(false, block_update);
} }

View File

@ -1392,7 +1392,6 @@ fn box_voxel_collision<T: BaseVol<Vox = Block> + ReadVol>(
near_aabb: Aabb<i32>, near_aabb: Aabb<i32>,
radius: f32, radius: f32,
z_range: Range<f32>, z_range: Range<f32>,
scale: f32,
) -> bool { ) -> bool {
let player_aabb = player_aabb(pos, radius, z_range); let player_aabb = player_aabb(pos, radius, z_range);
@ -1558,7 +1557,6 @@ fn box_voxel_collision<T: BaseVol<Vox = Block> + ReadVol>(
near_aabb, near_aabb,
radius, radius,
z_range.clone(), z_range.clone(),
scale,
) )
} }
// ...and there is a collision with a block beneath our current hitbox... // ...and there is a collision with a block beneath our current hitbox...
@ -1571,7 +1569,6 @@ fn box_voxel_collision<T: BaseVol<Vox = Block> + ReadVol>(
near_aabb, near_aabb,
radius, radius,
z_range.clone(), z_range.clone(),
scale,
) )
} { } {
// ...block-hop! // ...block-hop!
@ -1626,7 +1623,6 @@ fn box_voxel_collision<T: BaseVol<Vox = Block> + ReadVol>(
near_aabb, near_aabb,
radius, radius,
z_range.clone(), z_range.clone(),
scale,
) )
} { } {
//prof_span!("snap!!"); //prof_span!("snap!!");

View File

@ -210,6 +210,8 @@ fn path_towns(
impl Rule for NpcAi { impl Rule for NpcAi {
fn start(rtstate: &mut RtState) -> Result<Self, RuleError> { fn start(rtstate: &mut RtState) -> Result<Self, RuleError> {
rtstate.bind::<Self, OnTick>(|ctx| { rtstate.bind::<Self, OnTick>(|ctx| {
// Temporarily take the brains of NPCs out of their heads to appease the borrow
// checker
let mut npc_data = { let mut npc_data = {
let mut data = ctx.state.data_mut(); let mut data = ctx.state.data_mut();
data.npcs data.npcs
@ -224,6 +226,7 @@ impl Rule for NpcAi {
.collect::<Vec<_>>() .collect::<Vec<_>>()
}; };
// Do a little thinking
{ {
let data = &*ctx.state.data(); let data = &*ctx.state.data();
@ -245,56 +248,12 @@ impl Rule for NpcAi {
}); });
} }
// Reinsert NPC brains
let mut data = ctx.state.data_mut(); let mut data = ctx.state.data_mut();
for (npc_id, controller, brain) in npc_data { for (npc_id, controller, brain) in npc_data {
data.npcs[npc_id].action = controller.action; data.npcs[npc_id].action = controller.action;
data.npcs[npc_id].brain = Some(brain); data.npcs[npc_id].brain = Some(brain);
} }
/*
let action: ControlFlow<()> = try {
brain.tick(&mut NpcData {
ctx: &ctx,
npc,
npc_id,
controller: &mut controller,
});
/*
// // Choose a random plaza in the npcs home site (which should be the
// // current here) to go to.
let task =
generate(move |(_, npc, ctx): &(NpcId, &Npc, &EventCtx<_, _>)| {
let data = ctx.state.data();
let site2 =
npc.home.and_then(|home| data.sites.get(home)).and_then(
|home| match &ctx.index.sites.get(home.world_site?).kind
{
SiteKind::Refactor(site2)
| SiteKind::CliffTown(site2)
| SiteKind::DesertCity(site2) => Some(site2),
_ => None,
},
);
let wpos = site2
.and_then(|site2| {
let plaza = &site2.plots
[site2.plazas().choose(&mut thread_rng())?];
Some(site2.tile_center_wpos(plaza.root_tile()).as_())
})
.unwrap_or(npc.wpos.xy());
TravelTo {
wpos,
use_paths: true,
}
})
.repeat();
task_state.perform(task, &(npc_id, &*npc, &ctx), &mut controller)?;
*/
};
*/
}); });
Ok(Self) Ok(Self)
@ -371,16 +330,12 @@ where
site_exit = next; site_exit = next;
} }
// println!("[NPC {:?}] Pathing in site...", ctx.npc_id);
if let Some(path) = path_site(wpos, site_exit, site, ctx.index) { if let Some(path) = path_site(wpos, site_exit, site, ctx.index) {
// println!("[NPC {:?}] Found path of length {} from {:?} to {:?}!", ctx.npc_id,
// path.len(), wpos, site_exit);
Some(itertools::Either::Left( Some(itertools::Either::Left(
seq(path.into_iter().map(|wpos| goto_2d(wpos, 1.0, 8.0))) seq(path.into_iter().map(|wpos| goto_2d(wpos, 1.0, 8.0)))
.then(goto_2d(site_exit, 1.0, 8.0)), .then(goto_2d(site_exit, 1.0, 8.0)),
)) ))
} else { } else {
// println!("[NPC {:?}] No path", ctx.npc_id);
Some(itertools::Either::Right(goto_2d(site_exit, 1.0, 8.0))) Some(itertools::Either::Right(goto_2d(site_exit, 1.0, 8.0)))
} }
} else { } else {
@ -395,13 +350,9 @@ fn travel_to_point(wpos: Vec2<f32>) -> impl Action {
const WAYPOINT: f32 = 24.0; const WAYPOINT: f32 = 24.0;
let start = ctx.npc.wpos.xy(); let start = ctx.npc.wpos.xy();
let diff = wpos - start; let diff = wpos - start;
// if diff.magnitude() > 1.0 {
let n = (diff.magnitude() / WAYPOINT).max(1.0); let n = (diff.magnitude() / WAYPOINT).max(1.0);
let mut points = (1..n as usize + 1).map(move |i| start + diff * (i as f32 / n)); let mut points = (1..n as usize + 1).map(move |i| start + diff * (i as f32 / n));
traverse_points(move |_| points.next()).boxed() traverse_points(move |_| points.next()).boxed()
// } else {
// finish().boxed()
// }
}) })
.debug(|| "travel to point") .debug(|| "travel to point")
} }
@ -858,18 +809,3 @@ fn think() -> impl Action {
_ => casual(idle()), _ => casual(idle()),
}) })
} }
// if !matches!(stages.front(), Some(TravelStage::IntraSite { .. })) {
// let data = ctx.state.data();
// if let Some((site2, site)) = npc
// .current_site
// .and_then(|current_site| data.sites.get(current_site))
// .and_then(|site| site.world_site)
// .and_then(|site| Some((get_site2(site)?, site)))
// {
// let end = site2.wpos_tile_pos(self.wpos.as_());
// if let Some(path) = path_town(npc.wpos, site, ctx.index, |_|
// Some(end)) { stages.push_front(TravelStage::IntraSite { path,
// site }); }
// }
// }

View File

@ -1218,7 +1218,7 @@ fn handle_rtsim_tp(
fn handle_rtsim_info( fn handle_rtsim_info(
server: &mut Server, server: &mut Server,
client: EcsEntity, client: EcsEntity,
target: EcsEntity, _target: EcsEntity,
args: Vec<String>, args: Vec<String>,
action: &ServerChatCommand, action: &ServerChatCommand,
) -> CmdResult<()> { ) -> CmdResult<()> {
@ -1267,7 +1267,7 @@ fn handle_rtsim_info(
fn handle_rtsim_purge( fn handle_rtsim_purge(
server: &mut Server, server: &mut Server,
client: EcsEntity, client: EcsEntity,
target: EcsEntity, _target: EcsEntity,
args: Vec<String>, args: Vec<String>,
action: &ServerChatCommand, action: &ServerChatCommand,
) -> CmdResult<()> { ) -> CmdResult<()> {
@ -1298,8 +1298,8 @@ fn handle_rtsim_chunk(
server: &mut Server, server: &mut Server,
client: EcsEntity, client: EcsEntity,
target: EcsEntity, target: EcsEntity,
args: Vec<String>, _args: Vec<String>,
action: &ServerChatCommand, _action: &ServerChatCommand,
) -> CmdResult<()> { ) -> CmdResult<()> {
use crate::rtsim::{ChunkStates, RtSim}; use crate::rtsim::{ChunkStates, RtSim};
let pos = position(server, target, "target")?; let pos = position(server, target, "target")?;

View File

@ -6,20 +6,17 @@ use common::{
character::CharacterId, character::CharacterId,
comp::{ comp::{
self, self,
agent::pid_coefficients,
aura::{Aura, AuraKind, AuraTarget}, aura::{Aura, AuraKind, AuraTarget},
beam, beam,
buff::{BuffCategory, BuffData, BuffKind, BuffSource}, buff::{BuffCategory, BuffData, BuffKind, BuffSource},
shockwave, Agent, Alignment, Anchor, BehaviorCapability, Body, Health, Inventory, ItemDrop, shockwave, Alignment, BehaviorCapability, Body, ItemDrop, LightEmitter, Object, Ori, Pos,
LightEmitter, Object, Ori, PidController, Poise, Pos, Projectile, Scale, SkillSet, Stats, Projectile, TradingBehavior, Vel, WaypointArea,
TradingBehavior, Vel, WaypointArea,
}, },
event::{EventBus, NpcBuilder, UpdateCharacterMetadata}, event::{EventBus, NpcBuilder, UpdateCharacterMetadata},
lottery::LootSpec,
mounting::Mounting, mounting::Mounting,
outcome::Outcome, outcome::Outcome,
resources::{Secs, Time}, resources::{Secs, Time},
rtsim::{RtSimEntity, RtSimVehicle}, rtsim::RtSimVehicle,
uid::Uid, uid::Uid,
util::Dir, util::Dir,
ViewDistances, ViewDistances,

View File

@ -27,7 +27,7 @@ use common::{
outcome::{HealthChangeInfo, Outcome}, outcome::{HealthChangeInfo, Outcome},
resources::{Secs, Time}, resources::{Secs, Time},
rtsim::RtSimEntity, rtsim::RtSimEntity,
states::utils::{AbilityInfo, StageSection}, states::utils::StageSection,
terrain::{Block, BlockKind, TerrainGrid}, terrain::{Block, BlockKind, TerrainGrid},
uid::{Uid, UidAllocator}, uid::{Uid, UidAllocator},
util::Dir, util::Dir,

View File

@ -7,8 +7,7 @@
let_chains, let_chains,
never_type, never_type,
option_zip, option_zip,
unwrap_infallible, unwrap_infallible
explicit_generic_args_with_impl_trait
)] )]
#![feature(hash_drain_filter)] #![feature(hash_drain_filter)]
@ -1464,7 +1463,7 @@ impl Drop for Server {
#[cfg(feature = "worldgen")] #[cfg(feature = "worldgen")]
{ {
info!("Saving rtsim state..."); debug!("Saving rtsim state...");
self.state.ecs().write_resource::<rtsim::RtSim>().save(true); self.state.ecs().write_resource::<rtsim::RtSim>().save(true);
} }
} }

View File

@ -5,25 +5,21 @@ pub mod tick;
use common::{ use common::{
grid::Grid, grid::Grid,
rtsim::{ChunkResource, RtSimEntity, RtSimVehicle, WorldSettings}, rtsim::{ChunkResource, RtSimEntity, RtSimVehicle, WorldSettings},
slowjob::SlowJobPool, terrain::Block,
terrain::{Block, TerrainChunk},
vol::RectRasterableVol,
}; };
use common_ecs::{dispatch, System}; use common_ecs::dispatch;
use enum_map::EnumMap; use enum_map::EnumMap;
use rtsim::{ use rtsim::{
data::{npc::SimulationMode, Data, ReadError}, data::{npc::SimulationMode, Data},
event::{OnDeath, OnSetup}, event::{OnDeath, OnSetup},
rule::Rule,
RtState, RtState,
}; };
use specs::{DispatcherBuilder, WorldExt}; use specs::DispatcherBuilder;
use std::{ use std::{
error::Error, error::Error,
fs::{self, File}, fs::{self, File},
io::{self, Write}, io::{self, Write},
path::PathBuf, path::PathBuf,
sync::Arc,
time::Instant, time::Instant,
}; };
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};

View File

@ -1,8 +1,5 @@
use crate::rtsim::{event::OnBlockChange, ChunkStates}; use crate::rtsim::{event::OnBlockChange, ChunkStates};
use common::{ use common::terrain::CoordinateConversions;
terrain::{CoordinateConversions, TerrainChunk},
vol::RectRasterableVol,
};
use rtsim::{RtState, Rule, RuleError}; use rtsim::{RtState, Rule, RuleError};
pub struct DepleteResources; pub struct DepleteResources;
@ -22,7 +19,7 @@ impl Rule for DepleteResources {
/ chunk_state.max_res[res] as f32; / chunk_state.max_res[res] as f32;
} }
} }
// Add resources // Replenish resources
if let Some(res) = ctx.event.new.get_rtsim_resource() { if let Some(res) = ctx.event.new.get_rtsim_resource() {
if chunk_state.max_res[res] > 0 { if chunk_state.max_res[res] > 0 {
chunk_res[res] = (chunk_res[res] * chunk_state.max_res[res] as f32 + 1.0) chunk_res[res] = (chunk_res[res] * chunk_state.max_res[res] as f32 + 1.0)
@ -31,7 +28,7 @@ impl Rule for DepleteResources {
/ chunk_state.max_res[res] as f32; / chunk_state.max_res[res] as f32;
} }
} }
//println!("Chunk resources = {:?}", chunk_res);
ctx.state ctx.state
.data_mut() .data_mut()
.nature .nature

View File

@ -3,16 +3,15 @@
use super::*; use super::*;
use crate::sys::terrain::NpcData; use crate::sys::terrain::NpcData;
use common::{ use common::{
comp::{self, inventory::loadout::Loadout, skillset::skills, Agent, Body}, comp::{self, Body},
event::{EventBus, NpcBuilder, ServerEvent}, event::{EventBus, NpcBuilder, ServerEvent},
generation::{BodyBuilder, EntityConfig, EntityInfo}, generation::{BodyBuilder, EntityConfig, EntityInfo},
lottery::LootSpec,
resources::{DeltaTime, Time, TimeOfDay}, resources::{DeltaTime, Time, TimeOfDay},
rtsim::{RtSimController, RtSimEntity, RtSimVehicle}, rtsim::{RtSimEntity, RtSimVehicle},
slowjob::SlowJobPool, slowjob::SlowJobPool,
terrain::CoordinateConversions, terrain::CoordinateConversions,
trade::{Good, SiteInformation}, trade::{Good, SiteInformation},
LoadoutBuilder, SkillSetBuilder, LoadoutBuilder,
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use rtsim::data::{ use rtsim::data::{

View File

@ -769,12 +769,12 @@ fn do_combat(bdata: &mut BehaviorData) -> bool {
} }
fn remembers_fight_with( fn remembers_fight_with(
rtsim_entity: Option<&RtSimEntity>, _rtsim_entity: Option<&RtSimEntity>,
read_data: &ReadData, _read_data: &ReadData,
other: EcsEntity, _other: EcsEntity,
) -> bool { ) -> bool {
// TODO: implement for rtsim2 // TODO: implement for rtsim2
let name = || read_data.stats.get(other).map(|stats| stats.name.clone()); // let name = || read_data.stats.get(other).map(|stats| stats.name.clone());
// rtsim_entity.map_or(false, |rtsim_entity| { // rtsim_entity.map_or(false, |rtsim_entity| {
// name().map_or(false, |name| { // name().map_or(false, |name| {

View File

@ -539,22 +539,6 @@ impl Scene {
.get(scene_data.viewpoint_entity) .get(scene_data.viewpoint_entity)
.map_or(1.0, |scale| scale.0); .map_or(1.0, |scale| scale.0);
let viewpoint_rolling = ecs
.read_storage::<comp::CharacterState>()
.get(scene_data.viewpoint_entity)
.map_or(false, |cs| cs.is_dodge());
let is_running = ecs
.read_storage::<comp::Vel>()
.get(scene_data.viewpoint_entity)
.map(|v| v.0.magnitude_squared() > RUNNING_THRESHOLD.powi(2))
.unwrap_or(false);
let on_ground = ecs
.read_storage::<comp::PhysicsState>()
.get(scene_data.viewpoint_entity)
.map(|p| p.on_ground.is_some());
let (is_humanoid, viewpoint_height, viewpoint_eye_height) = scene_data let (is_humanoid, viewpoint_height, viewpoint_eye_height) = scene_data
.state .state
.ecs() .ecs()

View File

@ -30,7 +30,7 @@ pub fn density_factor_by_altitude(lower_limit: f32, altitude: f32, upper_limit:
const MUSH_FACT: f32 = 1.0e-4; // To balance things around the mushroom spawning rate const MUSH_FACT: f32 = 1.0e-4; // To balance things around the mushroom spawning rate
const GRASS_FACT: f32 = 1.0e-3; // To balance things around the grass spawning rate const GRASS_FACT: f32 = 1.0e-3; // To balance things around the grass spawning rate
const DEPTH_WATER_NORM: f32 = 15.0; // Water depth at which regular underwater sprites start spawning const DEPTH_WATER_NORM: f32 = 15.0; // Water depth at which regular underwater sprites start spawning
pub fn apply_scatter_to(canvas: &mut Canvas, rng: &mut impl Rng, calendar: Option<&Calendar>) { pub fn apply_scatter_to(canvas: &mut Canvas, _rng: &mut impl Rng, calendar: Option<&Calendar>) {
enum WaterMode { enum WaterMode {
Underwater, Underwater,
Floating, Floating,

View File

@ -500,7 +500,7 @@ impl World {
rtsim_resource_blocks.sort_unstable_by_key(|pos| pos.into_array()); rtsim_resource_blocks.sort_unstable_by_key(|pos| pos.into_array());
rtsim_resource_blocks.dedup(); rtsim_resource_blocks.dedup();
for wpos in rtsim_resource_blocks { for wpos in rtsim_resource_blocks {
chunk.map(wpos - chunk_wpos2d.with_z(0), |block| { let _ = chunk.map(wpos - chunk_wpos2d.with_z(0), |block| {
if let Some(res) = block.get_rtsim_resource() { if let Some(res) = block.get_rtsim_resource() {
// Note: this represents the upper limit, not the actual number spanwed, so // Note: this represents the upper limit, not the actual number spanwed, so
// we increment this before deciding whether we're going to spawn the // we increment this before deciding whether we're going to spawn the