working basic loading glbs demo after lots of fixes

This commit is contained in:
Yeicor
2024-02-17 21:04:37 +01:00
parent c357c88a6f
commit 16b3a8ea64
11 changed files with 569 additions and 73 deletions

View File

@@ -123,7 +123,7 @@ def create_gltf(vertices: np.ndarray, indices: np.ndarray, tex_coord: np.ndarray
byteLength=len(indices_blob) + len(vertices_blob) + len(tex_coord_blob) + len(image_blob),
)
],
samplers=[Sampler(magFilter=NEAREST, minFilter=NEAREST_MIPMAP_NEAREST)] if len(images) > 0 else [],
samplers=[Sampler(magFilter=NEAREST)] if len(images) > 0 else [],
textures=[Texture(source=i, sampler=0) for i, _ in enumerate(images)],
images=images,
)

View File

@@ -8,8 +8,8 @@ from build123d import *
def build_logo() -> TopoDS_Shape:
"""Builds the CAD part of the logo"""
with BuildPart() as logo_obj:
Box(1, 2, 3)
with BuildPart(Plane.XY.offset(30)) as logo_obj:
Box(10, 20, 30)
return logo_obj.part.wrapped
@@ -28,7 +28,7 @@ if __name__ == "__main__":
# 2. Load the GLTF part of the logo
with open(os.path.join(ASSETS_DIR, 'fox.glb'), 'rb') as f:
gltf = f.read()
show_object(gltf, 'fox.glb')
show_object(gltf, 'fox')
# 3. Save the complete logo to a GLBS file
with open(os.path.join(ASSETS_DIR, 'logo.glbs'), 'wb') as f:

View File

@@ -13,6 +13,7 @@ from typing import Optional, Dict, Union, AsyncGenerator, List
import tqdm.asyncio
from OCP.TopoDS import TopoDS_Shape
from aiohttp import web
from build123d import Shape, Axis
from dataclasses_json import dataclass_json, config
from tqdm.contrib.logging import logging_redirect_tqdm
@@ -175,6 +176,7 @@ class Server:
def show_cad(self, obj: Union[TopoDS_Shape, any], name: Optional[str] = None, **kwargs):
"""Publishes a CAD object to the server"""
start = time.time()
# Try to grab a shape if a different type of object was passed
if not isinstance(obj, TopoDS_Shape):
# Build123D
@@ -190,6 +192,9 @@ class Server:
if not isinstance(obj, TopoDS_Shape):
raise ValueError(f'Cannot show object of type {type(obj)} (submit issue?)')
# Convert Z-up (OCC convention) to Y-up (GLTF convention)
obj = Shape(obj).rotate(Axis.X, -90).wrapped
self._show_common(name, _hashcode(obj), start, obj)
async def _api_object(self, request: web.Request) -> web.StreamResponse:

View File

@@ -1,4 +1,5 @@
import concurrent
import copy
import hashlib
import io
import re
@@ -58,25 +59,25 @@ def tessellate(
) -> Generator[TessellationUpdate, None, None]:
"""Tessellate a whole shape into a list of triangle vertices and a list of triangle indices.
NOTE: The logic of the method is weird because multiprocessing was tested but it seems too inefficient
NOTE: The logic of the method is weird because multiprocessing was tested, but it seems too inefficient
with slow native packages.
"""
shape = Shape(ocp_shape)
futures = []
features = []
# Submit tessellation tasks
for face in shape.faces():
futures.append(lambda: _tessellate_element(face.wrapped, tolerance, angular_tolerance))
features.append(_tessellate_element(face.wrapped, tolerance, angular_tolerance))
for edge in shape.edges():
futures.append(lambda: _tessellate_element(edge.wrapped, tolerance, angular_tolerance))
features.append(_tessellate_element(edge.wrapped, tolerance, angular_tolerance))
for vertex in shape.vertices():
futures.append(lambda: _tessellate_element(vertex.wrapped, tolerance, angular_tolerance))
features.append(_tessellate_element(vertex.wrapped, tolerance, angular_tolerance))
# Collect results as they come in
for i, future in enumerate(futures):
sub_shape, gltf = future()
for i, future in enumerate(features):
sub_shape, gltf = future
yield TessellationUpdate(
progress=(i + 1) / len(futures),
progress=(i + 1) / len(features),
shape=sub_shape,
gltf=gltf,
)
@@ -105,6 +106,7 @@ def _tessellate_face(
) -> GLTF2:
"""Tessellate a face into a list of triangle vertices and a list of triangle indices"""
face = Face(ocp_face)
print("Tessellating face", face.center())
tri_mesh = face.tessellate(tolerance, angular_tolerance)
# Get UV of each face from the parameters
@@ -149,7 +151,7 @@ def _tessellate_edge(
tex_coord = np.array([], dtype=np.float32)
mode = LINE_STRIP
material = Material(
pbrMetallicRoughness=PbrMetallicRoughness(baseColorFactor=[1.0, 1.0, 0.5, 1.0]),
pbrMetallicRoughness=PbrMetallicRoughness(baseColorFactor=[0.3, 0.3, 1.0, 1.0]),
alphaCutoff=None)
return create_gltf(np.array(vertices), indices, tex_coord, mode, material)