[Python] Rotating Cylinder Mesh with python

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create cylinders with python and saving them in an object file. The cylinder mesh generation is working fine and placing the cylinder at a specific x, y, z coordinate is also working fine, but when trying to rotate the cylinder to the start and end coordinates it doesn't rotate right.

    My code:

    import trimesh
    import numpy as np
    from scipy.spatial.transform import Rotation as R

    def generate_cylinders_mesh(strat_points, end_points, radii, filename):

    cylinders = []

    for start_point, end_point, radius in zip(strat_points, end_points, radii):

    start_x, start_y, start_z = start_point
    end_x, end_y, end_z = end_point

    delta_x = end_x - start_x
    delta_y = end_y - start_y
    delta_z = end_z - start_z

    height = np.sqrt((delta_x)**2 + (delta_y)**2 + (delta_z)**2)

    centre_x = (start_x + end_x) / 2
    centre_y = (start_y + end_y) / 2
    centre_z = (start_z + end_z) / 2

    centre = (centre_x, centre_y, centre_z)

    cylinder = trimesh.creation.cylinder(subdivisions=3, radius=radius, height=height)
    cylinder.apply_translation(centre)

    rot_x = np.degrees(np.atan2(delta_y, delta_z))
    rot_y = np.degrees(np.atan2(delta_x, delta_z))
    rot_z = np.degrees(np.atan2(delta_y, delta_x))
    directions = (rot_x, rot_y, rot_z)

    # Convert to Rotation Matrix
    r = R.from_euler('xyz', directions, degrees=True)
    rotation_matrix = np.eye(4) # Identity matrix (4x4) for homogeneous transformation
    rotation_matrix[:3, :3] = r.as_matrix() # Assign 3x3 rotation

    # Apply transformation
    cylinder.apply_transform(rotation_matrix)


    cylinders.append(cylinder)


    # Combine all spheres into a single mesh
    combined_mesh_cylinders = trimesh.util.concatenate(cylinders)

    # Save the mesh to an .obj file
    combined_mesh_cylinders.export(filename)

    Continue reading...

Compartilhe esta Página