Advertisement
DIRK-VANTAS

Untitled

Oct 30th, 2024 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. def get_frame_exploded_mesh(obj, frame):
  2.     # Set Blender to the specific frame
  3.     bpy.context.scene.frame_set(frame)
  4.  
  5.     # Duplicate the object for this frame
  6.     obj_copy = obj.copy()
  7.     obj_copy.data = obj.data.copy()  
  8.    
  9.     # link is needed for modifier operations
  10.     bpy.context.collection.objects.link(obj_copy)
  11.  
  12.     #DECIMATE----------------------------------------------
  13.     decimate_mod = obj_copy.modifiers.new(name="Decimate", type='DECIMATE')
  14.     bpy.context.view_layer.objects.active = obj_copy
  15.    
  16.     #apply both modifiers to get mesh and decimate it
  17.     bpy.ops.object.modifier_apply(modifier="MeshSequenceCache")
  18.    
  19.     print("pre decimation : ", len(obj_copy.data.polygons))
  20.     max_faces = 8000
  21.     original_faces = len(obj_copy.data.polygons)
  22.     decimate_mod.ratio = (max_faces / original_faces) * 0.96
  23.    
  24.     bpy.ops.object.modifier_apply(modifier=decimate_mod.name)
  25.    
  26.     print("post decimation : ", len(obj_copy.data.polygons))
  27.    
  28.     mesh_eval = bpy.data.meshes.new_from_object(obj_copy)
  29.  
  30.     # create new mesh instance from that and explode it and record vertex data
  31.     bm = bmesh.new()
  32.     bm.from_mesh(mesh_eval)
  33.    
  34.     # Triangulate all faces
  35.     bmesh.ops.triangulate(bm, faces=bm.faces)
  36.    
  37.     # Split all the edges so no two faces share vertices
  38.     bmesh.ops.split_edges(bm, edges=bm.edges[:])
  39.    
  40.     # Update the mesh with the exploded geometry
  41.     bm.to_mesh(mesh_eval)
  42.    
  43.     # Collect triangle data from that frame
  44.     faces = {}
  45.     for face_index, face in enumerate(bm.faces):
  46.        
  47.         triangle = {}
  48.         for vert_index,vert in enumerate(face.verts):
  49.             co = vert.co.copy()
  50.             normal = vert.normal.copy()  # Get normal of the vertex
  51.            
  52.             # Store vertex coordinates and normal
  53.             triangle[f'vertex_{vert_index}'] = {
  54.                 'position': [co.x, co.y, co.z],
  55.                 'normal': [normal.x, normal.y, normal.z]
  56.             }
  57.         faces[f'face_{face_index}'] = triangle
  58.    
  59.     # Clean up
  60.     bm.free()
  61.     bpy.data.meshes.remove(mesh_eval)
  62.     bpy.context.collection.objects.unlink(obj_copy)
  63.    
  64.     #revert back to original object reference
  65.     bpy.context.view_layer.objects.active = active_obj
  66.    
  67.     #print("processed frame: ", frame, "with ", len(faces), "faces")
  68.     return faces    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement