phase -> execute loop

This commit is contained in:
Jim 2025-09-01 12:08:39 -04:00
parent 83256bfbe5
commit 6c0ac7f66d
Signed by: jim
GPG key ID: 3D7D94BA53088BF4
7 changed files with 273 additions and 35 deletions

2
Cargo.lock generated
View file

@ -3195,6 +3195,7 @@ dependencies = [
"building", "building",
"camera", "camera",
"combat", "combat",
"inhabitant",
"inhabitant_coranth", "inhabitant_coranth",
"physics", "physics",
"resource_graveyard", "resource_graveyard",
@ -5298,6 +5299,7 @@ dependencies = [
"building_placement", "building_placement",
"input", "input",
"resources", "resources",
"state",
"ui_state", "ui_state",
"upgrade", "upgrade",
] ]

View file

@ -3,20 +3,20 @@
MouseButton(Middle): [ MouseButton(Middle): [
CameraOrbitEnable, CameraOrbitEnable,
], ],
MouseButton(Right): [
PlaceTower,
],
MouseButton(Left): [
CameraPanEnable,
],
KeyCode(ShiftLeft): [ KeyCode(ShiftLeft): [
MultiPlaceTower, MultiPlaceTower,
], ],
KeyCode(F1): [
ToggleDebugUI,
],
MouseButton(Right): [
PlaceTower,
],
MouseScroll: [ MouseScroll: [
CameraZoom, CameraZoom,
], ],
KeyCode(F1): [ MouseButton(Left): [
ToggleDebugUI, CameraPanEnable,
], ],
MouseMovementX: [ MouseMovementX: [
CameraYaw, CameraYaw,

View file

@ -13,6 +13,7 @@ camera = { path = "../camera" }
combat = { path = "../combat" } combat = { path = "../combat" }
physics = { path = "../physics" } physics = { path = "../physics" }
building = { path = "../building" } building = { path = "../building" }
inhabitant = { path = "../inhabitant" }
inhabitant_coranth = { path = "../inhabitant_coranth" } inhabitant_coranth = { path = "../inhabitant_coranth" }
resource_graveyard = { path = "../resource_graveyard" } resource_graveyard = { path = "../resource_graveyard" }

View file

@ -14,20 +14,42 @@ use bevy::{
use bevy_egui::PrimaryEguiContext; use bevy_egui::PrimaryEguiContext;
use building::{BuildingTypes, PlaceBuilding}; use building::{BuildingTypes, PlaceBuilding};
use camera::ControlledCamera; use camera::ControlledCamera;
use inhabitant::Inhabitant;
use inhabitant_coranth::SpawnCoranth; use inhabitant_coranth::SpawnCoranth;
use physics::{Ground, PhysicsLayers}; use physics::{Ground, PhysicsLayers};
use resource_graveyard::PlaceGraveyard; use resource_graveyard::PlaceGraveyard;
use state::{AppState, GameSystemSet}; use state::{AppState, BasePhaseState, GameSystemSet, Phase};
pub struct LevelPlugin; pub struct LevelPlugin;
impl Plugin for LevelPlugin { impl Plugin for LevelPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Game), setup) app.init_resource::<ExecuteTimer>()
.add_systems(FixedUpdate, spawn_enemies.in_set(GameSystemSet::Execute)); .add_systems(OnEnter(AppState::Game), setup)
.add_systems(
OnTransition {
exited: Phase::Execute,
entered: Phase::Plan,
},
on_plan,
)
.add_systems(
OnTransition {
exited: Phase::Plan,
entered: Phase::Execute,
},
on_execute,
)
.add_systems(
FixedUpdate,
(spawn_enemies, tick_execute_timer).in_set(GameSystemSet::Execute),
);
} }
} }
#[derive(Resource, Default, Deref, DerefMut)]
pub struct ExecuteTimer(pub Option<Timer>);
fn setup( fn setup(
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
@ -123,3 +145,30 @@ fn spawn_enemies(
} }
} }
} }
fn on_execute(mut timer: ResMut<ExecuteTimer>) {
timer.0 = Some(Timer::from_seconds(5., TimerMode::Once));
}
fn tick_execute_timer(
mut execute_timer: ResMut<ExecuteTimer>,
time: Res<Time>,
curr_phase: Res<State<BasePhaseState>>,
mut next_phase: ResMut<NextState<BasePhaseState>>,
) {
if let Some(timer) = &mut execute_timer.0 {
timer.tick(time.delta());
if timer.finished() {
execute_timer.0 = None;
next_phase.set(BasePhaseState::Plan {
phase: curr_phase.get().phase_count() + 1,
});
}
}
}
fn on_plan(query: Query<Entity, With<Inhabitant>>, mut commands: Commands) {
for entity in query.iter() {
commands.entity(entity).despawn();
}
}

