awacke1 commited on
Commit
a9aa314
·
verified ·
1 Parent(s): a08719e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -129
app.py CHANGED
@@ -1,36 +1,30 @@
1
  # app.py
2
  import streamlit as st
3
- # st.set_page_config MUST be the very first Streamlit command.
4
- st.set_page_config(page_title="Infinite World Builder", layout="wide")
5
-
6
  import streamlit.components.v1 as components
7
  import os
8
  import json
9
  import pandas as pd
10
  import uuid
11
- import math
12
- import time
13
-
14
- from streamlit_js_eval import streamlit_js_eval # For JS communication
15
-
16
- # Import the GameState class for global state sharing.
17
- from gamestate import GameState
18
 
19
  # --- Constants ---
20
  SAVE_DIR = "saved_worlds"
21
- PLOT_WIDTH = 50.0 # Width of each plot in 3D space
22
- PLOT_DEPTH = 50.0 # Depth of each plot (can be same as width)
23
  CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
24
 
25
  # --- Ensure Save Directory Exists ---
26
  os.makedirs(SAVE_DIR, exist_ok=True)
27
 
28
- # --- Helper Functions (unchanged from your original code) ---
29
 
30
- @st.cache_data(ttl=3600)
31
  def load_plot_metadata():
32
- """Scans SAVE_DIR for plot_X*.csv files, extracts grid coordinates and metadata."""
33
  plots = []
 
34
  try:
35
  plot_files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".csv") and f.startswith("plot_X")]
36
  except FileNotFoundError:
@@ -39,86 +33,94 @@ def load_plot_metadata():
39
  except Exception as e:
40
  st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
41
  return []
42
-
 
43
  parsed_plots = []
44
  for filename in plot_files:
45
  try:
46
- parts = filename[:-4].split('_') # Remove .csv
47
- grid_x = int(parts[1][1:]) # Extract after "X"
48
- grid_z = int(parts[2][1:]) # Extract after "Z"
 
49
  plot_name = " ".join(parts[3:]) if len(parts) > 3 else f"Plot ({grid_x},{grid_z})"
 
50
  parsed_plots.append({
51
- 'id': filename[:-4],
52
  'filename': filename,
53
  'grid_x': grid_x,
54
  'grid_z': grid_z,
55
  'name': plot_name,
56
  'x_offset': grid_x * PLOT_WIDTH,
57
- 'z_offset': grid_z * PLOT_DEPTH
58
  })
59
  except (IndexError, ValueError):
60
  st.warning(f"Could not parse grid coordinates from filename: {filename}. Skipping.")
61
  continue
62
-
 
63
  parsed_plots.sort(key=lambda p: (p['grid_x'], p['grid_z']))
 
64
  return parsed_plots
65
 
66
  def load_plot_objects(filename, x_offset, z_offset):
67
- """Loads objects from a CSV file and applies world offsets."""
68
  file_path = os.path.join(SAVE_DIR, filename)
69
  objects = []
70
  try:
71
  df = pd.read_csv(file_path)
 
72
  if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
73
  st.warning(f"CSV '{filename}' missing essential columns. Skipping.")
74
  return []
75
- # Ensure an obj_id exists for each row.
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
- if col not in df.columns:
79
- df[col] = default
80
  for _, row in df.iterrows():
81
  obj_data = row.to_dict()
