The camera distance is set to 10 to improve the 3D visualization of the object. This change is purely cosmetic and does not affect the functionality of the code.
55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
"""
|
|
Created on Fri Apr 21 2023
|
|
@name: visplot_render.py
|
|
@desc: A module to render a 3D data using vispy
|
|
@auth: Djalim Simaila
|
|
@e-mail: djalim.simaila@inrae.fr
|
|
"""
|
|
import numpy as np
|
|
from vispy import app, scene
|
|
from vispy.scene.visuals import Mesh
|
|
from vispy.visuals.filters import ShadingFilter, WireframeFilter
|
|
from utils.files.input import ScannedObject
|
|
|
|
|
|
def render3D(obj:ScannedObject,show:bool=True)->scene.SceneCanvas|None:
|
|
"""
|
|
Render a 3D model mesh using vispy
|
|
|
|
:param obj: A ScannedObject to be rendered
|
|
:param show: If True, show the plot, else return the canvas
|
|
:return: A canvas with the rendered object
|
|
"""
|
|
# Extract the vertices and faces from the object
|
|
vertices = np.asarray(obj.get_vertices())
|
|
faces = np.asarray(obj.get_faces())
|
|
# Create the canvas
|
|
canvas = scene.SceneCanvas(keys='interactive', bgcolor='white')
|
|
# Create a viewbox to display the mesh in
|
|
view = canvas.central_widget.add_view()
|
|
view.camera = 'arcball'
|
|
view.camera.depth_value = 1e3
|
|
view.camera.distance = 10
|
|
color = (0.3, 0.5, 0.8)
|
|
mesh = Mesh(vertices, faces, color=color)
|
|
view.add(mesh)
|
|
# Add filters to the mesh
|
|
wireframe_filter = WireframeFilter(width=0)
|
|
shading_filter = ShadingFilter(shininess=0)
|
|
mesh.attach(wireframe_filter)
|
|
mesh.attach(shading_filter)
|
|
|
|
def attach_headlight(view):
|
|
light_dir = (0, 1, 0, 0)
|
|
shading_filter.light_dir = light_dir[:3]
|
|
initial_light_dir = view.camera.transform.imap(light_dir)
|
|
@view.scene.transform.changed.connect
|
|
def on_transform_change(event):
|
|
transform = view.camera.transform
|
|
shading_filter.light_dir = transform.map(initial_light_dir)[:3]
|
|
attach_headlight(view)
|
|
if show:
|
|
canvas.show()
|
|
app.run()
|
|
else:
|
|
return canvas |