Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,26 +5,25 @@ import os
|
|
5 |
import json
|
6 |
import pandas as pd
|
7 |
import uuid
|
8 |
-
import math
|
9 |
-
|
10 |
-
|
|
|
|
|
11 |
|
12 |
# --- Constants ---
|
13 |
SAVE_DIR = "saved_worlds"
|
14 |
-
PLOT_WIDTH = 50.0
|
15 |
-
PLOT_DEPTH = 50.0
|
16 |
CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
|
17 |
|
18 |
# --- Ensure Save Directory Exists ---
|
19 |
os.makedirs(SAVE_DIR, exist_ok=True)
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
@st.cache_data(ttl=3600) # Cache plot list
|
24 |
def load_plot_metadata():
|
25 |
-
"""Scans
|
26 |
plots = []
|
27 |
-
plot_files = []
|
28 |
try:
|
29 |
plot_files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".csv") and f.startswith("plot_X")]
|
30 |
except FileNotFoundError:
|
@@ -34,67 +33,60 @@ def load_plot_metadata():
|
|
34 |
st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
|
35 |
return []
|
36 |
|
37 |
-
# Parse filenames to get grid coordinates
|
38 |
parsed_plots = []
|
39 |
for filename in plot_files:
|
40 |
try:
|
41 |
-
parts = filename[:-4].split('_')
|
42 |
-
grid_x = int(parts[1][1:])
|
43 |
-
grid_z = int(parts[2][1:])
|
44 |
-
# Extract name if present (parts after Z coordinate)
|
45 |
plot_name = " ".join(parts[3:]) if len(parts) > 3 else f"Plot ({grid_x},{grid_z})"
|
46 |
-
|
47 |
parsed_plots.append({
|
48 |
-
'id': filename[:-4],
|
49 |
'filename': filename,
|
50 |
'grid_x': grid_x,
|
51 |
'grid_z': grid_z,
|
52 |
'name': plot_name,
|
53 |
'x_offset': grid_x * PLOT_WIDTH,
|
54 |
-
'z_offset': grid_z * PLOT_DEPTH
|
55 |
})
|
56 |
except (IndexError, ValueError):
|
57 |
st.warning(f"Could not parse grid coordinates from filename: {filename}. Skipping.")
|
58 |
continue
|
59 |
|
60 |
-
# Sort primarily by X, then by Z
|
61 |
parsed_plots.sort(key=lambda p: (p['grid_x'], p['grid_z']))
|
62 |
-
|
63 |
return parsed_plots
|
64 |
|
65 |
def load_plot_objects(filename, x_offset, z_offset):
|
66 |
-
"""Loads objects from a CSV
|
67 |
file_path = os.path.join(SAVE_DIR, filename)
|
68 |
objects = []
|
69 |
try:
|
70 |
df = pd.read_csv(file_path)
|
71 |
-
# Check required columns
|
72 |
if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
|
73 |
-
|
74 |
-
|
75 |
-
# Add defaults for optional columns
|
76 |
df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
|
77 |
for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
|
78 |
-
|
|
|
79 |
|
80 |
for _, row in df.iterrows():
|
81 |
obj_data = row.to_dict()
|
82 |
-
# Apply world offset
|
83 |
obj_data['pos_x'] += x_offset
|
84 |
-
obj_data['pos_z'] += z_offset
|
85 |
objects.append(obj_data)
|
86 |
return objects
|
87 |
except FileNotFoundError:
|
88 |
st.error(f"File not found during object load: {filename}")
|
89 |
return []
|
90 |
except pd.errors.EmptyDataError:
|
91 |
-
|
92 |
except Exception as e:
|
93 |
st.error(f"Error loading objects from {filename}: {e}")
|
94 |
return []
|
95 |
|
96 |
def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
|
97 |
-
"""Saves object data list to a CSV, making positions relative to plot origin."""
|
98 |
file_path = os.path.join(SAVE_DIR, filename)
|
99 |
relative_objects = []
|
100 |
if not isinstance(objects_data_list, list):
|
@@ -113,11 +105,11 @@ def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
|
|
113 |
|
114 |
relative_obj = {
|
115 |
'obj_id': obj_id, 'type': obj_type,
|
116 |
-
'pos_x': pos.get('x', 0.0) - plot_x_offset,
|
117 |
'pos_y': pos.get('y', 0.0),
|
118 |
-
'pos_z': pos.get('z', 0.0) - plot_z_offset,
|
119 |
-
'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0),
|
120 |
-
'rot_order': rot.get('_order', 'XYZ')
|
121 |
}
|
122 |
relative_objects.append(relative_obj)
|
123 |
|
@@ -130,19 +122,26 @@ def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
|
|
130 |
st.error(f"Failed to save plot data to {filename}: {e}")
|
131 |
return False
|
132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
# --- Page Config ---
|
134 |
-
st.set_page_config(
|
135 |
|
136 |
-
# ---
|
137 |
-
if 'selected_object' not in st.session_state:
|
138 |
-
|
139 |
-
if '
|
|
|
|
|
|
|
140 |
|
141 |
-
# --- Load Plot Metadata ---
|
142 |
-
# This is now the source of truth for saved plots
|
143 |
plots_metadata = load_plot_metadata()
|
144 |
-
|
145 |
-
# --- Load ALL Objects for Rendering ---
|
146 |
all_initial_objects = []
|
147 |
for plot in plots_metadata:
|
148 |
all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset'], plot['z_offset']))
|
@@ -150,93 +149,74 @@ for plot in plots_metadata:
|
|
150 |
# --- Sidebar ---
|
151 |
with st.sidebar:
|
152 |
st.title("🏗️ World Controls")
|
153 |
-
|
154 |
st.header("Navigation (Plots)")
|
155 |
st.caption("Click to teleport player to a plot.")
|
156 |
-
max_cols = 2
|
157 |
cols = st.columns(max_cols)
|
158 |
col_idx = 0
|
159 |
-
# Sort buttons by grid coords for logical layout
|
160 |
sorted_plots_for_nav = sorted(plots_metadata, key=lambda p: (p['grid_x'], p['grid_z']))
|
161 |
for plot in sorted_plots_for_nav:
|
162 |
button_label = f"➡️ {plot.get('name', plot['id'])} ({plot['grid_x']},{plot['grid_z']})"
|
163 |
if cols[col_idx].button(button_label, key=f"nav_{plot['id']}"):
|
164 |
target_x = plot['x_offset']
|
165 |
-
target_z = plot['z_offset']
|
166 |
try:
|
167 |
-
# Tell JS where to teleport (center of plot approx)
|
168 |
js_code = f"teleportPlayer({target_x + PLOT_WIDTH/2}, {target_z + PLOT_DEPTH/2});"
|
|
|
169 |
streamlit_js_eval(js_code=js_code, key=f"teleport_{plot['id']}")
|
170 |
except Exception as e:
|
171 |
-
|
172 |
col_idx = (col_idx + 1) % max_cols
|
173 |
|
174 |
st.markdown("---")
|
175 |
-
|
176 |
-
# --- Object Placement ---
|
177 |
st.header("Place Objects")
|
178 |
object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
|
179 |
current_object_index = object_types.index(st.session_state.selected_object) if st.session_state.selected_object in object_types else 0
|
180 |
-
selected_object_type_widget = st.selectbox(
|
181 |
-
"Select Object:", options=object_types, index=current_object_index, key="selected_object_widget"
|
182 |
-
)
|
183 |
if selected_object_type_widget != st.session_state.selected_object:
|
184 |
st.session_state.selected_object = selected_object_type_widget
|
185 |
-
# Rerun will happen, JS reloads state via sessionStorage, Python injects new selection
|
186 |
|
187 |
st.markdown("---")
|
188 |
-
|
189 |
-
# --- Saving ---
|
190 |
st.header("Save Work")
|
191 |
-
st.caption("Saves newly placed objects to the plot
|
192 |
if st.button("💾 Save Current Work", key="save_button"):
|
193 |
-
|
194 |
-
js_get_data_code = "getSaveDataAndPosition();"
|
195 |
streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
|
196 |
-
st.rerun()
|
197 |
-
|
198 |
|
199 |
-
# --- Process Save Data ---
|
200 |
save_data_from_js = st.session_state.get("js_save_processor", None)
|
201 |
-
|
202 |
if save_data_from_js is not None:
|
203 |
st.info("Received save data from client...")
|
204 |
save_processed_successfully = False
|
205 |
try:
|
206 |
-
# Expecting { playerPosition: {x,y,z}, objectsToSave: [...] }
|
207 |
payload = json.loads(save_data_from_js) if isinstance(save_data_from_js, str) else save_data_from_js
|
208 |
-
|
209 |
if isinstance(payload, dict) and 'playerPosition' in payload and 'objectsToSave' in payload:
|
210 |
player_pos = payload['playerPosition']
|
211 |
objects_to_save = payload['objectsToSave']
|
212 |
-
|
213 |
-
if isinstance(objects_to_save, list): # Allow saving empty list (clears new objects)
|
214 |
-
# Determine target plot based on player position
|
215 |
target_grid_x = math.floor(player_pos.get('x', 0.0) / PLOT_WIDTH)
|
216 |
-
target_grid_z = math.floor(player_pos.get('z', 0.0) / PLOT_DEPTH)
|
217 |
-
|
218 |
target_filename = f"plot_X{target_grid_x}_Z{target_grid_z}.csv"
|
219 |
target_plot_x_offset = target_grid_x * PLOT_WIDTH
|
220 |
target_plot_z_offset = target_grid_z * PLOT_DEPTH
|
221 |
-
|
222 |
st.write(f"Attempting to save plot: {target_filename} (Player at: x={player_pos.get('x', 0):.1f}, z={player_pos.get('z', 0):.1f})")
|
223 |
-
|
224 |
-
# Check if this plot already exists in metadata (for logging/future logic)
|
225 |
is_new_plot_file = not os.path.exists(os.path.join(SAVE_DIR, target_filename))
|
226 |
-
|
227 |
save_ok = save_plot_data(target_filename, objects_to_save, target_plot_x_offset, target_plot_z_offset)
|
228 |
-
|
229 |
if save_ok:
|
230 |
-
load_plot_metadata.clear()
|
231 |
-
try:
|
232 |
-
|
|
|
233 |
except Exception as js_e:
|
234 |
-
|
235 |
-
|
236 |
if is_new_plot_file:
|
237 |
st.success(f"New plot created and saved: {target_filename}")
|
238 |
else:
|
239 |
st.success(f"Updated existing plot: {target_filename}")
|
|
|
|
|
240 |
save_processed_successfully = True
|
241 |
else:
|
242 |
st.error(f"Failed to save plot data to file: {target_filename}")
|
@@ -244,63 +224,36 @@ if save_data_from_js is not None:
|
|
244 |
st.error("Invalid 'objectsToSave' format received (expected list).")
|
245 |
else:
|
246 |
st.error("Invalid save payload structure received from client.")
|
247 |
-
print("Received payload:", payload) # Log for debugging
|
248 |
-
|
249 |
except json.JSONDecodeError:
|
250 |
st.error("Failed to decode save data from client.")
|
251 |
-
print("Received raw data:", save_data_from_js)
|
252 |
except Exception as e:
|
253 |
st.error(f"Error processing save: {e}")
|
254 |
-
st.exception(e)
|
255 |
-
|
256 |
-
# Clear the trigger data from session state
|
257 |
st.session_state.js_save_processor = None
|
258 |
-
# Rerun after processing to reflect changes
|
259 |
if save_processed_successfully:
|
260 |
st.rerun()
|
261 |
|
262 |
-
|
263 |
# --- Main Area ---
|
264 |
st.header("Infinite Shared 3D World")
|
265 |
-
st.caption("Move to empty areas to expand the world. Use sidebar 'Save' to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
266 |
|
267 |
-
# --- Load and Prepare HTML ---
|
268 |
html_file_path = 'index.html'
|
269 |
html_content_with_state = None
|
270 |
-
|
271 |
try:
|
272 |
with open(html_file_path, 'r', encoding='utf-8') as f:
|
273 |
html_template = f.read()
|
274 |
|
275 |
-
# --- Inject Python state into JavaScript ---
|
276 |
js_injection_script = f"""
|
277 |
<script>
|
278 |
-
window.ALL_INITIAL_OBJECTS = {json.dumps(
|
279 |
-
window.PLOTS_METADATA = {json.dumps(
|
280 |
-
window.SELECTED_OBJECT_TYPE = {json
|
281 |
-
window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
|
282 |
-
window.PLOT_DEPTH = {json.dumps(PLOT_DEPTH)};
|
283 |
-
console.log("Streamlit State Injected:", {{
|
284 |
-
selectedObject: window.SELECTED_OBJECT_TYPE,
|
285 |
-
initialObjectsCount: window.ALL_INITIAL_OBJECTS ? window.ALL_INITIAL_OBJECTS.length : 0,
|
286 |
-
plotCount: window.PLOTS_METADATA ? window.PLOTS_METADATA.length : 0,
|
287 |
-
plotWidth: window.PLOT_WIDTH,
|
288 |
-
plotDepth: window.PLOT_DEPTH
|
289 |
-
}});
|
290 |
-
</script>
|
291 |
-
"""
|
292 |
-
html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
|
293 |
-
|
294 |
-
# --- Embed HTML Component ---
|
295 |
-
components.html(
|
296 |
-
html_content_with_state,
|
297 |
-
height=750,
|
298 |
-
scrolling=False
|
299 |
-
)
|
300 |
-
|
301 |
-
except FileNotFoundError:
|
302 |
-
st.error(f"CRITICAL ERROR: Could not find the file '{html_file_path}'.")
|
303 |
-
st.warning(f"Make sure `{html_file_path}` is in the same directory as `app.py` and `{SAVE_DIR}` exists.")
|
304 |
-
except Exception as e:
|
305 |
-
st.error(f"An critical error occurred during HTML preparation or component rendering: {e}")
|
306 |
-
st.exception(e)
|
|
|
5 |
import json
|
6 |
import pandas as pd
|
7 |
import uuid
|
8 |
+
import math
|
9 |
+
import time
|
10 |
+
|
11 |
+
# Import our GameState class
|
12 |
+
from gamestate import GameState
|
13 |
|
14 |
# --- Constants ---
|
15 |
SAVE_DIR = "saved_worlds"
|
16 |
+
PLOT_WIDTH = 50.0 # Width of each plot in 3D space
|
17 |
+
PLOT_DEPTH = 50.0 # Depth of each plot
|
18 |
CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
|
19 |
|
20 |
# --- Ensure Save Directory Exists ---
|
21 |
os.makedirs(SAVE_DIR, exist_ok=True)
|
22 |
|
23 |
+
@st.cache_data(ttl=3600)
|
|
|
|
|
24 |
def load_plot_metadata():
|
25 |
+
"""Scans SAVE_DIR for plot files and returns metadata."""
|
26 |
plots = []
|
|
|
27 |
try:
|
28 |
plot_files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".csv") and f.startswith("plot_X")]
|
29 |
except FileNotFoundError:
|
|
|
33 |
st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
|
34 |
return []
|
35 |
|
|
|
36 |
parsed_plots = []
|
37 |
for filename in plot_files:
|
38 |
try:
|
39 |
+
parts = filename[:-4].split('_') # Remove .csv
|
40 |
+
grid_x = int(parts[1][1:]) # After 'X'
|
41 |
+
grid_z = int(parts[2][1:]) # After 'Z'
|
|
|
42 |
plot_name = " ".join(parts[3:]) if len(parts) > 3 else f"Plot ({grid_x},{grid_z})"
|
|
|
43 |
parsed_plots.append({
|
44 |
+
'id': filename[:-4],
|
45 |
'filename': filename,
|
46 |
'grid_x': grid_x,
|
47 |
'grid_z': grid_z,
|
48 |
'name': plot_name,
|
49 |
'x_offset': grid_x * PLOT_WIDTH,
|
50 |
+
'z_offset': grid_z * PLOT_DEPTH
|
51 |
})
|
52 |
except (IndexError, ValueError):
|
53 |
st.warning(f"Could not parse grid coordinates from filename: {filename}. Skipping.")
|
54 |
continue
|
55 |
|
|
|
56 |
parsed_plots.sort(key=lambda p: (p['grid_x'], p['grid_z']))
|
|
|
57 |
return parsed_plots
|
58 |
|
59 |
def load_plot_objects(filename, x_offset, z_offset):
|
60 |
+
"""Loads objects from a CSV file and applies world offsets."""
|
61 |
file_path = os.path.join(SAVE_DIR, filename)
|
62 |
objects = []
|
63 |
try:
|
64 |
df = pd.read_csv(file_path)
|
|
|
65 |
if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
|
66 |
+
st.warning(f"CSV '{filename}' missing essential columns. Skipping.")
|
67 |
+
return []
|
|
|
68 |
df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
|
69 |
for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
|
70 |
+
if col not in df.columns:
|
71 |
+
df[col] = default
|
72 |
|
73 |
for _, row in df.iterrows():
|
74 |
obj_data = row.to_dict()
|
|
|
75 |
obj_data['pos_x'] += x_offset
|
76 |
+
obj_data['pos_z'] += z_offset
|
77 |
objects.append(obj_data)
|
78 |
return objects
|
79 |
except FileNotFoundError:
|
80 |
st.error(f"File not found during object load: {filename}")
|
81 |
return []
|
82 |
except pd.errors.EmptyDataError:
|
83 |
+
return []
|
84 |
except Exception as e:
|
85 |
st.error(f"Error loading objects from {filename}: {e}")
|
86 |
return []
|
87 |
|
88 |
def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
|
89 |
+
"""Saves object data list to a CSV file, making positions relative to the plot origin."""
|
90 |
file_path = os.path.join(SAVE_DIR, filename)
|
91 |
relative_objects = []
|
92 |
if not isinstance(objects_data_list, list):
|
|
|
105 |
|
106 |
relative_obj = {
|
107 |
'obj_id': obj_id, 'type': obj_type,
|
108 |
+
'pos_x': pos.get('x', 0.0) - plot_x_offset,
|
109 |
'pos_y': pos.get('y', 0.0),
|
110 |
+
'pos_z': pos.get('z', 0.0) - plot_z_offset,
|
111 |
+
'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0),
|
112 |
+
'rot_z': rot.get('_z', 0.0), 'rot_order': rot.get('_order', 'XYZ')
|
113 |
}
|
114 |
relative_objects.append(relative_obj)
|
115 |
|
|
|
122 |
st.error(f"Failed to save plot data to {filename}: {e}")
|
123 |
return False
|
124 |
|
125 |
+
# --- Initialize GameState Singleton ---
|
126 |
+
@st.cache_resource
|
127 |
+
def get_game_state():
|
128 |
+
# This instance is shared across all sessions and reruns.
|
129 |
+
return GameState(save_dir=SAVE_DIR, csv_filename="world_state.csv")
|
130 |
+
|
131 |
+
game_state = get_game_state()
|
132 |
+
|
133 |
# --- Page Config ---
|
134 |
+
st.set_page_config(page_title="Infinite World Builder", layout="wide")
|
135 |
|
136 |
+
# --- Session State Initialization ---
|
137 |
+
if 'selected_object' not in st.session_state:
|
138 |
+
st.session_state.selected_object = 'None'
|
139 |
+
if 'new_plot_name' not in st.session_state:
|
140 |
+
st.session_state.new_plot_name = ""
|
141 |
+
if 'js_save_data_result' not in st.session_state:
|
142 |
+
st.session_state.js_save_data_result = None
|
143 |
|
|
|
|
|
144 |
plots_metadata = load_plot_metadata()
|
|
|
|
|
145 |
all_initial_objects = []
|
146 |
for plot in plots_metadata:
|
147 |
all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset'], plot['z_offset']))
|
|
|
149 |
# --- Sidebar ---
|
150 |
with st.sidebar:
|
151 |
st.title("🏗️ World Controls")
|
|
|
152 |
st.header("Navigation (Plots)")
|
153 |
st.caption("Click to teleport player to a plot.")
|
154 |
+
max_cols = 2
|
155 |
cols = st.columns(max_cols)
|
156 |
col_idx = 0
|
|
|
157 |
sorted_plots_for_nav = sorted(plots_metadata, key=lambda p: (p['grid_x'], p['grid_z']))
|
158 |
for plot in sorted_plots_for_nav:
|
159 |
button_label = f"➡️ {plot.get('name', plot['id'])} ({plot['grid_x']},{plot['grid_z']})"
|
160 |
if cols[col_idx].button(button_label, key=f"nav_{plot['id']}"):
|
161 |
target_x = plot['x_offset']
|
162 |
+
target_z = plot['z_offset']
|
163 |
try:
|
|
|
164 |
js_code = f"teleportPlayer({target_x + PLOT_WIDTH/2}, {target_z + PLOT_DEPTH/2});"
|
165 |
+
from streamlit_js_eval import streamlit_js_eval
|
166 |
streamlit_js_eval(js_code=js_code, key=f"teleport_{plot['id']}")
|
167 |
except Exception as e:
|
168 |
+
st.error(f"Failed to send teleport command: {e}")
|
169 |
col_idx = (col_idx + 1) % max_cols
|
170 |
|
171 |
st.markdown("---")
|
|
|
|
|
172 |
st.header("Place Objects")
|
173 |
object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
|
174 |
current_object_index = object_types.index(st.session_state.selected_object) if st.session_state.selected_object in object_types else 0
|
175 |
+
selected_object_type_widget = st.selectbox("Select Object:", options=object_types, index=current_object_index, key="selected_object_widget")
|
|
|
|
|
176 |
if selected_object_type_widget != st.session_state.selected_object:
|
177 |
st.session_state.selected_object = selected_object_type_widget
|
|
|
178 |
|
179 |
st.markdown("---")
|
|
|
|
|
180 |
st.header("Save Work")
|
181 |
+
st.caption("Saves newly placed objects to the current plot. A new plot file is created for new areas.")
|
182 |
if st.button("💾 Save Current Work", key="save_button"):
|
183 |
+
from streamlit_js_eval import streamlit_js_eval
|
184 |
+
js_get_data_code = "getSaveDataAndPosition();"
|
185 |
streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
|
186 |
+
st.rerun()
|
|
|
187 |
|
188 |
+
# --- Process Save Data from JS ---
|
189 |
save_data_from_js = st.session_state.get("js_save_processor", None)
|
|
|
190 |
if save_data_from_js is not None:
|
191 |
st.info("Received save data from client...")
|
192 |
save_processed_successfully = False
|
193 |
try:
|
|
|
194 |
payload = json.loads(save_data_from_js) if isinstance(save_data_from_js, str) else save_data_from_js
|
|
|
195 |
if isinstance(payload, dict) and 'playerPosition' in payload and 'objectsToSave' in payload:
|
196 |
player_pos = payload['playerPosition']
|
197 |
objects_to_save = payload['objectsToSave']
|
198 |
+
if isinstance(objects_to_save, list):
|
|
|
|
|
199 |
target_grid_x = math.floor(player_pos.get('x', 0.0) / PLOT_WIDTH)
|
200 |
+
target_grid_z = math.floor(player_pos.get('z', 0.0) / PLOT_DEPTH)
|
|
|
201 |
target_filename = f"plot_X{target_grid_x}_Z{target_grid_z}.csv"
|
202 |
target_plot_x_offset = target_grid_x * PLOT_WIDTH
|
203 |
target_plot_z_offset = target_grid_z * PLOT_DEPTH
|
|
|
204 |
st.write(f"Attempting to save plot: {target_filename} (Player at: x={player_pos.get('x', 0):.1f}, z={player_pos.get('z', 0):.1f})")
|
|
|
|
|
205 |
is_new_plot_file = not os.path.exists(os.path.join(SAVE_DIR, target_filename))
|
|
|
206 |
save_ok = save_plot_data(target_filename, objects_to_save, target_plot_x_offset, target_plot_z_offset)
|
|
|
207 |
if save_ok:
|
208 |
+
load_plot_metadata.clear() # Clear cache so metadata reloads
|
209 |
+
try:
|
210 |
+
from streamlit_js_eval import streamlit_js_eval
|
211 |
+
streamlit_js_eval(js_code="resetNewlyPlacedObjects();", key="reset_js_state")
|
212 |
except Exception as js_e:
|
213 |
+
st.warning(f"Could not reset JS state after save: {js_e}")
|
|
|
214 |
if is_new_plot_file:
|
215 |
st.success(f"New plot created and saved: {target_filename}")
|
216 |
else:
|
217 |
st.success(f"Updated existing plot: {target_filename}")
|
218 |
+
# Update shared game state with new objects from this session
|
219 |
+
game_state.update_state(objects_to_save)
|
220 |
save_processed_successfully = True
|
221 |
else:
|
222 |
st.error(f"Failed to save plot data to file: {target_filename}")
|
|
|
224 |
st.error("Invalid 'objectsToSave' format received (expected list).")
|
225 |
else:
|
226 |
st.error("Invalid save payload structure received from client.")
|
|
|
|
|
227 |
except json.JSONDecodeError:
|
228 |
st.error("Failed to decode save data from client.")
|
|
|
229 |
except Exception as e:
|
230 |
st.error(f"Error processing save: {e}")
|
|
|
|
|
|
|
231 |
st.session_state.js_save_processor = None
|
|
|
232 |
if save_processed_successfully:
|
233 |
st.rerun()
|
234 |
|
|
|
235 |
# --- Main Area ---
|
236 |
st.header("Infinite Shared 3D World")
|
237 |
+
st.caption("Move to empty areas to expand the world. Use the sidebar 'Save' to store your work.")
|
238 |
+
|
239 |
+
# Inject state into JS—including the shared GAME_STATE from our GameState singleton.
|
240 |
+
injected_state = {
|
241 |
+
"ALL_INITIAL_OBJECTS": all_initial_objects,
|
242 |
+
"PLOTS_METADATA": plots_metadata,
|
243 |
+
"SELECTED_OBJECT_TYPE": st.session_state.selected_object,
|
244 |
+
"PLOT_WIDTH": PLOT_WIDTH,
|
245 |
+
"PLOT_DEPTH": PLOT_DEPTH,
|
246 |
+
"GAME_STATE": game_state.get_state()
|
247 |
+
}
|
248 |
|
|
|
249 |
html_file_path = 'index.html'
|
250 |
html_content_with_state = None
|
|
|
251 |
try:
|
252 |
with open(html_file_path, 'r', encoding='utf-8') as f:
|
253 |
html_template = f.read()
|
254 |
|
|
|
255 |
js_injection_script = f"""
|
256 |
<script>
|
257 |
+
window.ALL_INITIAL_OBJECTS = {json.dumps(injected_state["ALL_INITIAL_OBJECTS"])};
|
258 |
+
window.PLOTS_METADATA = {json.dumps(injected_state["PLOTS_METADATA"])};
|
259 |
+
window.SELECTED_OBJECT_TYPE = {json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|