Как я могу обновить средство просмотра Trimesh(Pyglet), чтобы увидеть вращение моей сетки (stl) и прервать эту визуализацию после углового состояния?
После долгих часов поисков решения моего вопроса я здесь, чтобы найти некоторую помощь, чтобы, я надеюсь, кто-то мог помочь мне разморозить мою реальную ситуацию. Так что, если есть какой-нибудь специалист или хороший "Python Guru", у которого есть время, чтобы помочь мне, вот контекст:
Я работаю над сценарием манипулирования сеткой благодаря замечательной библиотеке Trimesh на Python 3.6, и я хотел бы, применяя некоторое преобразование вращения матрицы, обновить визуализацию сетки, чтобы увидеть эволюцию вращения сетки в реальном времени.
Без успеха я попытался выполнить приведенный ниже скрипт, найденный на Trimesh GitHub, но я не могу остановить его, не щелкнув в правом верхнем углу "закрывающий крест". Вот оригинальный код:
"""
view_callback.py
------------------
Show how to pass a callback to the scene viewer for
easy visualizations.
"""
import time
import trimesh
import numpy as np
def sinwave(scene):
"""
A callback passed to a scene viewer which will update
transforms in the viewer periodically.
Parameters
-------------
scene : trimesh.Scene
Scene containing geometry
"""
# create an empty homogenous transformation
matrix = np.eye(4)
# set Y as cos of time
matrix[1][3] = np.cos(time.time()) * 2
# set Z as sin of time
matrix[2][3] = np.sin(time.time()) * 3
# take one of the two spheres arbitrarily
node = s.graph.nodes_geometry[0]
# apply the transform to the node
scene.graph.update(node, matrix=matrix)
if __name__ == '__main__':
# create some spheres
a = trimesh.primitives.Sphere()
b = trimesh.primitives.Sphere()
# set some colors for the balls
a.visual.face_colors = [255, 0, 0, 255]
b.visual.face_colors = [0, 0, 100, 255]
# create a scene with the two balls
s = trimesh.Scene([a, b])
# open the scene viewer and move a ball around
s.show(callback=sinwave)
И вот моя попытка интегрировать преобразование вращения матрицы (чтобы применить вращение к импортированной сетке), чтобы увидеть эволюцию. Но вращение не плавное (анимация свернута), и я не могу остановить его автоматически, скажем, после поворота на 97° по z. (И код основан на времени, в то время как я хотел бы, чтобы он основывался на угловом положении).
from pathlib import Path
import pandas as pd
import time
import xlsxwriter
import numpy as np
import trimesh
from trimesh import transformations as trf
# Actual directory loading and stl adress saving
actual_dir = Path(__file__).resolve().parent
stl = Path(actual_dir/"Belt_Bearing_Gear.stl")
mesh = trimesh.load(f"{stl}")
def R_matrix(scene):
u= 0
o= 0
t= time.time()
time.sleep(0.1)
rotation = (u, o, t)
# Angle conversion from degres to radian
def trig(angle):
r = np.deg2rad(angle)
return r
alpha = trig(rotation[0])
beta = trig(rotation[1])
gamma = trig(rotation[2])
origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
Rx = trf.rotation_matrix(alpha, xaxis)
Ry = trf.rotation_matrix(beta, yaxis)
Rz = trf.rotation_matrix(gamma, zaxis)
R = trf.concatenate_matrices(Rx, Ry, Rz)
R2=R[:3,:3]
# The rotation matrix is applyed to the mesh
mesh.vertices = np.matmul(mesh.vertices,R2)
# apply the transform to the node
s = trimesh.Scene([mesh])
scene.graph.update(s, matrix=R)
if __name__ == '__main__':
# set some colors for the mesh and the bounding box
mesh.visual.face_colors = [102, 255, 255, 255]
# create a scene with the mesh and the bounding box
s = trimesh.Scene([mesh])
liste=list(range(1,10))
# open the scene viewer and move a ball around
s.show(callback=R_matrix)
Все ваши идеи и предложения приветствуются, так как я молодой начинающий Python:) Заранее спасибо за вашу помощь, С уважением,
Р.В.