Skip to content

Instantly share code, notes, and snippets.

@nezix
Created May 31, 2023 10:56
Show Gist options
  • Save nezix/d48294c83d4d05dbe872c7286797fb39 to your computer and use it in GitHub Desktop.
Save nezix/d48294c83d4d05dbe872c7286797fb39 to your computer and use it in GitHub Desktop.
Nanome plugin code to load a 3D mesh
import nanome
from nanome.util import Color, Logs, Vector3
from nanome.api import shapes
import numpy as np
import open3d as o3d
class OBJLoader(nanome.PluginInstance):
def start(self):
path = "mypath.obj"
#Nanome plugin mesh
mesh = shapes.Mesh()
mesh.uv = []
mesh.colors = []
#Load a mesh
o3dmesh = o3d.io.read_triangle_mesh(path)
#Center the mesh
o3dmesh.translate(-o3dmesh.get_center())
#Compute normals if needed
if not o3dmesh.has_vertex_normals():
o3dmesh.compute_vertex_normals()
if o3dmesh.has_vertex_colors():
for c in o3dmesh.vertex_colors:
mesh.colors += [c[0], c[1], c[2], 1.0]
if o3dmesh.has_triangle_uvs():
mesh.uv = np.asarray(o3dmesh.triangle_uvs).flatten()
mesh.vertices = np.asarray(o3dmesh.vertices).flatten()
#mesh normals can be recomputed by Nanome if the array is empty
mesh.normals = np.asarray(o3dmesh.vertex_normals).flatten()
mesh.triangles = np.asarray(o3dmesh.triangles).flatten()
#Attach the mesh to the workspace, it could also be attached to an atom
mesh.anchors[0].anchor_type = nanome.util.enums.ShapeAnchorType.Workspace
mesh.anchors[0].position = nanome.util.Vector3(0, 0, 0)
mesh.color = nanome.util.Color(255, 255, 255, 255)
if len(mesh.uv)/2 < len(mesh.vertices) / 3:
mesh.uv = np.repeat([0.0, 0.0], len(mesh.vertices) / 3)
if len(mesh.colors)/4 < len(mesh.vertices) / 3:
mesh.colors = np.repeat([1.0, 1.0, 1.0, 1.0], len(mesh.vertices) / 3)
#Send mesh to Nanome
mesh.upload()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment