Parallelised rtsim NPC AI

This commit is contained in:
Joshua Barretto 2023-01-05 21:31:20 +00:00
parent 077da13a5f
commit c4032ee024
4 changed files with 85 additions and 75 deletions

1
Cargo.lock generated
View File

@ -6952,6 +6952,7 @@ dependencies = [
"hashbrown 0.12.3",
"itertools",
"rand 0.8.5",
"rayon",
"rmp-serde",
"ron 0.8.0",
"serde",

View File

@ -19,3 +19,4 @@ slotmap = { version = "1.0.6", features = ["serde"] }
rand = { version = "0.8", features = ["small_rng"] }
fxhash = "0.2.1"
itertools = "0.10.3"
rayon = "1.5"

View File

@ -89,7 +89,7 @@ impl Data {
.with_z(world.sim().get_alt_approx(wpos2d).unwrap_or(0.0))
};
if good_or_evil {
for _ in 0..32 {
for _ in 0..250 {
this.npcs.create(
Npc::new(rng.gen(), rand_wpos(&mut rng))
.with_faction(site.faction)
@ -107,7 +107,7 @@ impl Data {
);
}
} else {
for _ in 0..5 {
for _ in 0..15 {
this.npcs.create(
Npc::new(rng.gen(), rand_wpos(&mut rng))
.with_faction(site.faction)

View File

@ -21,6 +21,7 @@ use common::{
use fxhash::FxHasher64;
use itertools::Itertools;
use rand::prelude::*;
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
use std::{
any::{Any, TypeId},
marker::PhantomData,
@ -230,21 +231,27 @@ const MAX_STEP: f32 = 32.0;
impl Rule for NpcAi {
fn start(rtstate: &mut RtState) -> Result<Self, RuleError> {
rtstate.bind::<Self, OnTick>(|mut ctx| {
let npc_ids = ctx.state.data().npcs.keys().collect::<Vec<_>>();
for npc_id in npc_ids {
let mut brain = ctx.state.data_mut().npcs[npc_id]
.brain
.take()
.unwrap_or_else(|| Brain {
let mut npc_data = {
let mut data = ctx.state.data_mut();
data.npcs
.iter_mut()
.map(|(npc_id, npc)| {
let controller = Controller { goto: npc.goto };
let brain = npc.brain.take().unwrap_or_else(|| Brain {
action: Box::new(think().repeat()),
});
(npc_id, controller, brain)
})
.collect::<Vec<_>>()
};
let controller = {
{
let data = &*ctx.state.data();
let npc = &data.npcs[npc_id];
let mut controller = Controller { goto: npc.goto };
npc_data
.par_iter_mut()
.for_each(|(npc_id, controller, brain)| {
let npc = &data.npcs[*npc_id];
brain.action.tick(&mut NpcCtx {
state: ctx.state,
@ -253,9 +260,17 @@ impl Rule for NpcAi {
time_of_day: ctx.event.time_of_day,
time: ctx.event.time,
npc,
npc_id,
controller: &mut controller,
npc_id: *npc_id,
controller,
});
});
}
let mut data = ctx.state.data_mut();
for (npc_id, controller, brain) in npc_data {
data.npcs[npc_id].goto = controller.goto;
data.npcs[npc_id].brain = Some(brain);
}
/*
let action: ControlFlow<()> = try {
@ -301,13 +316,6 @@ impl Rule for NpcAi {
*/
};
*/
controller
};
ctx.state.data_mut().npcs[npc_id].goto = controller.goto;
ctx.state.data_mut().npcs[npc_id].brain = Some(brain);
}
});
Ok(Self)