awacke1 commited on
Commit
f32aedf
·
verified ·
1 Parent(s): 84a18e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -197
app.py CHANGED
@@ -5,12 +5,14 @@ import os
5
  import json
6
  import pandas as pd
7
  import uuid
8
- from PIL import Image, ImageDraw # Not used for minimap anymore, but kept just in case
 
9
  from streamlit_js_eval import streamlit_js_eval # For JS communication
10
 
11
  # --- Constants ---
12
  SAVE_DIR = "saved_worlds"
13
- PLOT_WIDTH = 50.0 # Width of each plot in 3D space (adjust as needed)
 
14
  CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
15
 
16
  # --- Ensure Save Directory Exists ---
@@ -18,340 +20,287 @@ os.makedirs(SAVE_DIR, exist_ok=True)
18
 
19
  # --- Helper Functions ---
20
 
21
- @st.cache_data(ttl=3600) # Cache plot list for an hour, or clear manually
22
  def load_plot_metadata():
23
- """Scans save dir, sorts plots, calculates metadata."""
24
  plots = []
25
- # Ensure consistent sorting, e.g., alphabetically which often aligns with plot_001, plot_002 etc.
26
  try:
27
- plot_files = sorted([f for f in os.listdir(SAVE_DIR) if f.endswith(".csv")])
28
  except FileNotFoundError:
29
  st.error(f"Save directory '{SAVE_DIR}' not found.")
30
- return [], 0.0 # Return empty if dir doesn't exist
31
  except Exception as e:
32
  st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
33
- return [], 0.0
34
-
35
-
36
- current_x_offset = 0.0
37
- for i, filename in enumerate(plot_files):
38
- # Extract name - assumes format like 'plot_001_MyName.csv' or just 'plot_001.csv'
39
- parts = filename[:-4].split('_') # Remove .csv and split by underscore
40
- plot_id = filename[:-4] # Use filename (without ext) as a unique ID for now
41
- plot_name = " ".join(parts[1:]) if len(parts) > 1 else f"Plot {i+1}" # Try to extract name
42
-
43
- plots.append({
44
- 'id': plot_id, # Use filename as ID
45
- 'name': plot_name,
46
- 'filename': filename,
47
- 'x_offset': current_x_offset
48
- })
49
- current_x_offset += PLOT_WIDTH
50
- # Also return the offset where the next plot would start
51
- return plots, current_x_offset
52
-
53
- def load_plot_objects(filename, x_offset):
54
- """Loads objects from a CSV, applying the plot's x_offset."""
 
 
 
 
 
 
 
 
 
 
55
  file_path = os.path.join(SAVE_DIR, filename)
56
  objects = []
57
  try:
58
  df = pd.read_csv(file_path)
59
- # Check if required columns exist, handle gracefully if not
60
  if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
61
- st.warning(f"CSV '{filename}' missing essential columns (type, pos_x/y/z). Skipping.")
62
  return []
63
- # Ensure optional columns default to something sensible if missing
64
- # Use vectorized operations for defaults where possible
65
  df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
66
  for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
67
  if col not in df.columns: df[col] = default
68
 
69
-
70
  for _, row in df.iterrows():
71
  obj_data = row.to_dict()
72
- # Apply world offset accumulated during loading
73
  obj_data['pos_x'] += x_offset
 
74
  objects.append(obj_data)
75
  return objects
76
  except FileNotFoundError:
77
- # This shouldn't happen if called via load_plot_metadata results, but handle anyway
78
  st.error(f"File not found during object load: {filename}")
79
  return []
80
  except pd.errors.EmptyDataError:
81
- # An empty file is valid, represents an empty plot
82
- return []
83
  except Exception as e:
84
  st.error(f"Error loading objects from {filename}: {e}")
85
  return []
86
 
87
-
88
- def save_plot_data(filename, objects_data_list, plot_x_offset):
89
- """Saves object data list to a new CSV file, making positions relative."""
90
  file_path = os.path.join(SAVE_DIR, filename)
91
  relative_objects = []
