awacke1's picture
Update app.py
aaac327 verified
import streamlit as st
import streamlit.components.v1 as components
import random
import json
import os
# Initialize session state
if "entities" not in st.session_state:
st.session_state.entities = []
# Function to get random 3D model file
def get_random_3d_model():
model_dir = "models"
model_files = [f for f in os.listdir(model_dir) if f.endswith(('.glb', '.obj'))]
return os.path.join(model_dir, random.choice(model_files)) if model_files else None
# Function to add a new entity to the scene
def add_entity(entity_type):
model_path = get_random_3d_model()
if model_path:
new_entity = {
'type': entity_type,
'model': model_path,
'position': {
'x': random.uniform(-5, 5),
'y': 0,
'z': random.uniform(-5, 5)
},
'rotation': {
'x': 0,
'y': random.uniform(0, 360),
'z': 0
}
}
st.session_state.entities.append(new_entity)
# Function to generate A-Frame entities
def generate_aframe_entities():
entities_html = ""
for entity in st.session_state.entities:
entities_html += f'''
<a-entity
gltf-model="#{entity['type']}"
position="{entity['position']['x']} {entity['position']['y']} {entity['position']['z']}"
rotation="{entity['rotation']['x']} {entity['rotation']['y']} {entity['rotation']['z']}">
</a-entity>
'''
return entities_html
# HTML template
html_template = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chofko's Ecosystem Simulator</title>
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
</head>
<body>
<a-scene>
<a-assets>
<a-asset-item id="skybike" src="{skybike_model}"></a-asset-item>
<a-asset-item id="heart" src="{heart_model}"></a-asset-item>
</a-assets>
<a-sky color="#ECECEC"></a-sky>
<a-plane position="0 0 0" rotation="-90 0 0" width="10" height="10" color="#7BC8A4"></a-plane>
{entities}
<a-entity camera look-controls position="0 1.6 0"></a-entity>
</a-scene>
</body>
</html>
'''
# Streamlit app
def main():
st.set_page_config(page_title="Chofko's Ecosystem Simulator", layout="wide")
# Sidebar
st.sidebar.title("Chofko's Ecosystem Controls")
if st.sidebar.button("🚲 Add SkyBike"):
add_entity("skybike")
if st.sidebar.button("❤️ Add Heart"):
add_entity("heart")
if st.sidebar.button("🗑️ Clear All Entities"):
st.session_state.entities = []
st.sidebar.subheader("Current Entities")
st.sidebar.json(st.session_state.entities)
# Main area - HTML5 canvas
skybike_model = "models/SkyBike.glb"
heart_model = "models/Heart.obj"
entities_html = generate_aframe_entities()
html_content = html_template.format(
skybike_model=skybike_model,
heart_model=heart_model,
entities=entities_html
)
components.html(html_content, height=600)
if __name__ == "__main__":
main()