Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 2 additions & 164 deletions .config/nextest.toml

Large diffs are not rendered by default.

25 changes: 6 additions & 19 deletions astraweave-ai/src/ecs_ai_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ use astraweave_core::{
};
use astraweave_ecs as ecs;

use crate::orchestrator::Orchestrator;
#[cfg(not(feature = "veilweaver_slice"))]
use crate::orchestrator::RuleOrchestrator;
#[cfg(feature = "veilweaver_slice")]
use crate::VeilweaverCompanionOrchestrator;
use crate::orchestrator::{Orchestrator, RuleOrchestrator};

pub struct AiPlanningPlugin;

Expand Down Expand Up @@ -101,9 +97,11 @@ fn sys_ai_planning(world: &mut ecs::World) {
}
}

#[cfg(feature = "veilweaver_slice")]
let orch: Box<dyn Orchestrator> = Box::new(VeilweaverCompanionOrchestrator::new());
#[cfg(not(feature = "veilweaver_slice"))]
// Always the rule planner. `veilweaver_slice` is enabled for the whole
// workspace resolve because `veilweaver_slice_runtime` turns that feature
// on, and `VeilweaverCompanionOrchestrator` does not emit `MoveTo` for a
// companion already near the player. The slice constructs that orchestrator
// itself (`veilweaver_slice_runtime/src/companion_ai.rs`).
let orch: Box<dyn Orchestrator> = Box::new(RuleOrchestrator);
let mut updates: Vec<(ecs::Entity, CDesiredPos)> = vec![];
let mut planned_events: Vec<AiPlannedEvent> = vec![];
Expand Down Expand Up @@ -355,7 +353,6 @@ mod tests {
use anyhow::Result;
use astraweave_core::{IVec2, World};

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn ai_plugin_sets_desired_position_for_companion() -> Result<()> {
// Legacy world can be empty for this test
Expand Down Expand Up @@ -544,7 +541,6 @@ mod tests {
Ok(())
}

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_ai_component_queries() -> Result<()> {
// Verify system correctly queries ECS components
Expand Down Expand Up @@ -1024,7 +1020,6 @@ mod tests {
// sys_ai_planning Legacy World Path Tests (4 tests)
// =============================================================================

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_sys_ai_planning_no_legacy_world() -> Result<()> {
// Verify ECS-only snapshot path when no legacy World resource
Expand Down Expand Up @@ -1071,7 +1066,6 @@ mod tests {
Ok(())
}

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_sys_ai_planning_no_player_in_legacy() -> Result<()> {
// Verify system handles missing player in legacy World
Expand Down Expand Up @@ -1119,7 +1113,6 @@ mod tests {
Ok(())
}

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_sys_ai_planning_no_companion_in_legacy() -> Result<()> {
// Verify system handles missing companion in legacy World
Expand Down Expand Up @@ -1360,7 +1353,6 @@ mod tests {
// ECS-Only Snapshot Path Tests (3 tests)
// =============================================================================

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_ecs_only_snapshot_multiple_allies() -> Result<()> {
// Verify ECS-only path handles multiple companions
Expand Down Expand Up @@ -1455,7 +1447,6 @@ mod tests {
Ok(())
}

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_ecs_only_snapshot_cooldowns_conversion() -> Result<()> {
// Verify ECS-only path converts cooldowns to BTreeMap<String, f32>
Expand Down Expand Up @@ -1500,7 +1491,6 @@ mod tests {
Ok(())
}

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_ecs_only_snapshot_enemy_filtering() -> Result<()> {
// Verify ECS-only path correctly filters team 2 as enemies
Expand Down Expand Up @@ -1572,7 +1562,6 @@ mod tests {
// Event Generation Tests (2 tests)
// =============================================================================

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_ai_planned_event_contents() -> Result<()> {
// Verify AiPlannedEvent has correct entity and target
Expand Down Expand Up @@ -1667,7 +1656,6 @@ mod tests {
// Component Query Edge Cases (2 tests)
// =============================================================================

#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_sys_ai_planning_missing_components() -> Result<()> {
// Verify system handles entities missing CAmmo or CCooldowns
Expand Down Expand Up @@ -1917,7 +1905,6 @@ mod tests {
/// are only written when the vec is empty (discarding real plans).
/// This test verifies that when a legacy world has enemies and planning
/// produces a MoveTo, CDesiredPos is actually written to the bridged ECS entity.
#[cfg(not(feature = "veilweaver_slice"))]
#[test]
fn test_sys_ai_planning_writes_desired_pos_when_updates_nonempty() -> Result<()> {
use astraweave_core::ecs_bridge::EntityBridge;
Expand Down
52 changes: 32 additions & 20 deletions astraweave-audio/src/dialogue_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ pub struct DialogueAudioMap {
pub map: HashMap<String, HashMap<String, String>>,
}

/// `.ogg` and `.wav` files in `folder`, sorted by path.
///
/// Directory order is not stable across operating systems. The playback
/// pick is still random; the candidate set is not.
pub fn voice_folder_candidates(folder: &Path) -> Vec<std::path::PathBuf> {
let Ok(rd) = fs::read_dir(folder) else {
return Vec::new();
};
let mut pool = Vec::new();
for entry in rd.flatten() {
let path = entry.path();
let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else {
continue;
};
if ext.eq_ignore_ascii_case("ogg") || ext.eq_ignore_ascii_case("wav") {
pool.push(path);
}
}
pool.sort();
pool
}

pub fn load_dialogue_audio_map(path: &str) -> Result<DialogueAudioMap> {
let txt = fs::read_to_string(path)?;
let m: DialogueAudioMap = toml::from_str(&txt)?;
Expand Down Expand Up @@ -68,26 +90,16 @@ impl<'a> DialoguePlayer<'a> {
}
} else {
// or any .ogg/.wav in folder
if let Ok(rd) = fs::read_dir(&vspec.folder) {
let mut pool: Vec<String> = vec![];
for e in rd.flatten() {
if let Some(ext) = e.path().extension() {
if ext == "ogg" || ext == "wav" {
pool.push(e.path().to_string_lossy().to_string());
}
}
}
if !pool.is_empty() {
let mut rng = rand::rng();
// INVARIANT: pool is non-empty (checked above), so choose always returns Some
#[allow(clippy::expect_used)]
let path = pool
.choose(&mut rng)
.expect("BUG: pool should have items after is_empty check")
.clone();
self.audio.play_voice_file(&path, None)?;
return Ok(true);
}
let pool = voice_folder_candidates(Path::new(&vspec.folder));
if !pool.is_empty() {
let mut rng = rand::rng();
// INVARIANT: pool is non-empty (checked above), so choose always returns Some
#[allow(clippy::expect_used)]
let path = pool
.choose(&mut rng)
.expect("BUG: pool should have items after is_empty check");
self.audio.play_voice_file(&path.to_string_lossy(), None)?;
return Ok(true);
}
}

Expand Down
41 changes: 28 additions & 13 deletions astraweave-audio/tests/dialogue_file_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,11 +450,30 @@ fn test_folder_scan_filters_non_audio() -> Result<()> {
let bank = create_test_voice_bank_folder_scan()?;
let mut audio_engine = AudioEngine::new()?;

// Check that readme.txt exists but won't be selected
assert!(Path::new(test_asset_generator::asset_path(
"speakers/charlie/readme.txt"
))
.exists());
// Check that readme.txt exists but is not a voice candidate.
let readme = test_asset_generator::asset_path("speakers/charlie/readme.txt");
assert!(Path::new(readme).exists());
let candidates = astraweave_audio::dialogue_runtime::voice_folder_candidates(Path::new(
test_asset_generator::asset_path("speakers/charlie"),
));
let names: Vec<String> = candidates
.iter()
.map(|path| {
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("")
.to_string()
})
.collect();
assert_eq!(
names,
vec![
"line_01.wav".to_string(),
"line_02.wav".to_string(),
"line_03.ogg".to_string()
]
);
assert!(!names.iter().any(|name| name == "readme.txt"));

// Should only select .wav/.ogg files, not .txt
let dialogue = Dialogue {
Expand All @@ -481,14 +500,10 @@ fn test_folder_scan_filters_non_audio() -> Result<()> {
subtitle_out: None,
};

// Run multiple times to ensure we never select readme.txt
for _ in 0..5 {
let result = player.speak_current(&dialogue, &state)?;
assert!(result);
thread::sleep(Duration::from_millis(20));
}

// Tick after the loop to avoid borrow issues
// One play. The candidate assertion above is the filter; this checks
// that a listed file actually opens.
let result = player.speak_current(&dialogue, &state)?;
assert!(result);
audio_engine.tick(0.1);

Ok(())
Expand Down
35 changes: 31 additions & 4 deletions astraweave-terrain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,10 +846,37 @@ mod tests {
assert_eq!(generator.config.seed, 12345);
}

/// Phase 1.6-F.3-phase-1.B: `halo_seed` must be deterministic for the same
/// (world_seed, target_chunk_id, halo_chunks) triple, and must produce
/// different seeds for different target chunks (so adjacent halos have
/// distinct PRNG streams).
/// The halo crop, before D.3b per-biome amplitude, matches `generate_chunk`.
///
/// `generate_chunk_with_climate` modulates heights after this crop. That
/// public heightmap is not the legacy field; the 0.01 check belongs here.
#[test]
fn phase_1_6_f3_phase_1_unmodulated_halo_crop_matches_generate_chunk() -> anyhow::Result<()> {
let mut config = WorldConfig::default();
config.noise.erosion_enabled = false;
let gen = WorldGenerator::new(config);
let chunk_id = ChunkId::new(0, 0);
let legacy = gen.generate_chunk(chunk_id)?;
let halo = gen.generate_halo_heightmap(chunk_id, 1)?;
let cropped = gen.crop_halo_to_chunk(&halo, chunk_id)?;
assert_eq!(legacy.heightmap().resolution(), cropped.resolution());
let dim = cropped.resolution();
let mut max_diff = 0.0f32;
for z in 0..dim {
for x in 0..dim {
let d = (legacy.heightmap().get_height(x, z) - cropped.get_height(x, z)).abs();
max_diff = max_diff.max(d);
}
}
assert!(
max_diff < 0.01,
"unmodulated halo crop diverges from generate_chunk by {max_diff:.6}"
);
Ok(())
}

/// `halo_seed` is deterministic for one `(world_seed, chunk, halo)` triple
/// and differs across chunks.
#[test]
fn phase_1_6_f3_phase_1_halo_seed_deterministic() {
let s1 = WorldGenerator::halo_seed(12345, ChunkId::new(5, 3), 1);
Expand Down
19 changes: 11 additions & 8 deletions astraweave-terrain/tests/mutation_resistant_comprehensive_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ mod noise_mutations {
fn noise_config_base_elevation_defaults() {
let c = NoiseConfig::default();
assert!((c.base_elevation.scale - 0.005).abs() < 1e-6);
assert!((c.base_elevation.amplitude - 50.0).abs() < 1e-3);
assert!((c.base_elevation.amplitude - 100.0).abs() < 1e-3);
assert_eq!(c.base_elevation.octaves, 4);
assert!((c.base_elevation.persistence - 0.5).abs() < 1e-6);
assert!((c.base_elevation.lacunarity - 2.0).abs() < 1e-6);
Expand All @@ -263,7 +263,7 @@ mod noise_mutations {
fn noise_config_mountains_defaults() {
let c = NoiseConfig::default();
assert!((c.mountains.scale - 0.002).abs() < 1e-6);
assert!((c.mountains.amplitude - 80.0).abs() < 1e-3);
assert!((c.mountains.amplitude - 480.0).abs() < 1e-3);
assert_eq!(c.mountains.octaves, 6);
assert!((c.mountains.persistence - 0.4).abs() < 1e-6);
assert!((c.mountains.lacunarity - 2.2).abs() < 1e-6);
Expand All @@ -274,7 +274,7 @@ mod noise_mutations {
fn noise_config_detail_defaults() {
let c = NoiseConfig::default();
assert!((c.detail.scale - 0.02).abs() < 1e-6);
assert!((c.detail.amplitude - 5.0).abs() < 1e-3);
assert!((c.detail.amplitude - 3.0).abs() < 1e-3);
assert_eq!(c.detail.octaves, 3);
assert!((c.detail.persistence - 0.6).abs() < 1e-6);
assert!((c.detail.lacunarity - 2.0).abs() < 1e-6);
Expand Down Expand Up @@ -326,11 +326,14 @@ mod noise_mutations {
"Height range must be substantial (got {}), noise is working",
range
);
// With base amp=50, mountains amp=80, detail amp=5 the max height should be < 300
// Each layer's noise is in about [-1, 1] and mountains use abs, so the
// sampled height stays under the sum of the E3 default amplitudes
// (base 100 + mountains 480 + detail 3).
let amp_ceiling =
config.base_elevation.amplitude + config.mountains.amplitude + config.detail.amplitude;
assert!(
max_h < 300.0,
"Max height should be bounded by amplitudes, got {}",
max_h
max_h < amp_ceiling,
"Max height should be bounded by amplitudes ({amp_ceiling}), got {max_h}"
);
}

Expand All @@ -355,7 +358,7 @@ mod noise_mutations {
full_higher_count += 1;
}
}
// Mountains (.abs() * 80.0) should almost always add to height
// Mountains (.abs() * mountains.amplitude) should almost always add to height
assert!(
full_higher_count > total / 2,
"Mountains should add height in most cases ({}/{})",
Expand Down
29 changes: 17 additions & 12 deletions astraweave-terrain/tests/phase_1_6_f3_phase_1_halo_scaffolding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,27 @@ fn make_generator(seed: u64) -> WorldGenerator {

#[test]
fn halo_cropped_heightmap_matches_single_chunk_generation() {
// The halo path generates 3×3 chunks at per-vertex spacing matching
// single-chunk generation, then crops the center. Because
// `TerrainNoise::sample_height` is deterministic per world (x, z), the
// cropped heights must match what `generate_chunk` produces for the same
// chunk via the SIMD (or scalar) heightmap generator — up to float
// precision differences in accumulator ordering.
//
// Tolerance: 0.01 world units. Runs with erosion_enabled=false so
// phase 2's AdvancedErosion doesn't confound the machinery test.
// D.3b re-samples the halo with per-biome mountain amplitude before the
// public heightmap is returned. That field is not `generate_chunk`.
// The 0.01 crop identity is
// `phase_1_6_f3_phase_1_unmodulated_halo_crop_matches_generate_chunk`.
// This test locks the public result: two climate generations are
// bit-identical, and modulation moves the field off the legacy heights.
let gen = make_generator(12345);
let legacy = gen
.generate_chunk(ChunkId::new(0, 0))
.expect("legacy generation should succeed");
let new_path = gen
.generate_chunk_with_climate(ChunkId::new(0, 0), ClimateBias::Temperate)
.expect("new generation should succeed");
let again = gen
.generate_chunk_with_climate(ChunkId::new(0, 0), ClimateBias::Temperate)
.expect("second climate generation should succeed");
assert_eq!(
new_path.heightmap().data(),
again.heightmap().data(),
"climate heightmap must be bit-identical across calls"
);

let legacy_hm = legacy.heightmap();
let new_hm = new_path.heightmap();
Expand All @@ -68,10 +73,10 @@ fn halo_cropped_heightmap_matches_single_chunk_generation() {
}
}
}
println!("halo vs legacy max height diff (no erosion): {max_diff:.6}");
println!("modulated climate vs legacy max height diff (no erosion): {max_diff:.6}");
assert!(
max_diff < 0.01,
"halo-cropped heightmap machinery diverges from legacy single-chunk by {max_diff:.6}"
max_diff > 0.01,
"per-biome mountain amplitude should move the climate heightmap off generate_chunk, diff {max_diff:.6}"
);
}

Expand Down
Loading
Loading