92
- # Ensure objects_data_list is actually a list
93
  if not isinstance(objects_data_list, list):
94
  st.error("Invalid data format received for saving (expected a list).")
95
- print("Invalid save data:", objects_data_list) # Log for debugging
96
  return False
97
 
98
  for obj in objects_data_list:
99
- # Validate incoming object structure more carefully
100
  pos = obj.get('position', {})
101
  rot = obj.get('rotation', {})
102
  obj_type = obj.get('type', 'Unknown')
103
- obj_id = obj.get('obj_id', str(uuid.uuid4())) # Generate ID if missing from JS
104
 
105
  if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
106
  print(f"Skipping malformed object during save prep: {obj}")
107
  continue
108
 
109
  relative_obj = {
110
- 'obj_id': obj_id,
111
- 'type': obj_type,
112
- 'pos_x': pos.get('x', 0.0) - plot_x_offset, # Make relative to plot start
113
  'pos_y': pos.get('y', 0.0),
114
- 'pos_z': pos.get('z', 0.0),
115
- 'rot_x': rot.get('_x', 0.0),
116
- 'rot_y': rot.get('_y', 0.0),
117
- 'rot_z': rot.get('_z', 0.0),
118
  'rot_order': rot.get('_order', 'XYZ')
119
  }
120
  relative_objects.append(relative_obj)
121
 
122
  try:
123
- # Only save if there are objects to save
124
- if relative_objects:
125
- df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
126
- df.to_csv(file_path, index=False)
127
- st.success(f"Saved {len(relative_objects)} objects to {filename}")
128
- else:
129
- # Create an empty file with headers if nothing new was placed
130
- pd.DataFrame(columns=CSV_COLUMNS).to_csv(file_path, index=False)
131
- st.info(f"Saved empty plot file: {filename}")
132
  return True
133
  except Exception as e:
134
  st.error(f"Failed to save plot data to {filename}: {e}")
135
  return False
136
 
137
  # --- Page Config ---
138
- st.set_page_config(
139
- page_title="Shared World Builder",
140
- layout="wide"
141
- )
142
 
143
  # --- Initialize Session State ---
144
- if 'selected_object' not in st.session_state:
145
- st.session_state.selected_object = 'None'
146
- if 'new_plot_name' not in st.session_state:
147
- st.session_state.new_plot_name = ""
148
- # Use a more descriptive key for clarity
149
- if 'js_save_data_result' not in st.session_state:
150
- st.session_state.js_save_data_result = None
151
 
152
  # --- Load Plot Metadata ---
153
- # Cached function returns list of plots and the next starting x_offset
154
- plots_metadata, next_plot_x_offset = load_plot_metadata()
155
 
156
  # --- Load ALL Objects for Rendering ---
157
- # This could be slow with many plots!
158
  all_initial_objects = []
159
  for plot in plots_metadata:
160
- all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset']))
161
 
162
  # --- Sidebar ---
163
  with st.sidebar:
164
  st.title("🏗️ World Controls")
165
 
166
  st.header("Navigation (Plots)")
167
- st.caption("Click to teleport player to the start of a plot.")
168
-
169
- # Use columns for a horizontal button layout if desired
170
- max_cols = 3 # Adjust number of columns
171
  cols = st.columns(max_cols)
172
  col_idx = 0
173
- for plot in plots_metadata:
174
- # Use an emoji + name for the button
175
- button_label = f"➡️ {plot.get('name', plot['id'])}" # Fallback to id if name missing
176
- # Use plot filename (unique) as key
177
- if cols[col_idx].button(button_label, key=f"nav_{plot['filename']}"):
178
- # Send command to JS to move the player
179
  target_x = plot['x_offset']
 
180
  try:
181
- streamlit_js_eval(js_code=f"teleportPlayer({target_x});", key=f"teleport_{plot['filename']}")
 
 
182
  except Exception as e:
183
  st.error(f"Failed to send teleport command: {e}")
184
- # No rerun needed here, JS handles the move instantly
185
-
186
- col_idx = (col_idx + 1) % max_cols # Cycle through columns
187
 