View file

@ -12,8 +12,9 @@ impl Plugin for StatePlugin {
app.init_state::<AppState>() app.init_state::<AppState>()
.enable_state_scoped_entities::<AppState>() .enable_state_scoped_entities::<AppState>()
.add_sub_state::<GameState>() .add_sub_state::<GameState>()
.add_sub_state::<BasePhaseState>()
.enable_state_scoped_entities::<GameState>() .enable_state_scoped_entities::<GameState>()
.add_sub_state::<Phase>() .add_computed_state::<Phase>()
.configure_sets( .configure_sets(
FixedUpdate, FixedUpdate,
GameSystemSet::LoadingTick.run_if(in_state(GameState::Loading)), GameSystemSet::LoadingTick.run_if(in_state(GameState::Loading)),
@ -80,14 +81,48 @@ pub enum GameState {
Paused, Paused,
} }
#[derive(Debug, Clone, Eq, PartialEq, Hash, SubStates, Default)] /// this is what you should set to change the state. do not read this for scheduling
#[source(GameState = GameState::Running)] #[derive(Debug, Clone, Eq, PartialEq, Hash, SubStates)]
#[source(AppState = AppState::Game)]
pub enum BasePhaseState {
Execute { phase: u32 },
Plan { phase: u32 },
}
impl Default for BasePhaseState {
fn default() -> Self {
Self::Plan { phase: 0 }
}
}
impl BasePhaseState {
pub fn phase_count(&self) -> u32 {
match self {
BasePhaseState::Execute { phase } => *phase,
BasePhaseState::Plan { phase } => *phase,
}
}
}
/// this is what you should read, as it takes into account the game state
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Phase { pub enum Phase {
#[default]
Execute, Execute,
Plan, Plan,
} }
impl ComputedStates for Phase {
type SourceStates = (BasePhaseState, GameState);
fn compute(sources: Self::SourceStates) -> Option<Self> {
match sources {
(_, GameState::Loading) | (_, GameState::Paused) => None,
(BasePhaseState::Execute { .. }, GameState::Running) => Some(Self::Execute),
(BasePhaseState::Plan { .. }, GameState::Running) => Some(Self::Plan),
}
}
}
#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)] #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
pub enum GameSystemSet { pub enum GameSystemSet {
// fixed update - contains all gameplay logic. does not run when game is paused // fixed update - contains all gameplay logic. does not run when game is paused

View file

@ -8,6 +8,7 @@ bevy = { workspace = true }
bevy_egui = { workspace = true } bevy_egui = { workspace = true }
ui_state = { path = "../ui_state" } ui_state = { path = "../ui_state" }
state = { path = "../state" }
resources = { path = "../resources" } resources = { path = "../resources" }
building = { path = "../building" } building = { path = "../building" }
input = { path = "../input" } input = { path = "../input" }

View file

@ -2,6 +2,8 @@
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use std::time::Duration;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_egui::{ use bevy_egui::{
EguiContexts, EguiPrimaryContextPass, EguiContexts, EguiPrimaryContextPass,
@ -11,6 +13,7 @@ use building::BuildingInfo;
use building_placement::SelectBuildingPreview; use building_placement::SelectBuildingPreview;
use input::{SelectEntity, Selected}; use input::{SelectEntity, Selected};
use resources::{AvailableWorkers, Cost, ResourceDeposit, Resources, WorkedResourceDeposit}; use resources::{AvailableWorkers, Cost, ResourceDeposit, Resources, WorkedResourceDeposit};
use state::{BasePhaseState, Phase};
use ui_state::GameUIState; use ui_state::GameUIState;
use upgrade::{UnlockUpgrade, Upgradable, Upgrade}; use upgrade::{UnlockUpgrade, Upgradable, Upgrade};
@ -18,14 +21,161 @@ pub struct UiIngamePlugin;
impl Plugin for UiIngamePlugin { impl Plugin for UiIngamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems( app.init_state::<PhaseTransitionState>()
EguiPrimaryContextPass, .init_resource::<TransitionTimer>()
resource_ui.run_if(in_state(GameUIState::Default)), .add_systems(
); EguiPrimaryContextPass,
(
side_panel.run_if(in_state(GameUIState::Default)),
plan_ui.run_if(in_state(GameUIState::Default).and(in_state(Phase::Plan))),
execute_ui.run_if(in_state(GameUIState::Default).and(in_state(Phase::Execute))),
transition_ui.run_if(
in_state(GameUIState::Default).and(
not(in_state(PhaseTransitionState::None))
.and(state_exists::<BasePhaseState>),
),
),
),
)
//doing ontransition since this is a substate. otherwise, shows up every time you unpause
.add_systems(
OnTransition {
exited: Phase::Plan,
entered: Phase::Execute,
},
execute_transition,
)
.add_systems(
OnTransition {
exited: Phase::Execute,
entered: Phase::Plan,
},
plan_transition,
);
} }
} }
fn resource_ui( const LARGE_FONT_SIZE: f32 = 24.;
const FONT_SIZE: f32 = 16.;
#[derive(States, Default, Debug, Clone, PartialEq, Eq, Hash)]
enum PhaseTransitionState {
#[default]
None,
ToExecute,
ToPlan,
}
fn plan_ui(
mut contexts: EguiContexts,
curr_phase: Res<State<BasePhaseState>>,
mut next_phase: ResMut<NextState<BasePhaseState>>,
) {
let ctx = contexts.ctx_mut().unwrap();
egui::Window::new("PlanUI")
.resizable(false)
.collapsible(false)
.title_bar(false)
.anchor(Align2::CENTER_BOTTOM, [0., 0.])
.show(ctx, |ui| {
if ui
.button(RichText::new("EXECUTE").size(LARGE_FONT_SIZE))
.clicked()
{
next_phase.set(BasePhaseState::Execute {
phase: curr_phase.get().phase_count(),
});
}
});
}
fn execute_ui(
mut contexts: EguiContexts,
curr_phase: Res<State<BasePhaseState>>,
mut next_phase: ResMut<NextState<BasePhaseState>>,
) {
let ctx = contexts.ctx_mut().unwrap();
egui::Window::new("ExecuteUI")
.resizable(false)
.collapsible(false)
.title_bar(false)
.anchor(Align2::CENTER_TOP, [0., 0.])
.show(ctx, |ui| {
// todo - remove this
if ui
.button(RichText::new("DEBUG - PLAN").size(LARGE_FONT_SIZE))
.clicked()
{
next_phase.set(BasePhaseState::Plan {
phase: curr_phase.get().phase_count() + 1,
});
}
});
}
#[derive(Resource, DerefMut, Deref)]
struct TransitionTimer(Timer);
impl Default for TransitionTimer {
fn default() -> Self {
Self(Timer::new(Duration::from_secs(1), TimerMode::Once))
}
}
fn execute_transition(
mut next_transition: ResMut<NextState<PhaseTransitionState>>,
mut timer: ResMut<TransitionTimer>,
) {
next_transition.set(PhaseTransitionState::ToExecute);
timer.reset();
}
fn plan_transition(
mut next_transition: ResMut<NextState<PhaseTransitionState>>,
mut timer: ResMut<TransitionTimer>,
) {
next_transition.set(PhaseTransitionState::ToPlan);
timer.reset();
}
fn transition_ui(
mut contexts: EguiContexts,
curr_transition: Res<State<PhaseTransitionState>>,
mut next_transition: ResMut<NextState<PhaseTransitionState>>,
curr_state: Res<State<BasePhaseState>>,
time: Res<Time>,
mut timer: ResMut<TransitionTimer>,
) {
let ctx = contexts.ctx_mut().unwrap();
timer.tick(time.delta());
if timer.finished() {
next_transition.set(PhaseTransitionState::None);
timer.reset();
return;
}
egui::Window::new("TRANSITION")
.resizable(false)
.collapsible(false)
.title_bar(false)
.anchor(Align2::CENTER_CENTER, [0., 0.])
.show(ctx, |ui| {
ui.label(
RichText::new(format!(
"{} {}",
match curr_transition.get() {
PhaseTransitionState::None => "WHAT",
PhaseTransitionState::ToExecute => "EXECUTE",
PhaseTransitionState::ToPlan => "PLAN",
},
curr_state.get().phase_count()
))
.size(64.),
);
});
}
fn side_panel(
mut contexts: EguiContexts, mut contexts: EguiContexts,
mut commands: Commands, mut commands: Commands,
resources: Res<Resources>, resources: Res<Resources>,
@ -39,14 +189,13 @@ fn resource_ui(
mut select_writer: EventWriter<SelectEntity>, mut select_writer: EventWriter<SelectEntity>,
) { ) {
let ctx = contexts.ctx_mut().unwrap(); let ctx = contexts.ctx_mut().unwrap();
let large_font_size = 24.;
let font_size = 16.;
egui::Window::new("Resources") egui::Window::new("Resources")
.resizable(false) .resizable(false)
.collapsible(false) .collapsible(false)
.title_bar(false) .title_bar(false)
.anchor(Align2::RIGHT_TOP, [0., 0.]) .anchor(Align2::RIGHT_TOP, [0., 0.])
.show(ctx, |ui| { .show(ctx, |ui| {
// --- view when object selected ---
if let Ok((selected, selected_name)) = selected.single() { if let Ok((selected, selected_name)) = selected.single() {
if ui.button("x").clicked() { if ui.button("x").clicked() {
select_writer.write(SelectEntity(None)); select_writer.write(SelectEntity(None));
@ -56,7 +205,7 @@ fn resource_ui(
// resource deposit management // resource deposit management
if let Ok((deposit, mut opt_worked)) = selected_resource_deposit.get_mut(selected) { if let Ok((deposit, mut opt_worked)) = selected_resource_deposit.get_mut(selected) {
ui.label( ui.label(
RichText::new(format!("Level {} deposit", deposit.level)).size(font_size), RichText::new(format!("Level {} deposit", deposit.level)).size(FONT_SIZE),
); );
ui.heading( ui.heading(
RichText::new(if let Some(ref worked) = opt_worked { RichText::new(if let Some(ref worked) = opt_worked {
@ -64,7 +213,7 @@ fn resource_ui(
} else { } else {
"Not worked".to_string() "Not worked".to_string()
}) })
.size(large_font_size) .size(LARGE_FONT_SIZE)
.underline(), .underline(),
); );
// worker management buttons // worker management buttons
@ -96,10 +245,10 @@ fn resource_ui(
} }
ui.heading(RichText::new("Bounty").underline()); ui.heading(RichText::new("Bounty").underline());
ui.label( ui.label(
RichText::new(format!("Souls: {}", deposit.bounty.souls)).size(font_size), RichText::new(format!("Souls: {}", deposit.bounty.souls)).size(FONT_SIZE),
); );
ui.label( ui.label(
RichText::new(format!("Bones: {}", deposit.bounty.bones)).size(font_size), RichText::new(format!("Bones: {}", deposit.bounty.bones)).size(FONT_SIZE),
); );
} }
@ -118,7 +267,7 @@ fn resource_ui(
.filter_map(|u| upgrades.get(*u).map(|(up, n)| (*u, up, n)).ok()) .filter_map(|u| upgrades.get(*u).map(|(up, n)| (*u, up, n)).ok())
{ {
if ui if ui
.button(RichText::new(upgrade_name.as_str()).size(large_font_size)) .button(RichText::new(upgrade_name.as_str()).size(LARGE_FONT_SIZE))
.clicked() .clicked()
{ {
commands.trigger_targets( commands.trigger_targets(
@ -126,8 +275,8 @@ fn resource_ui(
upgrade_entity, upgrade_entity,
); );
} }
ui.label(RichText::new(upgrade.description.as_str()).size(font_size)); ui.label(RichText::new(upgrade.description.as_str()).size(FONT_SIZE));
ui.label(RichText::new(upgrade.cost.to_string()).size(font_size)); ui.label(RichText::new(upgrade.cost.to_string()).size(FONT_SIZE));
} }
if !active_upgrades.is_empty() { if !active_upgrades.is_empty() {
ui.collapsing("Active Upgrades", |ui| { ui.collapsing("Active Upgrades", |ui| {
@ -135,20 +284,21 @@ fn resource_ui(
active_upgrades.iter().filter_map(|u| upgrades.get(*u).ok()) active_upgrades.iter().filter_map(|u| upgrades.get(*u).ok())
{ {
ui.label( ui.label(
RichText::new(upgrade_name.as_str()).size(large_font_size), RichText::new(upgrade_name.as_str()).size(LARGE_FONT_SIZE),
); );
ui.label( ui.label(
RichText::new(upgrade.description.as_str()).size(font_size), RichText::new(upgrade.description.as_str()).size(FONT_SIZE),
); );
ui.label(RichText::new(upgrade.cost.to_string()).size(font_size)); ui.label(RichText::new(upgrade.cost.to_string()).size(FONT_SIZE));
} }
}); });
} }
} }
return; return;
} }
ui.label(RichText::new(format!("Souls: {}", resources.souls)).size(large_font_size)); // --- view when nothing's selected ---
ui.label(RichText::new(format!("Bones: {}", resources.bones)).size(large_font_size)); ui.label(RichText::new(format!("Souls: {}", resources.souls)).size(LARGE_FONT_SIZE));
ui.label(RichText::new(format!("Bones: {}", resources.bones)).size(LARGE_FONT_SIZE));
ui.heading(RichText::new("Buildings").underline()); ui.heading(RichText::new("Buildings").underline());
for (info, cost, name) in buildings.iter() { for (info, cost, name) in buildings.iter() {
if !info.unlocked { if !info.unlocked {
@ -157,7 +307,7 @@ fn resource_ui(
if ui if ui
.button( .button(
RichText::new(format!("{} - {}", name, cost.0.to_string())).size(font_size), RichText::new(format!("{} - {}", name, cost.0.to_string())).size(FONT_SIZE),
) )
.clicked() .clicked()
{ {