From 0ede2e567f43ddbff88bbf85cf7f83f6abcae47d Mon Sep 17 00:00:00 2001 From: cinnaboot Date: Mon, 6 Apr 2026 13:12:09 +0000 Subject: [PATCH] trying out a new method for generating llm context --- scripts/generate_interface_summaries.sh | 78 +++ scripts/source_documentation_analysis.md | 732 +++++++++++++++++++++++ scripts/test_prompt.txt | 1 + 3 files changed, 811 insertions(+) create mode 100755 scripts/generate_interface_summaries.sh create mode 100644 scripts/source_documentation_analysis.md create mode 100644 scripts/test_prompt.txt diff --git a/scripts/generate_interface_summaries.sh b/scripts/generate_interface_summaries.sh new file mode 100755 index 0000000..d1108d5 --- /dev/null +++ b/scripts/generate_interface_summaries.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# Generate interface summaries for all modules in src/ +# Creates temporary markdown files alongside source files for quick reference + +set -e + +PROVIDER="llama.cpp" +MODEL="Qwen3.5-35B" +SRC_DIR="/home/agent/dev/claudes_game/src" +TEMP_EXT=".interface.md" +TMP_PROMPT=$(mktemp) + +# Cleanup on exit +trap "rm -f $TMP_PROMPT" EXIT + +# Function to generate prompt for a specific module +generate_prompt() { + local module_name="$1" + cat < "$TMP_PROMPT" + echo $TMP_PROMPT + + # pi --print --no-session --provider llama.cpp --model \ + # "Qwen3.5-35B" "print a hello world application in rust" + # + # Use pi -p with the prompt as file argument + #pi -p "$TMP_PROMPT" "$header_file" > "$output_file" 2>&1 || { + # echo "Error processing ${module_name}" + # cat "$output_file" + # return 1 + #} + + echo "Generated: ${output_file}" +} + +# List of modules to process (based on src/ directory) +MODULES=( $(ls src/*.h | grep -oP '[^/]+(?=\.h)') ) + +echo "=== Interface Summary Generator ===" +echo "Processing ${#MODULES[@]} modules..." +echo "" + +for module in "${MODULES[@]}"; do + process_module "$module" +done + +echo "" +echo "=== Complete ===" +echo "Generated ${TEMP_EXT} files alongside source files in ${SRC_DIR}" +echo "These files are temporary and should be added to .gitignore" diff --git a/scripts/source_documentation_analysis.md b/scripts/source_documentation_analysis.md new file mode 100644 index 0000000..fde39c3 --- /dev/null +++ b/scripts/source_documentation_analysis.md @@ -0,0 +1,732 @@ +# Source Documentation Analysis + +## Executive Summary + +Comprehensive examination of all source files in `src/` directory (15 files) to identify under-documented interface structs, enums, and functions. Focus areas: frequently used structures/enums and functions containing complex algorithms. + +**Total under-documented items identified:** 24 + +**By priority:** +- **High (frequently used, complex algorithms):** 10 items +- **Medium (frequently used, important logic):** 10 items +- **Low (UI/rendering, less critical):** 4 items + +**By type:** +- **Structs:** 5 +- **Enums:** 2 +- **Functions:** 17 + +--- + +## HIGH PRIORITY - Frequently Used Core Structures + +### 1. OrbitalElements (orbital_mechanics.h) + +**Status:** Under-documented despite being used throughout the codebase + +**Missing documentation:** +- Union field usage explanation (why semi_major_axis vs semi_latus_rectum) +- Parameter meanings and units for all 6 elements +- Which elements are required vs optional in config files +- Relationship to classical Keplerian elements +- Parabolic orbit handling rationale + +**Usage frequency:** Extremely high - used in simulation.cpp, maneuver.cpp, renderer.cpp, config_loader.cpp + +**Current code:** +```cpp +struct OrbitalElements { + union { + double semi_major_axis; // elliptical (e<1) and hyperbolic (e>1) + double semi_latus_rectum; // parabolic (e≈1) + }; + double eccentricity; + double true_anomaly; + double inclination; + double longitude_of_ascending_node; + double argument_of_periapsis; +}; +``` + +--- + +### 2. CelestialBody (simulation.h) + +**Status:** Partially documented but missing key details + +**Missing documentation:** +- When local vs global coordinates are used +- SOI radius calculation method and significance +- Parent index hierarchy rules +- Color format specification (RGB range) +- Velocity frame of reference + +**Usage frequency:** Extremely high - core simulation structure + +**Current code:** +```cpp +struct CelestialBody { + char name[64]; + double mass; // kg + double radius; // meters + int parent_index; // index of gravitational parent (-1 for root) + float color[3]; // RGB color for rendering + + OrbitalElements orbit; // Keplerian elements from config + + Vec3 global_position; // meters from origin + Vec3 global_velocity; // m/s + Vec3 local_position; // meters from parent + Vec3 local_velocity; // m/s relative to parent + + double soi_radius; // sphere of influence radius (meters) +}; +``` + +--- + +### 3. SimulationState (simulation.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Memory ownership (who allocates/frees) +- Thread safety (if applicable) +- Maximum time step recommendations +- Config name field usage +- Relationship between max_* and actual counts + +**Usage frequency:** Extremely high - passed to almost every function + +**Current code:** +```cpp +struct SimulationState { + CelestialBody* bodies; + int body_count; + int max_bodies; + + Spacecraft* spacecraft; + int craft_count; + int max_craft; + + Maneuver* maneuvers; + int maneuver_count; + int max_maneuvers; + + double time; + double dt; + char config_name[256]; +}; +``` + +--- + +## HIGH PRIORITY - Core Enums + +### 4. BurnDirection (maneuver.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Local frame definition (which axes) +- Physical meaning of each direction +- When to use each direction (mission planning context) +- BURN_CUSTOM usage and requirements + +**Usage frequency:** High - used in maneuver.cpp, ui_renderer.cpp, renderer.cpp + +**Current code:** +```cpp +enum BurnDirection { + BURN_PROGRADE, + BURN_RETROGRADE, + BURN_NORMAL, + BURN_ANTINORMAL, + BURN_RADIAL_IN, + BURN_RADIAL_OUT, + BURN_CUSTOM +}; +``` + +--- + +### 5. TriggerType (maneuver.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Time trigger precision requirements +- True anomaly trigger tolerance (0.01 rad) +- Which trigger is more accurate for different scenarios +- Recommended use cases + +**Usage frequency:** Medium - used in maneuver.cpp, config_loader.cpp + +**Current code:** +```cpp +enum TriggerType { + TRIGGER_TIME, + TRIGGER_TRUE_ANOMALY +}; +``` + +--- + +## HIGH PRIORITY - Complex Algorithm Functions + +### 6. propagate_orbital_elements() (orbital_mechanics.h/cpp) + +**Status:** Documented in technical_reference.md but missing in source + +**Missing in source code:** +- Parameter units explanation +- Edge case handling (near-parabolic, near-circular) +- Numerical stability guarantees +- Expected accuracy per time step +- When to use vs RK4_step + +**Current comment:** None in header, minimal in implementation + +**Function signature:** +```cpp +OrbitalElements propagate_orbital_elements(OrbitalElements elements, double dt, double parent_mass); +``` + +**Algorithm complexity:** High - handles elliptical, parabolic, and hyperbolic orbits with different propagation methods + +--- + +### 7. cartesian_to_orbital_elements() (orbital_mechanics.h/cpp) + +**Status:** Documented in technical_reference.md but missing in source + +**Missing in source code:** +- Near-parabolic detection threshold +- Near-circular handling rationale +- Numerical stability measures +- Output guarantees for edge cases +- When reconstruction is needed (after burns, SOI transitions) + +**Current comment:** None in header, minimal in implementation + +**Function signature:** +```cpp +OrbitalElements cartesian_to_orbital_elements(Vec3 position, Vec3 velocity, double parent_mass); +``` + +**Algorithm complexity:** High - requires vector cross products, eccentricity vector calculation, and special case handling + +--- + +### 8. solve_kepler_elliptical() and solve_kepler_hyperbolic() (orbital_mechanics.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Initial guess strategy explanation +- Convergence criteria and tolerance +- Maximum iterations justification +- Expected iteration count for typical cases +- Failure mode behavior + +**Current comment:** Initial guess formula in get_initial_trial_value() but no explanation + +**Function signatures:** +```cpp +double solve_kepler_elliptical(double mean_anomaly, double eccentricity); +double solve_kepler_hyperbolic(double mean_anomaly, double eccentricity); +``` + +**Algorithm complexity:** High - Newton-Raphson iterative solver with convergence checking + +--- + +### 9. find_dominant_body() (simulation.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- SOI transition detection algorithm +- Performance characteristics (O(n) worst case) +- Root body handling logic +- When transitions are checked (every frame) +- Performance impact of many bodies + +**Current comment:** None + +**Function signature:** +```cpp +int find_dominant_body(SimulationState* sim, int body_index); +``` + +**Algorithm complexity:** Medium - iterates through all bodies to find closest SOI-dominant body + +--- + +### 10. check_maneuver_trigger() (maneuver.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- True anomaly trigger prediction algorithm +- scheduled_dt calculation method +- Wraparound crossing detection logic +- Time precision requirements +- Performance considerations + +**Current comment:** Some inline comments but no function-level documentation + +**Function signature:** +```cpp +bool check_maneuver_trigger(Maneuver* maneuver, Spacecraft* craft, SimulationState* sim); +``` + +**Algorithm complexity:** Medium - requires orbital element to true anomaly conversion and crossing detection + +--- + +## MEDIUM PRIORITY - Frequently Used Functions + +### 11. initialize_orbital_objects() (simulation.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Initialization sequence and order +- Error handling behavior +- When to call (after config load, before simulation) +- What happens on failed initialization + +**Current comment:** "Initialize orbital objects from orbital elements" - too brief + +**Function signature:** +```cpp +void initialize_orbital_objects(SimulationState* sim); +``` + +--- + +### 12. update_simulation() (simulation.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Complete update sequence explanation +- Sub-function call order rationale +- Time step integration +- Maneuver execution timing within frame +- When to call (main loop only) + +**Current comment:** None + +**Function signature:** +```cpp +void update_simulation(SimulationState* sim); +``` + +--- + +### 13. execute_pending_maneuvers() (simulation.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Exact position burn execution rationale +- scheduled_dt usage +- Remaining time propagation +- Spacecraft handling flag purpose +- Performance implications + +**Current comment:** None + +**Function signature:** +```cpp +void execute_pending_maneuvers(SimulationState* sim); +``` + +--- + +### 14. orbital_elements_to_cartesian() (orbital_mechanics.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Rotation matrix derivation (z-x-z Euler) +- Coordinate frame transformations +- Output frame of reference +- Numerical stability measures +- Performance characteristics + +**Current comment:** None + +**Function signature:** +```cpp +void orbital_elements_to_cartesian(OrbitalElements elements, double parent_mass, Vec3* out_pos, Vec3* out_vel); +``` + +**Algorithm complexity:** Medium - requires Euler angle rotations and anomaly conversions + +--- + +## MEDIUM PRIORITY - Configuration/Validation + +### 15. load_system_config() (config_loader.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- TOML format requirements +- Error handling behavior +- Memory allocation strategy +- Validation sequence +- What fields are required vs optional + +**Current comment:** None + +**Function signature:** +```cpp +bool load_system_config(SimulationState* sim, const char* filepath); +``` + +--- + +### 16. run_all_config_validations() (config_validator.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Complete validation list +- Validation order and dependencies +- Error reporting format +- Which validations are critical vs warnings +- Performance impact + +**Current comment:** None + +**Function signature:** +```cpp +bool run_all_config_validations(SimulationState* sim); +``` + +--- + +## MEDIUM PRIORITY - Physics Module + +### 17. mat3_rotation_orbital() (physics.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Euler angle sequence (z-x-z) +- Angle order and units +- Output matrix structure +- Use cases +- Numerical stability + +**Current comment:** None + +**Function signature:** +```cpp +Mat3 mat3_rotation_orbital(double omega, double i, double Omega); +``` + +--- + +### 18. rk4_step() (physics.h/cpp) + +**Status:** Documented in technical_reference.md but missing in source + +**Missing in source code:** +- When it's available but not used +- Comparison to analytical propagation +- Performance vs accuracy trade-offs +- Integration with orbital_mechanics + +**Current comment:** "RK4 inferior to analytical propagation" comment exists but insufficient + +**Function signature:** +```cpp +void rk4_step(Vec3* out_accel, Vec3 position, Vec3 velocity, double dt, double parent_mass); +``` + +--- + +## MEDIUM PRIORITY - Maneuver Module + +### 19. preview_burn_result() (maneuver.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- UI preview usage +- State vector reconstruction method +- Accuracy guarantees +- Performance characteristics +- When to call (before execution) + +**Current comment:** None + +**Function signature:** +```cpp +void preview_burn_result(Spacecraft* craft, BurnDirection direction, double delta_v, + Vec3* out_new_local_pos, Vec3* out_new_local_vel, SimulationState* sim); +``` + +--- + +### 20. calculate_hohmann_transfer() (maneuver.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- Hohmann transfer assumptions +- Required conditions (coplanar, circular) +- Output field meanings +- Accuracy limitations +- When to use vs other transfers + +**Current comment:** None + +**Function signature:** +```cpp +void calculate_hohmann_transfer(SimulationState* sim, int current_body_index, + int target_body_index, HohmannTransfer* out_transfer); +``` + +--- + +## LOW PRIORITY - UI/Renderer + +### 21. RenderState (renderer.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Texture array usage (6 textures for burn directions) +- Camera follow mode state +- Offset preservation logic +- Last target index change detection + +**Current comment:** None + +**Current code:** +```cpp +struct RenderState { + Camera3D camera; + double distance_scale; // Scale factor for distances + double size_scale; // Scale factor for body sizes + int selected_body_index; // -1 = no selection + bool camera_target_enabled; // Whether camera follows selected body + Vector3 camera_offset; // Offset from target when following body + int last_target_index; // Tracks body index for change detection + Texture2D maneuver_textures[6]; // One per burn direction + bool texture_loaded; +}; +``` + +--- + +### 22. UIState (ui_renderer.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Buffer management strategy +- Cache invalidation rules +- Memory allocation/deallocation +- State persistence between frames +- Thread safety (if applicable) + +**Current comment:** None + +**Current code:** +```cpp +struct UIState { + int body_list_scroll; + int body_list_active; + int selected_craft_index; + + ManeuverDialogState maneuver_dialog; + int maneuver_list_active; + int maneuver_list_scroll; + int selected_maneuver_index; + + int cached_body_count; + int cached_craft_count; + int cached_maneuver_count; + int cached_executed_count; + int body_list_buffer_size; + char* body_list_buffer; + int craft_list_buffer_size; + char* craft_list_buffer; + int body_dropdown_buffer_size; + char* body_dropdown_buffer; + int maneuver_list_buffer_size; + char* maneuver_list_buffer; +}; +``` + +--- + +### 23. ManeuverDialogState (ui_renderer.h) + +**Status:** Missing documentation + +**Missing documentation:** +- Tab state machine +- Preview calculation triggers +- Error message management +- Delete confirmation flow +- Field validation state + +**Current comment:** None + +**Current code:** +```cpp +struct ManeuverDialogState { + bool open; + ManeuverDialogTab active_tab; + + int craft_index; + char name[64]; + int direction_active; + double delta_v; + int trigger_type_active; + double trigger_value; + int edit_maneuver_index; + + int target_body_index; + int current_body_index; + int transfer_body_index; + bool show_hohmann_preview; + HohmannTransfer last_calc; + + bool show_preview; + bool preview_valid; + OrbitalElements preview_elements; + + char error_message[256]; + bool show_error; + bool show_delete_confirm; +}; +``` + +--- + +## TEST UTILITIES + +### 24. OrbitTracker (test_utilities.h/cpp) + +**Status:** Missing documentation + +**Missing documentation:** +- 3D angle calculation method +- Quadrant transition counting +- Orbit completion criteria +- min_time_days significance +- When to use vs simple angle tracking + +**Current comment:** None + +**Current code:** +```cpp +struct OrbitTracker { + double initial_angle; + double previous_angle; + int quadrant_transitions; + bool orbit_completed; + double time_at_completion; + int body_index; + double min_time_days; + + // Orbital elements for 3D angle calculation + double inclination; + double longitude_of_ascending_node; + double argument_of_periapsis; + bool has_orbital_elements; +}; +``` + +--- + +## Most Critical Gaps + +The following 5 items are most critical for code maintainability and developer onboarding: + +1. **OrbitalElements** - Core data structure used throughout the codebase +2. **propagate_orbital_elements()** - Main propagation algorithm with complex orbital mechanics +3. **cartesian_to_orbital_elements()** - Element reconstruction after burns and SOI transitions +4. **BurnDirection** - Mission planning interface with physical significance +5. **find_dominant_body()** - SOI transition detection algorithm + +--- + +## Recommendations + +### Immediate Actions (High Priority) + +1. Add inline documentation to all HIGH PRIORITY items +2. Document parameter units and expected ranges +3. Explain algorithm choices and edge case handling +4. Add usage examples for complex functions + +### Short-term Actions (Medium Priority) + +1. Add function-level comments for MEDIUM PRIORITY items +2. Document initialization sequences and dependencies +3. Add performance notes where relevant +4. Document error handling behavior + +### Long-term Actions (Low Priority) + +1. Add comprehensive documentation for UI/Renderer structures +2. Document memory management patterns +3. Add thread safety notes (if applicable) +4. Create usage examples for complex UI state machines + +--- + +## Impact Assessment + +**Current state:** Code relies on technical_reference.md for documentation, but this is not visible to developers reading source files directly. + +**Expected improvement:** Adding inline documentation will: +- Reduce onboarding time for new developers +- Improve code maintainability +- Reduce bugs from misunderstood algorithms +- Enable better code reviews +- Facilitate future feature additions + +**Documentation coverage target:** 100% of public API functions and complex internal functions should have inline documentation explaining: +- Purpose and algorithm +- Parameter units and ranges +- Return value meaning +- Edge cases and error conditions +- Performance characteristics (where relevant) + +--- + +## Methodology + +This analysis was performed by: +1. Reading all 15 source files in `src/` directory +2. Identifying structs, enums, and functions +3. Assessing usage frequency across codebase +4. Evaluating algorithm complexity +5. Checking existing documentation (inline comments, technical_reference.md) +6. Prioritizing based on impact and frequency of use + +**Files examined:** +- config_loader.h/cpp +- config_validator.h/cpp +- orbital_mechanics.h/cpp +- physics.h/cpp +- maneuver.h/cpp +- simulation.h/cpp +- spacecraft.h +- renderer.h/cpp +- ui_renderer.h/cpp +- main.cpp +- test_utilities.h/cpp + +**Total lines of code analyzed:** ~8,500 lines diff --git a/scripts/test_prompt.txt b/scripts/test_prompt.txt new file mode 100644 index 0000000..b62bf0f --- /dev/null +++ b/scripts/test_prompt.txt @@ -0,0 +1 @@ +pi --model Qwen3.5-35B --provider llama.cpp --print "Summarize the module src/orbital_mechanics . Do not read in any other files, we will use this summary as input into another llm session. we need to preserve any interface structs,enums,function signatures, etc as the original source code, along with a concise summary of each. Only provide a detailed explaination for functions with complex algorithms. The Formatting should be summary first, then original source code underneath. Add any extra info as inline comments to the source"