188
  st.markdown("---")
189
 
190
  # --- Object Placement ---
191
  st.header("Place Objects")
192
  object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
193
- current_object_index = 0
194
- try:
195
- # Ensure robustness if selected_object is somehow not in list
196
- current_object_index = object_types.index(st.session_state.selected_object)
197
- except ValueError:
198
- st.session_state.selected_object = "None" # Reset to default
199
- current_object_index = 0
200
-
201
  selected_object_type_widget = st.selectbox(
202
- "Select Object:",
203
- options=object_types,
204
- index=current_object_index,
205
- key="selected_object_widget" # Use a distinct key for the widget
206
  )
207
- # Update session state only if the widget's value actually changes
208
- # This change WILL trigger a rerun because Streamlit tracks widget state.
209
- # The JS side now handles preserving its state across the resulting reload via sessionStorage.
210
  if selected_object_type_widget != st.session_state.selected_object:
211
  st.session_state.selected_object = selected_object_type_widget
212
- # We don't *need* to force a rerun here, Streamlit handles it.
213
- # The important part is that the NEXT run will inject the new selected type,
214
- # and the JS will restore placed objects from sessionStorage.
215
-
216
 
217
  st.markdown("---")
218
 
219
  # --- Saving ---
220
- st.header("Save New Plot")
221
- # Ensure text input reflects current state value
222
- st.session_state.new_plot_name = st.text_input(
223
- "Name for New Plot:",
224
- value=st.session_state.new_plot_name,
225
- placeholder="My Awesome Creation",
226
- key="new_plot_name_input" # Use distinct key
227
- )
228
 
229
- if st.button("💾 Save Current Work as New Plot", key="save_button"):
230
- # 1. Trigger JS function `getSaveData()` defined in index.html
231
- # This function collects data for newly placed objects and returns a JSON string.
232
- # The key argument ('js_save_processor') stores the JS result in session_state.
233
- streamlit_js_eval(
234
- js_code="getSaveData();",
235
- key="js_save_processor" # Store result under this key
236
- )
237
- # Small delay MAY sometimes help ensure the value is set before rerun, but usually not needed
238
- # import time
239
- # time.sleep(0.1)
240
- st.rerun() # Rerun to process the result in the next step
241
-
242
-
243
- # --- Process Save Data (if received from JS via the key) ---
244
- # Check the session state key set by the streamlit_js_eval call
245
  save_data_from_js = st.session_state.get("js_save_processor", None)
246
 
247
- if save_data_from_js is not None: # Process only if data is present
248
  st.info("Received save data from client...")
249
  save_processed_successfully = False
250
  try:
251
- # Ensure data is treated as a string before loading json
252
- if isinstance(save_data_from_js, str):
253
- objects_to_save = json.loads(save_data_from_js)
254
- else:
255
- # Handle case where it might already be parsed by chance (less likely)
256
- objects_to_save = save_data_from_js
257
-
258
- # Proceed only if we have a list (even an empty one is ok now)
259
- if isinstance(objects_to_save, list):
260
- # Determine filename for the new plot
261
- new_plot_index = len(plots_metadata) # 0-based index -> number of plots
262
- # Sanitize name: replace spaces, keep only alphanumeric/underscore
263
- plot_name_sanitized = "".join(c for c in st.session_state.new_plot_name if c.isalnum() or c in (' ')).strip().replace(' ', '_')
264
- if not plot_name_sanitized: # Ensure there is a name part
265
- plot_name_sanitized = f"Plot_{new_plot_index + 1}"
266
-
267
- new_filename = f"plot_{new_plot_index:03d}_{plot_name_sanitized}.csv"
268
-
269
- # Save the data, converting world coords to relative coords inside the func
270
- save_ok = save_plot_data(new_filename, objects_to_save, next_plot_x_offset)
271
-
272
- if save_ok:
273
- # Clear the plot metadata cache so it reloads with the new file
274
- load_plot_metadata.clear()
275
- # Reset the new plot name field for next time
276
- st.session_state.new_plot_name = ""
277
- # Reset newly placed objects in JS AFTER successful save
278
- try:
279
- # This call tells JS to clear its internal 'newlyPlacedObjects' array AND sessionStorage
280
- streamlit_js_eval(js_code="resetNewlyPlacedObjects();", key="reset_js_state")
281
- except Exception as js_e:
282
- st.warning(f"Could not reset JS state after save: {js_e}")
283
-
284
- st.success(f"New plot '{plot_name_sanitized}' saved!")
285
- save_processed_successfully = True
 
 
286
  else:
