Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,6 +7,7 @@ def load_aframe_and_extras():
|
|
7 |
return """
|
8 |
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
|
9 |
<script src="https://unpkg.com/[email protected]/dist/aframe-event-set-component.min.js"></script>
|
|
|
10 |
<script>
|
11 |
let score = 0;
|
12 |
AFRAME.registerComponent('draggable', {
|
@@ -33,142 +34,43 @@ def load_aframe_and_extras():
|
|
33 |
},
|
34 |
dragMove: function (evt) {
|
35 |
if (!this.isDragging) return;
|
36 |
-
var camera = this.camera;
|
37 |
-
var
|
38 |
-
|
39 |
-
var
|
40 |
-
|
41 |
-
var
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
}
|
44 |
});
|
45 |
-
|
46 |
-
|
47 |
-
speed: {type: 'vec3', default: {x: 0.1, y: 0.1, z: 0.1}},
|
48 |
-
dist: {type: 'vec3', default: {x: 0.5, y: 0.5, z: 0.5}}
|
49 |
-
},
|
50 |
-
init: function () {
|
51 |
-
this.originalPos = this.el.getAttribute('position');
|
52 |
-
this.dir = {x: 1, y: 1, z: 1};
|
53 |
-
},
|
54 |
-
tick: function (time, timeDelta) {
|
55 |
-
var currentPos = this.el.getAttribute('position');
|
56 |
-
var speed = this.data.speed;
|
57 |
-
var dist = this.data.dist;
|
58 |
-
['x', 'y', 'z'].forEach(axis => {
|
59 |
-
currentPos[axis] += speed[axis] * this.dir[axis] * (timeDelta / 1000);
|
60 |
-
if (Math.abs(currentPos[axis] - this.originalPos[axis]) > dist[axis]) {
|
61 |
-
this.dir[axis] *= -1;
|
62 |
-
}
|
63 |
-
});
|
64 |
-
this.el.setAttribute('position', currentPos);
|
65 |
-
},
|
66 |
-
boost: function() {
|
67 |
-
var speed = this.data.speed;
|
68 |
-
['x', 'y', 'z'].forEach(axis => {
|
69 |
-
speed[axis] *= 1.5;
|
70 |
-
});
|
71 |
-
this.data.speed = speed;
|
72 |
-
this.dir = {
|
73 |
-
x: Math.random() > 0.5 ? 1 : -1,
|
74 |
-
y: Math.random() > 0.5 ? 1 : -1,
|
75 |
-
z: Math.random() > 0.5 ? 1 : -1
|
76 |
-
};
|
77 |
-
}
|
78 |
-
});
|
79 |
-
AFRAME.registerComponent('moving-light', {
|
80 |
schema: {
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
},
|
85 |
init: function () {
|
86 |
-
this.
|
87 |
-
this.
|
88 |
-
this.light.setAttribute('type', 'point');
|
89 |
-
this.light.setAttribute('color', this.data.color);
|
90 |
-
this.light.setAttribute('intensity', '0.75');
|
91 |
-
this.el.appendChild(this.light);
|
92 |
},
|
93 |
-
tick: function (time,
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
['x', 'y', 'z'].forEach(axis => {
|
98 |
-
currentPos[axis] += speed[axis] * this.dir[axis] * (timeDelta / 1000);
|
99 |
-
if (Math.abs(currentPos[axis]) > bounds[axis]) {
|
100 |
-
this.dir[axis] *= -1;
|
101 |
-
}
|
102 |
-
});
|
103 |
-
this.el.setAttribute('position', currentPos);
|
104 |
-
}
|
105 |
-
});
|
106 |
-
function moveCamera(direction) {
|
107 |
-
var camera = document.querySelector('[camera]');
|
108 |
-
var rig = document.querySelector('#rig');
|
109 |
-
var pos = rig.getAttribute('position');
|
110 |
-
var rot = rig.getAttribute('rotation');
|
111 |
-
var speed = 0.5;
|
112 |
-
var rotationSpeed = 5;
|
113 |
-
switch(direction) {
|
114 |
-
case 'up': pos.y += speed; break;
|
115 |
-
case 'down': pos.y -= speed; break;
|
116 |
-
case 'forward': pos.z -= speed; break;
|
117 |
-
case 'left': pos.x -= speed; break;
|
118 |
-
case 'right': pos.x += speed; break;
|
119 |
-
case 'rotateLeft': rot.y += rotationSpeed; break;
|
120 |
-
case 'rotateRight': rot.y -= rotationSpeed; break;
|
121 |
-
case 'reset': pos = {x: 0, y: 10, z: 0}; rot = {x: -90, y: 0, z: 0}; break;
|
122 |
-
case 'ground': pos = {x: 0, y: 1.6, z: 0}; rot = {x: 0, y: 0, z: 0}; break;
|
123 |
-
}
|
124 |
-
rig.setAttribute('position', pos);
|
125 |
-
rig.setAttribute('rotation', rot);
|
126 |
-
}
|
127 |
-
function fireRaycast() {
|
128 |
-
var camera = document.querySelector('[camera]');
|
129 |
-
var direction = new THREE.Vector3();
|
130 |
-
camera.object3D.getWorldDirection(direction);
|
131 |
-
var raycaster = new THREE.Raycaster();
|
132 |
-
raycaster.set(camera.object3D.position, direction);
|
133 |
-
var intersects = raycaster.intersectObjects(document.querySelectorAll('.raycastable').map(el => el.object3D), true);
|
134 |
-
if (intersects.length > 0) {
|
135 |
-
var hitObject = intersects[0].object.el;
|
136 |
-
if (hitObject.components.bouncing) {
|
137 |
-
hitObject.components.bouncing.boost();
|
138 |
-
score += 10;
|
139 |
-
document.getElementById('score').setAttribute('value', 'Score: ' + score);
|
140 |
-
}
|
141 |
-
}
|
142 |
-
}
|
143 |
-
document.addEventListener('keydown', function(event) {
|
144 |
-
switch(event.key.toLowerCase()) {
|
145 |
-
case 'w': moveCamera('up'); break;
|
146 |
-
case 's': moveCamera('forward'); break;
|
147 |
-
case 'x': moveCamera('down'); break;
|
148 |
-
case 'q': moveCamera('rotateLeft'); break;
|
149 |
-
case 'e': moveCamera('rotateRight'); break;
|
150 |
-
case 'z': moveCamera('reset'); break;
|
151 |
-
case 'c': moveCamera('ground'); break;
|
152 |
-
case ' ': fireRaycast(); break;
|
153 |
}
|
154 |
});
|
155 |
</script>
|
156 |
"""
|
157 |
|
158 |
-
def create_aframe_entity(file_stem, file_type, position):
|
159 |
-
rotation = f"0 {random.uniform(0, 360)} 0"
|
160 |
-
bounce_speed = f"{random.uniform(0.05, 0.1)} {random.uniform(0.05, 0.1)} {random.uniform(0.05, 0.1)}"
|
161 |
-
bounce_dist = f"0.1 0.1 0.1"
|
162 |
-
if file_type == 'obj':
|
163 |
-
return f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" obj-model="obj: #{file_stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
|
164 |
-
elif file_type == 'glb':
|
165 |
-
return f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" gltf-model="#{file_stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
|
166 |
-
elif file_type in ['webp', 'png']:
|
167 |
-
return f'<a-image position="{position}" rotation="-90 0 0" src="#{file_stem}" width="0.5" height="0.5" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-image>'
|
168 |
-
elif file_type == 'mp4':
|
169 |
-
return f'<a-video position="{position}" rotation="-90 0 0" src="#{file_stem}" width="0.5" height="0.5" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-video>'
|
170 |
-
return ''
|
171 |
-
|
172 |
@st.cache_data
|
173 |
def encode_file(file_path):
|
174 |
with open(file_path, "rb") as file:
|
@@ -181,8 +83,12 @@ def generate_tilemap(files, directory, grid_width, grid_height, max_unique_model
|
|
181 |
tile_size = 1
|
182 |
start_x = -(grid_width * tile_size) / 2
|
183 |
start_z = -(grid_height * tile_size) / 2
|
184 |
-
|
|
|
185 |
encoded_files = {}
|
|
|
|
|
|
|
186 |
for file in unique_files:
|
187 |
file_path = os.path.join(directory, file)
|
188 |
file_type = file.split('.')[-1]
|
@@ -190,19 +96,36 @@ def generate_tilemap(files, directory, grid_width, grid_height, max_unique_model
|
|
190 |
encoded_files[file] = encoded_file
|
191 |
if file_type in ['obj', 'glb']:
|
192 |
assets += f'<a-asset-item id="{Path(file).stem}" src="data:application/octet-stream;base64,{encoded_file}"></a-asset-item>'
|
193 |
-
elif file_type in ['webp', 'png'
|
194 |
-
mime_type = f"image/{file_type}"
|
195 |
-
assets += f'<
|
|
|
|
|
|
|
196 |
for i in range(grid_width):
|
197 |
for j in range(grid_height):
|
198 |
x = start_x + (i * tile_size)
|
199 |
z = start_z + (j * tile_size)
|
200 |
position = f"{x} 0 {z}"
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
return assets, entities
|
207 |
|
208 |
def main():
|
@@ -212,32 +135,20 @@ def main():
|
|
212 |
st.markdown("[Open 3D Animation Toolkit](https://huggingface.co/spaces/awacke1/3d_animation_toolkit)", unsafe_allow_html=True)
|
213 |
st.markdown("### ⬆️ Upload")
|
214 |
uploaded_files = st.file_uploader("Add files:", accept_multiple_files=True, key="file_uploader")
|
215 |
-
st.markdown("### 🎮 Camera Controls")
|
216 |
-
col1, col2, col3 = st.columns(3)
|
217 |
-
with col1:
|
218 |
-
st.button("⬅️", on_click=lambda: st.session_state.update({'camera_move': 'left'}))
|
219 |
-
st.button("🔄↺", on_click=lambda: st.session_state.update({'camera_move': 'rotateLeft'}))
|
220 |
-
st.button("🔝", on_click=lambda: st.session_state.update({'camera_move': 'reset'}))
|
221 |
-
with col2:
|
222 |
-
st.button("⬆️", on_click=lambda: st.session_state.update({'camera_move': 'up'}))
|
223 |
-
st.button("👀", on_click=lambda: st.session_state.update({'camera_move': 'ground'}))
|
224 |
-
st.button("🔫", on_click=lambda: st.session_state.update({'camera_move': 'fire'}))
|
225 |
-
with col3:
|
226 |
-
st.button("➡️", on_click=lambda: st.session_state.update({'camera_move': 'right'}))
|
227 |
-
st.button("⬇️", on_click=lambda: st.session_state.update({'camera_move': 'down'}))
|
228 |
-
st.button("⏩", on_click=lambda: st.session_state.update({'camera_move': 'forward'}))
|
229 |
st.markdown("### 🗺️ Grid Size")
|
230 |
-
grid_width = st.slider("Grid Width", 1,
|
231 |
-
grid_height = st.slider("Grid Height", 1,
|
232 |
st.markdown("### ℹ️ Instructions")
|
233 |
-
st.write("-
|
|
|
|
|
234 |
st.markdown("### 📁 Directory")
|
235 |
directory = st.text_input("Enter path:", ".", key="directory_input")
|
236 |
-
|
237 |
if not os.path.isdir(directory):
|
238 |
st.sidebar.error("Invalid directory path")
|
239 |
return
|
240 |
-
file_types = ['obj', 'glb', 'webp', 'png'
|
241 |
if uploaded_files:
|
242 |
for uploaded_file in uploaded_files:
|
243 |
file_extension = Path(uploaded_file.name).suffix.lower()[1:]
|
@@ -251,28 +162,19 @@ def main():
|
|
251 |
|
252 |
aframe_scene = f"""
|
253 |
<a-scene embedded style="height: 600px; width: 100%;">
|
254 |
-
|
255 |
-
<a-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
|
|
|
|
|
|
262 |
"""
|
263 |
-
|
264 |
-
assets, entities = generate_tilemap(files, directory, grid_width, grid_height, max_unique_models=5)
|
265 |
-
aframe_scene += assets + entities + "</a-scene>"
|
266 |
-
|
267 |
-
camera_move = st.session_state.get('camera_move', None)
|
268 |
-
if camera_move:
|
269 |
-
if camera_move == 'fire':
|
270 |
-
aframe_scene += "<script>fireRaycast();</script>"
|
271 |
-
else:
|
272 |
-
aframe_scene += f"<script>moveCamera('{camera_move}');</script>"
|
273 |
-
st.session_state.pop('camera_move')
|
274 |
-
|
275 |
-
st.components.v1.html(load_aframe_and_extras() + aframe_scene, height=600)
|
276 |
|
277 |
if __name__ == "__main__":
|
278 |
main()
|
|
|
7 |
return """
|
8 |
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
|
9 |
<script src="https://unpkg.com/[email protected]/dist/aframe-event-set-component.min.js"></script>
|
10 |
+
<script src="https://cdn.jsdelivr.net/npm/aframe-volumetric-fog@latest/dist/aframe-volumetric-fog.min.js"></script>
|
11 |
<script>
|
12 |
let score = 0;
|
13 |
AFRAME.registerComponent('draggable', {
|
|
|
34 |
},
|
35 |
dragMove: function (evt) {
|
36 |
if (!this.isDragging) return;
|
37 |
+
var camera = this.camera.getObject3D('camera');
|
38 |
+
var worldPos = new THREE.Vector3();
|
39 |
+
camera.getWorldPosition(worldPos);
|
40 |
+
var worldDir = new THREE.Vector3();
|
41 |
+
camera.getWorldDirection(worldDir);
|
42 |
+
var camX = worldPos.x;
|
43 |
+
var camY = worldPos.y;
|
44 |
+
var camZ = worldPos.z;
|
45 |
+
var dirX = worldDir.x;
|
46 |
+
var dirY = worldDir.y;
|
47 |
+
var dirZ = worldDir.z;
|
48 |
+
var t = -camY / dirY;
|
49 |
+
var moveX = camX + t * dirX;
|
50 |
+
var moveZ = camZ + t * dirZ;
|
51 |
+
this.el.setAttribute('position', moveX + " " + 0.0 + " " + moveZ);
|
52 |
}
|
53 |
});
|
54 |
+
|
55 |
+
AFRAME.registerComponent('undulating-rotation', {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
schema: {
|
57 |
+
speed: { type: 'number', default: 1 }, // Base rotation speed
|
58 |
+
amplitude: { type: 'number', default: 20 }, // Maximum rotation in degrees
|
59 |
+
frequency: { type: 'number', default: 0.5 } // Speed of undulation
|
60 |
},
|
61 |
init: function () {
|
62 |
+
this.initialRotation = Math.random() * 360; // Random initial rotation
|
63 |
+
this.time = 0;
|
|
|
|
|
|
|
|
|
64 |
},
|
65 |
+
tick: function (time, deltaTime) {
|
66 |
+
this.time += deltaTime / 1000;
|
67 |
+
const rotationAmount = Math.sin(this.time * this.data.frequency) * this.data.amplitude;
|
68 |
+
this.el.setAttribute('rotation', { x: 0, y: this.initialRotation + rotationAmount, z: 0 });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
}
|
70 |
});
|
71 |
</script>
|
72 |
"""
|
73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
@st.cache_data
|
75 |
def encode_file(file_path):
|
76 |
with open(file_path, "rb") as file:
|
|
|
83 |
tile_size = 1
|
84 |
start_x = -(grid_width * tile_size) / 2
|
85 |
start_z = -(grid_height * tile_size) / 2
|
86 |
+
available_models = [f for f in files if f.endswith(('.obj', '.glb'))]
|
87 |
+
available_images = [f for f in files if f.endswith(('.webp', '.png'))]
|
88 |
encoded_files = {}
|
89 |
+
|
90 |
+
unique_files = random.sample(files, min(len(files), max_unique_models))
|
91 |
+
|
92 |
for file in unique_files:
|
93 |
file_path = os.path.join(directory, file)
|
94 |
file_type = file.split('.')[-1]
|
|
|
96 |
encoded_files[file] = encoded_file
|
97 |
if file_type in ['obj', 'glb']:
|
98 |
assets += f'<a-asset-item id="{Path(file).stem}" src="data:application/octet-stream;base64,{encoded_file}"></a-asset-item>'
|
99 |
+
elif file_type in ['webp', 'png']:
|
100 |
+
mime_type = f"image/{file_type}"
|
101 |
+
assets += f'<img id="{Path(file).stem}" src="data:{mime_type};base64,{encoded_file}" />'
|
102 |
+
|
103 |
+
assets += "</a-assets>"
|
104 |
+
|
105 |
for i in range(grid_width):
|
106 |
for j in range(grid_height):
|
107 |
x = start_x + (i * tile_size)
|
108 |
z = start_z + (j * tile_size)
|
109 |
position = f"{x} 0 {z}"
|
110 |
+
|
111 |
+
chosen_file = random.choice(files)
|
112 |
+
file_type = chosen_file.split('.')[-1]
|
113 |
+
file_stem = Path(chosen_file).stem
|
114 |
+
rotation = f"0 {random.uniform(0, 360)} 0"
|
115 |
+
bounce_speed = f"{random.uniform(0.01, 0.03)} {random.uniform(0.01, 0.03)} {random.uniform(0.01, 0.03)}"
|
116 |
+
amplitude = random.uniform(5, 15)
|
117 |
+
frequency = random.uniform(0.1, 0.5)
|
118 |
+
|
119 |
+
if file_type == 'obj':
|
120 |
+
entities += f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" obj-model="obj: #{file_stem}" class="raycastable" draggable undulating-rotation="amplitude: {amplitude}; frequency: {frequency}"></a-entity>'
|
121 |
+
elif file_type == 'glb':
|
122 |
+
entities += f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" gltf-model="#{file_stem}" class="raycastable" draggable undulating-rotation="amplitude: {amplitude}; frequency: {frequency}"></a-entity>'
|
123 |
+
elif file_type in ['webp', 'png']:
|
124 |
+
if available_images:
|
125 |
+
random_image = random.choice(available_images)
|
126 |
+
image_stem = Path(random_image).stem
|
127 |
+
entities += f'<a-plane position="{position}" rotation="-90 0 0" width="{tile_size}" height="{tile_size}" material="src: #{image_stem}" class="raycastable" draggable></a-plane>'
|
128 |
+
|
129 |
return assets, entities
|
130 |
|
131 |
def main():
|
|
|
135 |
st.markdown("[Open 3D Animation Toolkit](https://huggingface.co/spaces/awacke1/3d_animation_toolkit)", unsafe_allow_html=True)
|
136 |
st.markdown("### ⬆️ Upload")
|
137 |
uploaded_files = st.file_uploader("Add files:", accept_multiple_files=True, key="file_uploader")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
st.markdown("### 🗺️ Grid Size")
|
139 |
+
grid_width = st.slider("Grid Width", 1, 10, 8)
|
140 |
+
grid_height = st.slider("Grid Height", 1, 10, 5)
|
141 |
st.markdown("### ℹ️ Instructions")
|
142 |
+
st.write("- Click and drag to move objects")
|
143 |
+
st.write("- Mouse wheel to zoom")
|
144 |
+
st.write("- Right-click and drag to rotate view")
|
145 |
st.markdown("### 📁 Directory")
|
146 |
directory = st.text_input("Enter path:", ".", key="directory_input")
|
147 |
+
|
148 |
if not os.path.isdir(directory):
|
149 |
st.sidebar.error("Invalid directory path")
|
150 |
return
|
151 |
+
file_types = ['obj', 'glb', 'webp', 'png']
|
152 |
if uploaded_files:
|
153 |
for uploaded_file in uploaded_files:
|
154 |
file_extension = Path(uploaded_file.name).suffix.lower()[1:]
|
|
|
162 |
|
163 |
aframe_scene = f"""
|
164 |
<a-scene embedded style="height: 600px; width: 100%;">
|
165 |
+
{load_aframe_and_extras()}
|
166 |
+
<a-entity id="rig" movement-controls="fly: true; speed: 0.3" position="0 1.6 0">
|
167 |
+
<a-camera id="camera" position="0 1.6 10"></a-camera>
|
168 |
+
</a-entity>
|
169 |
+
<a-entity light="type: ambient; color: #EEE"></a-entity>
|
170 |
+
<a-entity light="type: directional; color: #FFF; intensity: 0.6" position="-0.5 1 1"></a-entity>
|
171 |
+
<a-sky color="#ECF0F1"></a-sky>
|
172 |
+
<a-entity id="tilemap">
|
173 |
+
{''.join(generate_tilemap(files, directory, grid_width, grid_height))}
|
174 |
+
</a-entity>
|
175 |
+
</a-scene>
|
176 |
"""
|
177 |
+
st.components.v1.html(aframe_scene, height=600)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
if __name__ == "__main__":
|
180 |
main()
|