82
- # Apply plot offsets to positions.
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
- return []
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 file, making positions relative to the plot origin."""
98
  file_path = os.path.join(SAVE_DIR, filename)
99
  relative_objects = []
100
  if not isinstance(objects_data_list, list):
101
  st.error("Invalid data format received for saving (expected a list).")
102
  return False
103
-
104
  for obj in objects_data_list:
105
  pos = obj.get('position', {})
106
  rot = obj.get('rotation', {})
107
  obj_type = obj.get('type', 'Unknown')
108
  obj_id = obj.get('obj_id', str(uuid.uuid4()))
 
109
  if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
110
  print(f"Skipping malformed object during save prep: {obj}")
111
  continue
 
112
  relative_obj = {
113
  'obj_id': obj_id, 'type': obj_type,
114
- 'pos_x': pos.get('x', 0.0) - plot_x_offset,
115
  'pos_y': pos.get('y', 0.0),
116
- 'pos_z': pos.get('z', 0.0) - plot_z_offset,
117
- 'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0),
118
- 'rot_z': rot.get('_z', 0.0), 'rot_order': rot.get('_order', 'XYZ')
119
  }
120
  relative_objects.append(relative_obj)
121
-
122
  try:
123
  df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
124
  df.to_csv(file_path, index=False)
@@ -128,144 +130,177 @@ def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
128
  st.error(f"Failed to save plot data to {filename}: {e}")
129
  return False
130
 
131
- # --- Global State Management ---
132
-
133
- # Create a singleton GameState instance using st.cache_resource.
134
- @st.cache_resource
135
- def get_game_state():
136
- return GameState(state_file="global_state.json")
137
 
138
- game_state = get_game_state()
 
 
 
139
 
140
- # --- Page Config and Session State Initialization ---
141
- # (st.set_page_config already called at top.)
142
- if 'selected_object' not in st.session_state:
143
- st.session_state.selected_object = 'None'
144
- if 'js_save_data' not in st.session_state:
145
- st.session_state.js_save_data = None
146
-
147
- # --- Load Plot Metadata and Initial Objects ---
148
  plots_metadata = load_plot_metadata()
 
 
149
  all_initial_objects = []
150
  for plot in plots_metadata:
151
  all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset'], plot['z_offset']))
152
 
153
- # Optionally, merge the objects from your CSVs into the global state if not already present.
154
- if not game_state.get_state().get("objects"):
155
- game_state.update_state(all_initial_objects)
156
-
157
- # --- Sidebar Controls ---
158
  with st.sidebar:
159
  st.title("🏗️ World Controls")
 
160
  st.header("Navigation (Plots)")
161
  st.caption("Click to teleport player to a plot.")
162
- max_cols = 2
163
  cols = st.columns(max_cols)
164
  col_idx = 0
 
165
  sorted_plots_for_nav = sorted(plots_metadata, key=lambda p: (p['grid_x'], p['grid_z']))
166
  for plot in sorted_plots_for_nav:
167
  button_label = f"➡️ {plot.get('name', plot['id'])} ({plot['grid_x']},{plot['grid_z']})"
168
  if cols[col_idx].button(button_label, key=f"nav_{plot['id']}"):
169
  target_x = plot['x_offset']
170
- target_z = plot['z_offset']
171
  try:
 
172
  js_code = f"teleportPlayer({target_x + PLOT_WIDTH/2}, {target_z + PLOT_DEPTH/2});"
173
  streamlit_js_eval(js_code=js_code, key=f"teleport_{plot['id']}")
174
  except Exception as e:
175
- st.error(f"Failed to send teleport command: {e}")
176
  col_idx = (col_idx + 1) % max_cols
177
 
178
  st.markdown("---")
 
 
179
  st.header("Place Objects")
180
  object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
181
  current_object_index = object_types.index(st.session_state.selected_object) if st.session_state.selected_object in object_types else 0
182
- selected_object_type_widget = st.selectbox("Select Object:", options=object_types, index=current_object_index, key="selected_object_widget")
 
 
183
  if selected_object_type_widget != st.session_state.selected_object:
184
  st.session_state.selected_object = selected_object_type_widget
 
185
 
186
  st.markdown("---")
 
 
187
  st.header("Save Work")
188
- st.caption("Saves newly placed objects to the current plot and updates the global state.")
189
  if st.button("💾 Save Current Work", key="save_button"):
190
- try:
191
- # Trigger JS to get data (player position and new objects).
192
- js_get_data_code = "getSaveDataAndPosition();"
193
- streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
194
- except Exception as e:
195
- st.error(f"Error triggering JS save: {e}")
196
- st.experimental_rerun()
197
 
198
- st.markdown("---")
199
- st.header("Download Global State as Markdown")
200
- global_state = game_state.get_state()
201
- default_md_name = global_state.get("last_updated", "save").replace(":", "").replace(" ", "_") + ".md"
202
- download_name = st.text_input("Override File Name", value=default_md_name)
203
- md_outline = f"""# Global Save: {download_name}
204
- - **Timestamp:** {global_state.get("last_updated", "N/A")}
205
- - 🎮 **Number of Game Objects:** {len(global_state.get("objects", []))}
206
-
207
- ## Game Objects:
208
- """
209
- for i, obj in enumerate(global_state.get("objects", []), start=1):
210
- obj_type = obj.get("type", "Unknown")
211
- pos = (obj.get("x", 0), obj.get("y", 0), obj.get("z", 0))
212
- md_outline += f"- {i}. ✨ **{obj_type}** at {pos}\n"
213
- st.download_button("Download Markdown Save", data=md_outline, file_name=download_name, mime="text/markdown")
214
-
215
- # --- Process Save Data from JS ---
216
- save_data_from_js = st.session_state.get("js_save_data", None)
217
- if save_data_from_js:
218
  try:
219
- payload = json.loads(save_data_from_js) if isinstance(save_data_from_js, str) else save_data_from_js
220
- if isinstance(payload, dict) and "playerPosition" in payload and "objectsToSave" in payload:
221
- player_pos = payload["playerPosition"]
222
- new_objects = payload["objectsToSave"]
223
- # Optionally, add additional info (like a timestamp) to each new object.
224
- for obj in new_objects:
225
- obj["timestamp"] = time.strftime("%Y-%m-%d %H:%M:%S")
226
- game_state.update_state(new_objects)
227
- st.success("Global state updated with new objects.")
228
- st.session_state["js_save_data"] = None
229
- st.experimental_rerun()
230
- else:
231
- st.error("Invalid payload received from client.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  except Exception as e:
233
- st.error(f"Error processing save data: {e}")
234
- st.session_state["js_save_data"] = None
 
 
 
 
 
 
 
235
 
236
  # --- Main Area ---
237
  st.header("Infinite Shared 3D World")
238
- st.caption("Move to empty areas to expand the world. Use the sidebar 'Save' controls to store your work.")
239
-
240
- # --- Inject State into HTML ---
241
- # We inject both the original objects (for initial 3D scene rendering) and the global state.
242
- injected_state = {
243
- "ALL_INITIAL_OBJECTS": all_initial_objects,
244
- "PLOTS_METADATA": plots_metadata,
245
- "SELECTED_OBJECT_TYPE": st.session_state.selected_object,
246
- "PLOT_WIDTH": PLOT_WIDTH,
247
- "PLOT_DEPTH": PLOT_DEPTH,
248
- "GLOBAL_STATE": game_state.get_state()
249
- }
250
-
251
- html_file_path = "index.html"
252
  try:
253
- with open(html_file_path, "r", encoding="utf-8") as f:
254
- html_template = f.read()
 
 
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.dumps(injected_state["SELECTED_OBJECT_TYPE"])};
260
- window.PLOT_WIDTH = {json.dumps(injected_state["PLOT_WIDTH"])};
261
- window.PLOT_DEPTH = {json.dumps(injected_state["PLOT_DEPTH"])};
262
- window.GLOBAL_STATE = {json.dumps(injected_state["GLOBAL_STATE"])};
263
- console.log("Injected Global State:", window.GLOBAL_STATE);
 
 
 
 
 
264
  </script>
265
  """
