yt-project / widgyts

Widgets for yt
https://widgyts.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
10 stars 10 forks source link

Add mesh rendering #94

Open matthewturk opened 1 year ago

matthewturk commented 1 year ago

It's very straightforward to render meshes from unstructured meshes, if you are satisfied with the first-order approximation. We should add this to widgyts, to make it easier to visualize the structure.

Here is some sample code:

cam = pythreejs.PerspectiveCamera(
    position=[25, 35, 100], fov=20, children=[pythreejs.AmbientLight()],
)
children = [cam, pythreejs.AmbientLight(color="#dddddd")]
material = pythreejs.MeshBasicMaterial(
    color="#ff0000", vertexColors="VertexColors", side="DoubleSide"
)

def mesh_to_geometry(mesh):
    indices = mt.triangulate_indices(mesh.connectivity_indices - mesh._index_offset)
    # We need to convert these to the triangulated mesh, which is done inside mesh_triangulation.pyx
    attributes = dict(
        position=pythreejs.BufferAttribute(mesh.connectivity_coords, normalized=False),
        index=pythreejs.BufferAttribute(
           indices[:,(0,1,2)].ravel(order="C").astype("u4"), normalized=False
        ),
        color = pythreejs.BufferAttribute(
            (mesh.connectivity_coords * 255).astype('u1')
        )
    )
    geometry = pythreejs.BufferGeometry(attributes=attributes)
    geometry.exec_three_obj_method("computeFaceNormals")
    return geometry

for mesh in ds.index.meshes:
    geometry = mesh_to_geometry(mesh)
    children.append(pythreejs.Mesh(
        geometry=geometry, material=material, position=[0, 0, 0]
    ))

scene = pythreejs.Scene(children=children)

rendererCube = pythreejs.Renderer(
    camera=cam,
    background="white",
    background_opacity=1,
    scene=scene,
    controls=[pythreejs.OrbitControls(controlling=cam)],
    width=800,
    height=800,
)

rendererCube

This is very, very simple, and not at all representative of the wealth of information accessible, but having it display similarly to how the AMR grid structure is displayed would be an enormous improvement.

matthewturk commented 1 year ago

I'm going to put this here so I don't forget it, but it looks like using InstancedMesh may be preferable, since we can potentially color individual elements. I may be totally misunderstanding the situation, however, so I need to test this before investing too much time.