Skip to content

AI System & Code Quality Improvements#137

Merged
M1thieu merged 15 commits intomainfrom
dev
Nov 24, 2025
Merged

AI System & Code Quality Improvements#137
M1thieu merged 15 commits intomainfrom
dev

Conversation

@M1thieu
Copy link
Collaborator

@M1thieu M1thieu commented Nov 24, 2025

Objective

Consolidate 15 commits from dev branch:

  • Recent: Tracker refactoring (eliminate 80% duplication)
  • Previous: AI core simplification (-2,304 lines), code consistency, systems improvements

Implementation

1. Tracker Deduplication - Main focus of recent work

  • Extracted shared evaluation logic from ThreatTracker + PreyTracker (80% duplication)
  • Created evaluate_tracked_entities_with_decay() helper function
  • Impact: ThreatTracker + PreyTracker each reduced from 29 to 14 lines
  • Enables rapid addition of 6 planned trackers (aggression, social, territory, noise, obstacle, injury)

2. AI Architecture Simplification

  • Removed complex DSL (~2,300 lines of over-abstraction)
  • Replaced with clean utility arbiter pipeline (~210 lines)
  • Net change: -2,304 lines removed

3. Code Consistency

  • Standardized import order: std -> bevy -> crate (across all files)
  • Extracted duplicate helpers (e.g., normalize_or() in waves)
  • Removed redundant new() constructors using Default instead
  • Added trait defaults to eliminate empty implementations

4. Minor Fixes

  • Restored project logo
  • Fixed line wrapping in gravity calculations
  • Formatting consistency improvements

Core AI Systems:

  • Entity tracking with data/evaluation separation
  • Threat tracking with panic calculations
  • Utility smoothing for stable behavior selection
  • Relationship context handling for social AI
  • Needs tracking foundation

Systems Infrastructure:

  • Configurable systems plugin architecture
  • Configurable gravitational constant
  • pbmpm renamed to mpm crate for convenience
  • Systems aggregator documentation
  • Community files (.github templates, CoC, funding)

Testing

Compilation:

cargo check --workspace       # All crates compile
cargo check --example basic_ai & cargo run --example basic_ai # Refactored example works
cargo clippy --workspace      # No new warnings

Behavior Preserved:

  • ThreatTracker panic formula identical (exponential saturation)
  • PreyTracker best-prey selection identical (attractiveness scoring)
  • Time decay: exp(-decay_rate * time_since) unchanged
  • Distance factors unchanged

No breaking changes to public APIs.

Code Example

Before: Duplicated Evaluation

// ThreatTracker - 29 lines
for tracked in entity_tracker.filter_by_metadata(...) {
    let time_since = tracked.time_since_seen(current_time);
    let decay = (-config.decay_per_second * time_since).exp();
    let distance_factor = if tracked.last_distance > 0.0 {
        1.0 - (tracked.last_distance / max).clamp(0.0, 1.0)
    } else { 1.0 };
    // ... more duplicated logic
}
// PreyTracker - 29 lines of 80% identical code

After: Shared Helper

// Both trackers use same helper
for (entity, score) in super::evaluate_tracked_entities_with_decay(
    entity_tracker, current_time, decay_rate, max_distance,
    |m| match m {
        EntityMetadata::Threat { severity } => Some(*severity),
        _ => None,
    },
) {
    // Process scores (tracker-specific logic only)
}

Technical Notes

Modularity:

  • Component-based design works for both creatures and plants
  • Same trackers can be used across all organism types

Future Trackers:

  • Each new tracker will be ~15 lines instead of ~30 lines thanks to shared helper.
  • They will also be enhanced later on as they're now still basic enough

Performance:

  • Iterator-based (lazy evaluation)
  • No allocations in hot path
  • Removed unnecessary closure cloning