266
- html_content_with_state = html_template.replace("</head>", js_injection_script + "\n</head>", 1)
267
- components.html(html_content_with_state, height=750, scrolling=False)
 
 
 
 
 
 
 
268
  except FileNotFoundError:
269
  st.error(f"CRITICAL ERROR: Could not find the file '{html_file_path}'.")
 
270
  except Exception as e:
271
- st.error(f"An error occurred during HTML component rendering: {e}")
 
 
1
  # app.py
2
  import streamlit as st
 
 
 
3
  import streamlit.components.v1 as components
4
  import os
5
  import json
6
  import pandas as pd
7
  import uuid
8
+ import math # For floor function
9
+ # from PIL import Image, ImageDraw # No longer needed for minimap
10
+ from streamlit_js_eval import streamlit_js_eval # For JS communication
 
 
 
 
11
 
12
  # --- Constants ---
13
  SAVE_DIR = "saved_worlds"
14
+ PLOT_WIDTH = 50.0 # Width of each plot in 3D space
15
+ PLOT_DEPTH = 50.0 # Depth of each plot (can be same as width)
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
+ # --- Helper Functions ---
22
 
23
+ @st.cache_data(ttl=3600) # Cache plot list
24
  def load_plot_metadata():
25
+ """Scans save dir for plot_X*_Z*.csv, sorts, calculates metadata."""
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:
 
33
  except Exception as e:
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('_') # Remove .csv
42
+ grid_x = int(parts[1][1:]) # Extract number after X
43
+ grid_z = int(parts[2][1:]) # Extract number after Z
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], # Use filename base as unique ID
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 # Use PLOT_DEPTH for Z offset
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, applying the plot's world offsets."""
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
  st.warning(f"CSV '{filename}' missing essential columns. Skipping.")
74
  return []
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
+ if col not in df.columns: df[col] = default
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 # Apply Z offset too
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
+ return [] # Empty file is valid
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):
101
  st.error("Invalid data format received for saving (expected a list).")
102
  return False
103
+
104
  for obj in objects_data_list:
105
  pos = obj.get('position', {})
106
  rot = obj.get('rotation', {})
107
  obj_type = obj.get('type', 'Unknown')
108
  obj_id = obj.get('obj_id', str(uuid.uuid4()))
109
+
110
  if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
111
  print(f"Skipping malformed object during save prep: {obj}")
112
  continue
113
+
114
  relative_obj = {
115
  'obj_id': obj_id, 'type': obj_type,
116
+ 'pos_x': pos.get('x', 0.0) - plot_x_offset, # Make relative X
117
  'pos_y': pos.get('y', 0.0),
118
+ 'pos_z': pos.get('z', 0.0) - plot_z_offset, # Make relative Z
119
+ 'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0), 'rot_z': rot.get('_z', 0.0),
120
+ 'rot_order': rot.get('_order', 'XYZ')
121
  }
122
  relative_objects.append(relative_obj)
123
+
124
  try:
125
  df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
126
  df.to_csv(file_path, index=False)
 
130
  st.error(f"Failed to save plot data to {filename}: {e}")
131
  return False
132
 
133
+ # --- Page Config ---
134
+ st.set_page_config( page_title="Infinite World Builder", layout="wide")
 
 
 
 
135
 
136
+ # --- Initialize Session State ---
137
+ if 'selected_object' not in st.session_state: st.session_state.selected_object = 'None'
138
+ if 'new_plot_name' not in st.session_state: st.session_state.new_plot_name = "" # No longer used for filename
139
+ if 'js_save_data_result' not in st.session_state: st.session_state.js_save_data_result = None
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']))
149
 
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 # Adjust columns for potentially more buttons
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'] # Use Z offset too
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
+ st.error(f"Failed to send teleport command: {e}")
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 the player is currently in. If it's a new area, a new plot file is created.")
192
  if st.button("💾 Save Current Work", key="save_button"):
193
+ # Trigger JS to get data AND player position
194
+ js_get_data_code = "getSaveDataAndPosition();" # JS function needs update
195
+ streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
196
+ st.rerun() # Rerun to process result
 
 
 
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) # Use Z pos too
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() # Clear cache to force reload metadata
231
+ try: # Tell JS to clear its unsaved state
232
+ streamlit_js_eval(js_code="resetNewlyPlacedObjects();", key="reset_js_state")
233
+ except Exception as js_e:
234
+ st.warning(f"Could not reset JS state after save: {js_e}")
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}")
243
+ else:
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 save work to current plot.")
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(all_initial_objects)};
279
+ window.PLOTS_METADATA = {json.dumps(plots_metadata)}; // Send plot info to JS
280
+ window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
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)