287
- st.error("Failed to save plot data to file.")
288
-
289
  else:
290
- st.error(f"Received invalid save data format from client (expected list): {type(objects_to_save)}")
291
-
292
 
293
  except json.JSONDecodeError:
294
- st.error("Failed to decode save data from client. Data might be corrupted or empty.")
295
- print("Received raw data:", save_data_from_js) # Log raw data
296
  except Exception as e:
297
  st.error(f"Error processing save: {e}")
298
  st.exception(e)
299
 
300
- # IMPORTANT: Clear the session state key regardless of success/failure
301
- # to prevent reprocessing on the next rerun unless the button is clicked again.
302
  st.session_state.js_save_processor = None
303
-
304
- # Rerun AGAIN after processing save to reflect changes (new plot loaded, cache cleared etc.)
305
  if save_processed_successfully:
306
  st.rerun()
307
 
308
 
309
  # --- Main Area ---
310
- st.header("Shared 3D World")
311
- st.caption("Build side-by-side with others. Saving adds a new plot to the right.")
312
 
313
  # --- Load and Prepare HTML ---
314
  html_file_path = 'index.html'
315
- html_content_with_state = None # Initialize
316
 
317
  try:
318
- # --- Read the HTML template file ---
319
  with open(html_file_path, 'r', encoding='utf-8') as f:
320
  html_template = f.read()
321
 
322
- # --- Prepare JavaScript code to inject state ---
323
- # Ensure all state variables are correctly serialized as JSON
324
  js_injection_script = f"""
325
  <script>
326
- // Set global variables BEFORE the main script runs
327
- window.ALL_INITIAL_OBJECTS = {json.dumps(all_initial_objects)}; // All objects from all plots
328
  window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
329
  window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
330
- window.NEXT_PLOT_X_OFFSET = {json.dumps(next_plot_x_offset)}; // Needed for save calculation & ground size
331
- // Basic logging to verify state in browser console
332
  console.log("Streamlit State Injected:", {{
333
  selectedObject: window.SELECTED_OBJECT_TYPE,
334
  initialObjectsCount: window.ALL_INITIAL_OBJECTS ? window.ALL_INITIAL_OBJECTS.length : 0,
 
335
  plotWidth: window.PLOT_WIDTH,
336
- nextPlotX: window.NEXT_PLOT_X_OFFSET
337
  }});
338
  </script>
339
  """
340
- # --- Inject the script into the HTML template ---
341
- # Replacing just before </head> is generally safe
342
  html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
343
 
344
- # --- Embed HTML Component (ONLY if HTML loading and preparation succeeded) ---
345
  components.html(
346
  html_content_with_state,
347
- height=750, # Adjust height as needed
348
  scrolling=False
349
  )
350
 
351
- # --- Error Handling ---
352
  except FileNotFoundError:
353
  st.error(f"CRITICAL ERROR: Could not find the file '{html_file_path}'.")
354
- st.warning(f"Please make sure `{html_file_path}` is in the same directory as `app.py` and that the `{SAVE_DIR}` directory exists.")
355
  except Exception as e:
356
  st.error(f"An critical error occurred during HTML preparation or component rendering: {e}")
357
- st.exception(e) # Show full traceback for debugging
 
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 ---
 
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:
31
  st.error(f"Save directory '{SAVE_DIR}' not found.")
32
+ return []
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)
127
+ st.success(f"Saved {len(relative_objects)} objects to {filename}")
 
 
 
 
 
 
128
  return True
129
  except Exception as e:
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)