awacke1's picture
Rename app.py to src/app.py
9dbf934 verified
# app.py
import streamlit as st
# st.set_page_config MUST be the very first Streamlit command.
st.set_page_config(page_title="Infinite World Builder", layout="wide")
import streamlit.components.v1 as components
import os
import json
import pandas as pd
import uuid
import math
import time
from streamlit_js_eval import streamlit_js_eval # For JS communication
# Import the GameState class for global state sharing.
from gamestate import GameState
# --- Constants ---
SAVE_DIR = "saved_worlds"
PLOT_WIDTH = 50.0 # Width of each plot in 3D space
PLOT_DEPTH = 50.0 # Depth of each plot (can be same as width)
CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
# --- Ensure Save Directory Exists ---
os.makedirs(SAVE_DIR, exist_ok=True)
# --- Helper Functions (unchanged from your original code) ---
@st.cache_data(ttl=3600)
def load_plot_metadata():
"""Scans SAVE_DIR for plot_X*.csv files, extracts grid coordinates and metadata."""
plots = []
try:
plot_files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".csv") and f.startswith("plot_X")]
except FileNotFoundError:
st.error(f"Save directory '{SAVE_DIR}' not found.")
return []
except Exception as e:
st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
return []
parsed_plots = []
for filename in plot_files:
try:
parts = filename[:-4].split('_') # Remove .csv
grid_x = int(parts[1][1:]) # Extract after "X"
grid_z = int(parts[2][1:]) # Extract after "Z"
plot_name = " ".join(parts[3:]) if len(parts) > 3 else f"Plot ({grid_x},{grid_z})"
parsed_plots.append({
'id': filename[:-4],
'filename': filename,
'grid_x': grid_x,
'grid_z': grid_z,
'name': plot_name,
'x_offset': grid_x * PLOT_WIDTH,
'z_offset': grid_z * PLOT_DEPTH
})
except (IndexError, ValueError):
st.warning(f"Could not parse grid coordinates from filename: {filename}. Skipping.")
continue
parsed_plots.sort(key=lambda p: (p['grid_x'], p['grid_z']))
return parsed_plots
def load_plot_objects(filename, x_offset, z_offset):
"""Loads objects from a CSV file and applies world offsets."""
file_path = os.path.join(SAVE_DIR, filename)
objects = []
try:
df = pd.read_csv(file_path)
if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
st.warning(f"CSV '{filename}' missing essential columns. Skipping.")
return []
# Ensure an obj_id exists for each row.
df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
if col not in df.columns:
df[col] = default
for _, row in df.iterrows():
obj_data = row.to_dict()
# Apply plot offsets to positions.
obj_data['pos_x'] += x_offset
obj_data['pos_z'] += z_offset
objects.append(obj_data)
return objects
except FileNotFoundError:
st.error(f"File not found during object load: {filename}")
return []
except pd.errors.EmptyDataError:
return []
except Exception as e:
st.error(f"Error loading objects from {filename}: {e}")
return []
def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
"""Saves object data list to a CSV file, making positions relative to the plot origin."""
file_path = os.path.join(SAVE_DIR, filename)
relative_objects = []
if not isinstance(objects_data_list, list):
st.error("Invalid data format received for saving (expected a list).")
return False
for obj in objects_data_list:
pos = obj.get('position', {})
rot = obj.get('rotation', {})
obj_type = obj.get('type', 'Unknown')
obj_id = obj.get('obj_id', str(uuid.uuid4()))
if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
print(f"Skipping malformed object during save prep: {obj}")
continue
relative_obj = {
'obj_id': obj_id, 'type': obj_type,
'pos_x': pos.get('x', 0.0) - plot_x_offset,
'pos_y': pos.get('y', 0.0),
'pos_z': pos.get('z', 0.0) - plot_z_offset,
'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0),
'rot_z': rot.get('_z', 0.0), 'rot_order': rot.get('_order', 'XYZ')
}
relative_objects.append(relative_obj)
try:
df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
df.to_csv(file_path, index=False)
st.success(f"Saved {len(relative_objects)} objects to {filename}")
return True
except Exception as e:
st.error(f"Failed to save plot data to {filename}: {e}")
return False
# --- Global State Management ---
# Create a singleton GameState instance using st.cache_resource.
@st.cache_resource
def get_game_state():
return GameState(state_file="global_state.json")
game_state = get_game_state()
# --- Page Config and Session State Initialization ---
# (st.set_page_config already called at top.)
if 'selected_object' not in st.session_state:
st.session_state.selected_object = 'None'
if 'js_save_data' not in st.session_state:
st.session_state.js_save_data = None
# --- Load Plot Metadata and Initial Objects ---
plots_metadata = load_plot_metadata()
all_initial_objects = []
for plot in plots_metadata:
all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset'], plot['z_offset']))
# Optionally, merge the objects from your CSVs into the global state if not already present.
if not game_state.get_state().get("objects"):
game_state.update_state(all_initial_objects)
# --- Sidebar Controls ---
with st.sidebar:
st.title("🏗️ World Controls")
st.header("Navigation (Plots)")
st.caption("Click to teleport player to a plot.")
max_cols = 2
cols = st.columns(max_cols)
col_idx = 0
sorted_plots_for_nav = sorted(plots_metadata, key=lambda p: (p['grid_x'], p['grid_z']))
for plot in sorted_plots_for_nav:
button_label = f"➡️ {plot.get('name', plot['id'])} ({plot['grid_x']},{plot['grid_z']})"
if cols[col_idx].button(button_label, key=f"nav_{plot['id']}"):
target_x = plot['x_offset']
target_z = plot['z_offset']
try:
js_code = f"teleportPlayer({target_x + PLOT_WIDTH/2}, {target_z + PLOT_DEPTH/2});"
streamlit_js_eval(js_code=js_code, key=f"teleport_{plot['id']}")
except Exception as e:
st.error(f"Failed to send teleport command: {e}")
col_idx = (col_idx + 1) % max_cols
st.markdown("---")
st.header("Place Objects")
object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
current_object_index = object_types.index(st.session_state.selected_object) if st.session_state.selected_object in object_types else 0
selected_object_type_widget = st.selectbox("Select Object:", options=object_types, index=current_object_index, key="selected_object_widget")
if selected_object_type_widget != st.session_state.selected_object:
st.session_state.selected_object = selected_object_type_widget
st.markdown("---")
st.header("Save Work")
st.caption("Saves newly placed objects to the current plot and updates the global state.")
if st.button("💾 Save Current Work", key="save_button"):
try:
# Trigger JS to get data (player position and new objects).
js_get_data_code = "getSaveDataAndPosition();"
streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
except Exception as e:
st.error(f"Error triggering JS save: {e}")
st.experimental_rerun()
st.markdown("---")
st.header("Download Global State as Markdown")
global_state = game_state.get_state()
default_md_name = global_state.get("last_updated", "save").replace(":", "").replace(" ", "_") + ".md"
download_name = st.text_input("Override File Name", value=default_md_name)
md_outline = f"""# Global Save: {download_name}
- ⏰ **Timestamp:** {global_state.get("last_updated", "N/A")}
- 🎮 **Number of Game Objects:** {len(global_state.get("objects", []))}
## Game Objects:
"""
for i, obj in enumerate(global_state.get("objects", []), start=1):
obj_type = obj.get("type", "Unknown")
pos = (obj.get("x", 0), obj.get("y", 0), obj.get("z", 0))
md_outline += f"- {i}. ✨ **{obj_type}** at {pos}\n"
st.download_button("Download Markdown Save", data=md_outline, file_name=download_name, mime="text/markdown")
# --- Process Save Data from JS ---
save_data_from_js = st.session_state.get("js_save_data", None)
if save_data_from_js:
try:
payload = json.loads(save_data_from_js) if isinstance(save_data_from_js, str) else save_data_from_js
if isinstance(payload, dict) and "playerPosition" in payload and "objectsToSave" in payload:
player_pos = payload["playerPosition"]
new_objects = payload["objectsToSave"]
# Optionally, add additional info (like a timestamp) to each new object.
for obj in new_objects:
obj["timestamp"] = time.strftime("%Y-%m-%d %H:%M:%S")
game_state.update_state(new_objects)
st.success("Global state updated with new objects.")
st.session_state["js_save_data"] = None
st.experimental_rerun()
else:
st.error("Invalid payload received from client.")
except Exception as e:
st.error(f"Error processing save data: {e}")
st.session_state["js_save_data"] = None
# --- Main Area ---
st.header("Infinite Shared 3D World")
st.caption("Move to empty areas to expand the world. Use the sidebar 'Save' controls to store your work.")
# --- Inject State into HTML ---
# We inject both the original objects (for initial 3D scene rendering) and the global state.
injected_state = {
"ALL_INITIAL_OBJECTS": all_initial_objects,
"PLOTS_METADATA": plots_metadata,
"SELECTED_OBJECT_TYPE": st.session_state.selected_object,
"PLOT_WIDTH": PLOT_WIDTH,
"PLOT_DEPTH": PLOT_DEPTH,
"GLOBAL_STATE": game_state.get_state()
}
html_file_path = "index.html"
try:
with open(html_file_path, "r", encoding="utf-8") as f:
html_template = f.read()
js_injection_script = f"""
<script>
window.ALL_INITIAL_OBJECTS = {json.dumps(injected_state["ALL_INITIAL_OBJECTS"])};
window.PLOTS_METADATA = {json.dumps(injected_state["PLOTS_METADATA"])};
window.SELECTED_OBJECT_TYPE = {json.dumps(injected_state["SELECTED_OBJECT_TYPE"])};
window.PLOT_WIDTH = {json.dumps(injected_state["PLOT_WIDTH"])};
window.PLOT_DEPTH = {json.dumps(injected_state["PLOT_DEPTH"])};
window.GLOBAL_STATE = {json.dumps(injected_state["GLOBAL_STATE"])};
console.log("Injected Global State:", window.GLOBAL_STATE);
</script>
"""
html_content_with_state = html_template.replace("</head>", js_injection_script + "\n</head>", 1)
components.html(html_content_with_state, height=750, scrolling=False)
except FileNotFoundError:
st.error(f"CRITICAL ERROR: Could not find the file '{html_file_path}'.")
except Exception as e:
st.error(f"An error occurred during HTML component rendering: {e}")