Preserve social history instead of overwriting, expose configurable personality inputs, embed fractal templates, and document SystemsPlugin configuration.
- UtilitySmoothing: Component that smooths scorer outputs over time with continuation bonuses to prevent rapid action switching (thrashing)
- ThreatTracker: Tracks visible threats with distance-based severity, natural decay, and exponential panic calculation for fear-driven behaviors

Both components integrate seamlessly with existing scorer and perception systems.
Config extraction:
- PersonalityConfig: social influence distance tuning
- GravityParams: Barnes-Hut algorithm parameters (depth, bodies per node)
- ThreatTrackerConfig: decay rate and forget timeout defaults
- SocialConfig: relationship decay time scale and blending weights

Fixes:
- Remove threat panic "sticky" floor, now decays naturally with accumulated threat
- Add HashMap capacity hints (EntityTracker, ThreatTracker, SocialNetwork)

Breaking API changes:
- SocialNetwork methods now require &SocialConfig parameter
- update_collective_influence() requires Res<PersonalityConfig> (Bevy auto-injects)
Architecture:
• entity_tracker: Data storage (position, last_seen, EntityMetadata enum)
• threat_tracker: Threat evaluation (panic calculation from entity data)
• prey_tracker: Food evaluation (attractiveness from entity data)
• Clean separation: data layer independent from evaluation layer

Changes:
• Added entity_tracker.rs (data storage with metadata enum)
• Added threat_tracker.rs (evaluates threats, outputs panic level)
• Added prey_tracker.rs (evaluates food sources, outputs hunger score)
• Deleted base_tracker.rs (replaced by entity_tracker)
• Updated mod.rs with future tracker plans

Benefits:
• Data storage separate from evaluation logic
• Easy to add new tracker types (just implement evaluation)
• Trackers read shared EntityTracker (no duplication)
• Scalable pattern for LP's multi-organism ecosystem

Future trackers planned:
• aggression, social, territory, noise, obstacle, injury
Reformat line wrapping in gravity calculations and import lists for consistency with Rust style guidelines.

- gravity.rs: Adjust force magnitude calculation line breaks
- mod.rs: Consolidate prelude import lists
Standardize code patterns across the AI system crate for better maintainability:

- Standardize import order: std → bevy → crate (consistent across all files)
- Add default implementation to AIModule::update() trait method
- Remove empty update() implementations using new default
- Remove redundant new() constructors that just call Default::default()

Changes maintain backward compatibility while reducing boilerplate.
Apply DRY, KISS, and consistency improvements to forces, energy, and information crates:

**Import Order:**
- Standardize to: std → bevy → crate (energy/electromagnetism, information/fractals)

**DRY Improvements:**
- Extract duplicated normalize_or() helper to waves/mod.rs
- Remove duplicate implementations from oscillation.rs and propagation.rs

**Redundant Code Cleanup:**
- Remove WaveParameters::new() (use Default instead with builder pattern)
- Keep MassProperties::new() (actively used in gravity.rs:164)

**Code Quality:**
- All changes maintain backward compatibility
- Zero functional changes, pure refactoring
Extracted common evaluation logic (time decay + distance factors) from ThreatTracker and PreyTracker into shared helper function `evaluate_tracked_entities_with_decay()`.

Changes:
- Add evaluate_tracked_entities_with_decay() in trackers/mod.rs
  - Handles exponential time-based decay
  - Applies linear distance-based scoring
  - Generic over metadata extraction via closure

- Simplify ThreatTracker::update()
  - Uses shared helper with Threat severity extraction
  - Preserves original panic saturation formula

- Simplify PreyTracker::update()
  - Uses shared helper with Prey attractiveness extraction
  - Preserves original best-prey selection logic

No behavior changes purely refactoring to reduce 80% code duplication between trackers.
Future trackers (aggression, social, territory) will use the same helper.
@M1thieu M1thieu added the AI label Nov 24, 2025
@M1thieu M1thieu merged commit ac385c3 into main Nov 24, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant