Screencast Keys Addon: Improved mouse silhouette, fixed box width to fit to text...
[blender-addons.git] / object_fracture_cell / fracture_cell_setup.py
blob93ac1b9a64b556d332758d633524bc4e87ac46cb
1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
19 # <pep8 compliant>
21 # Script copyright (C) Blender Foundation 2012
23 import bpy
24 import bmesh
27 def _redraw_yasiamevil():
28 _redraw_yasiamevil.opr(**_redraw_yasiamevil.arg)
29 _redraw_yasiamevil.opr = bpy.ops.wm.redraw_timer
30 _redraw_yasiamevil.arg = dict(type='DRAW_WIN_SWAP', iterations=1)
33 def _points_from_object(obj, source):
35 _source_all = {
36 'PARTICLE_OWN', 'PARTICLE_CHILD',
37 'PENCIL',
38 'VERT_OWN', 'VERT_CHILD',
41 print(source - _source_all)
42 print(source)
43 assert(len(source | _source_all) == len(_source_all))
44 assert(len(source))
46 points = []
48 def edge_center(mesh, edge):
49 v1, v2 = edge.vertices
50 return (mesh.vertices[v1].co + mesh.vertices[v2].co) / 2.0
52 def poly_center(mesh, poly):
53 from mathutils import Vector
54 co = Vector()
55 tot = 0
56 for i in poly.loop_indices:
57 co += mesh.vertices[mesh.loops[i].vertex_index].co
58 tot += 1
59 return co / tot
61 def points_from_verts(obj):
62 """Takes points from _any_ object with geometry"""
63 if obj.type == 'MESH':
64 mesh = obj.data
65 matrix = obj.matrix_world.copy()
66 points.extend([matrix * v.co for v in mesh.vertices])
67 else:
68 try:
69 mesh = ob.to_mesh(scene=bpy.context.scene,
70 apply_modifiers=True,
71 settings='PREVIEW')
72 except:
73 mesh = None
75 if mesh is not None:
76 matrix = obj.matrix_world.copy()
77 points.extend([matrix * v.co for v in mesh.vertices])
78 bpy.data.meshes.remove(mesh)
80 def points_from_particles(obj):
81 points.extend([p.location.copy()
82 for psys in obj.particle_systems
83 for p in psys.particles])
85 # geom own
86 if 'VERT_OWN' in source:
87 points_from_verts(obj)
89 # geom children
90 if 'VERT_CHILD' in source:
91 for obj_child in obj.children:
92 points_from_verts(obj_child)
94 # geom particles
95 if 'PARTICLE_OWN' in source:
96 points_from_particles(obj)
98 if 'PARTICLE_CHILD' in source:
99 for obj_child in obj.children:
100 points_from_particles(obj_child)
102 # grease pencil
103 def get_points(stroke):
104 return [point.co.copy() for point in stroke.points]
106 def get_splines(gp):
107 if gp.layers.active:
108 frame = gp.layers.active.active_frame
109 return [get_points(stroke) for stroke in frame.strokes]
110 else:
111 return []
113 if 'PENCIL' in source:
114 gp = obj.grease_pencil
115 if gp:
116 points.extend([p for spline in get_splines(gp)
117 for p in spline])
119 print("Found %d points" % len(points))
121 return points
124 def cell_fracture_objects(scene, obj,
125 source={'PARTICLE_OWN'},
126 source_limit=0,
127 source_noise=0.0,
128 clean=True,
129 # operator options
130 use_smooth_faces=False,
131 use_data_match=False,
132 use_debug_points=False,
133 margin=0.0,
134 material_index=0,
135 use_debug_redraw=False,
136 cell_scale=(1.0, 1.0, 1.0),
139 from . import fracture_cell_calc
141 # -------------------------------------------------------------------------
142 # GET POINTS
144 points = _points_from_object(obj, source)
146 if not points:
147 # print using fallback
148 points = _points_from_object(obj, {'VERT_OWN'})
150 if not points:
151 print("no points found")
152 return []
154 # apply optional clamp
155 if source_limit != 0 and source_limit < len(points):
156 import random
157 random.shuffle(points)
158 points[source_limit:] = []
160 # saddly we cant be sure there are no doubles
161 from mathutils import Vector
162 to_tuple = Vector.to_tuple
163 points = list({to_tuple(p, 4): p for p in points}.values())
164 del to_tuple
165 del Vector
167 # end remove doubles
168 # ------------------
170 if source_noise > 0.0:
171 from random import random
172 # boundbox approx of overall scale
173 from mathutils import Vector
174 matrix = obj.matrix_world.copy()
175 bb_world = [matrix * Vector(v) for v in obj.bound_box]
176 scalar = source_noise * ((bb_world[0] - bb_world[6]).length / 2.0)
178 from mathutils.noise import random_unit_vector
180 points[:] = [p + (random_unit_vector() * (scalar * random())) for p in points]
182 if use_debug_points:
183 bm = bmesh.new()
184 for p in points:
185 bm.verts.new(p)
186 mesh_tmp = bpy.data.meshes.new(name="DebugPoints")
187 bm.to_mesh(mesh_tmp)
188 bm.free()
189 obj_tmp = bpy.data.objects.new(name=mesh_tmp.name, object_data=mesh_tmp)
190 scene.objects.link(obj_tmp)
191 del obj_tmp, mesh_tmp
193 mesh = obj.data
194 matrix = obj.matrix_world.copy()
195 verts = [matrix * v.co for v in mesh.vertices]
197 cells = fracture_cell_calc.points_as_bmesh_cells(verts,
198 points,
199 cell_scale,
200 margin_cell=margin)
202 # some hacks here :S
203 cell_name = obj.name + "_cell"
205 objects = []
207 for center_point, cell_points in cells:
209 # ---------------------------------------------------------------------
210 # BMESH
212 # create the convex hulls
213 bm = bmesh.new()
215 # WORKAROUND FOR CONVEX HULL BUG/LIMIT
216 # XXX small noise
217 import random
218 def R():
219 return (random.random() - 0.5) * 0.001
220 # XXX small noise
222 for i, co in enumerate(cell_points):
224 # XXX small noise
225 co.x += R()
226 co.y += R()
227 co.z += R()
228 # XXX small noise
230 bm_vert = bm.verts.new(co)
232 import mathutils
233 bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.005)
234 try:
235 bmesh.ops.convex_hull(bm, input=bm.verts)
236 except RuntimeError:
237 import traceback
238 traceback.print_exc()
240 if clean:
241 bm.normal_update()
242 try:
243 bmesh.ops.dissolve_limit(bm, verts=bm.verts, angle_limit=0.001)
244 except RuntimeError:
245 import traceback
246 traceback.print_exc()
248 if use_smooth_faces:
249 for bm_face in bm.faces:
250 bm_face.smooth = True
252 if material_index != 0:
253 for bm_face in bm.faces:
254 bm_face.material_index = material_index
257 # ---------------------------------------------------------------------
258 # MESH
259 mesh_dst = bpy.data.meshes.new(name=cell_name)
261 bm.to_mesh(mesh_dst)
262 bm.free()
263 del bm
265 if use_data_match:
266 # match materials and data layers so boolean displays them
267 # currently only materials + data layers, could do others...
268 mesh_src = obj.data
269 for mat in mesh_src.materials:
270 mesh_dst.materials.append(mat)
271 for lay_attr in ("vertex_colors", "uv_textures"):
272 lay_src = getattr(mesh_src, lay_attr)
273 lay_dst = getattr(mesh_dst, lay_attr)
274 for key in lay_src.keys():
275 lay_dst.new(name=key)
277 # ---------------------------------------------------------------------
278 # OBJECT
280 obj_cell = bpy.data.objects.new(name=cell_name, object_data=mesh_dst)
281 scene.objects.link(obj_cell)
282 # scene.objects.active = obj_cell
283 obj_cell.location = center_point
285 objects.append(obj_cell)
287 # support for object materials
288 if use_data_match:
289 for i in range(len(mesh_dst.materials)):
290 slot_src = obj.material_slots[i]
291 slot_dst = obj_cell.material_slots[i]
293 slot_dst.link = slot_src.link
294 slot_dst.material = slot_src.material
296 if use_debug_redraw:
297 scene.update()
298 _redraw_yasiamevil()
300 scene.update()
302 # move this elsewhere...
303 for obj_cell in objects:
304 game = obj_cell.game
305 game.physics_type = 'RIGID_BODY'
306 game.use_collision_bounds = True
307 game.collision_bounds_type = 'CONVEX_HULL'
309 return objects
312 def cell_fracture_boolean(scene, obj, objects,
313 use_debug_bool=False,
314 clean=True,
315 use_island_split=False,
316 use_interior_hide=False,
317 use_debug_redraw=False,
318 level=0,
319 remove_doubles=True
322 objects_boolean = []
324 if use_interior_hide and level == 0:
325 # only set for level 0
326 obj.data.polygons.foreach_set("hide", [False] * len(obj.data.polygons))
328 for obj_cell in objects:
329 mod = obj_cell.modifiers.new(name="Boolean", type='BOOLEAN')
330 mod.object = obj
331 mod.operation = 'INTERSECT'
333 if not use_debug_bool:
335 if use_interior_hide:
336 obj_cell.data.polygons.foreach_set("hide", [True] * len(obj_cell.data.polygons))
338 mesh_new = obj_cell.to_mesh(scene,
339 apply_modifiers=True,
340 settings='PREVIEW')
341 mesh_old = obj_cell.data
342 obj_cell.data = mesh_new
343 obj_cell.modifiers.remove(mod)
345 # remove if not valid
346 if not mesh_old.users:
347 bpy.data.meshes.remove(mesh_old)
348 if not mesh_new.vertices:
349 scene.objects.unlink(obj_cell)
350 if not obj_cell.users:
351 bpy.data.objects.remove(obj_cell)
352 obj_cell = None
353 if not mesh_new.users:
354 bpy.data.meshes.remove(mesh_new)
355 mesh_new = None
357 # avoid unneeded bmesh re-conversion
358 if mesh_new is not None:
359 bm = None
361 if clean:
362 if bm is None: # ok this will always be true for now...
363 bm = bmesh.new()
364 bm.from_mesh(mesh_new)
365 bm.normal_update()
366 try:
367 bmesh.ops.dissolve_limit(bm, verts=bm.verts, edges=bm.edges, angle_limit=0.001)
368 except RuntimeError:
369 import traceback
370 traceback.print_exc()
372 if remove_doubles:
373 if bm is None:
374 bm = bmesh.new()
375 bm.from_mesh(mesh_new)
376 bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.005)
378 if bm is not None:
379 bm.to_mesh(mesh_new)
380 bm.free()
382 del mesh_new
383 del mesh_old
385 if obj_cell is not None:
386 objects_boolean.append(obj_cell)
388 if use_debug_redraw:
389 _redraw_yasiamevil()
391 if (not use_debug_bool) and use_island_split:
392 # this is ugly and Im not proud of this - campbell
393 base = None
394 for base in scene.object_bases:
395 base.select = False
396 for obj_cell in objects_boolean:
397 obj_cell.select = True
399 bpy.ops.mesh.separate(type='LOOSE')
401 objects_boolean[:] = [obj_cell for obj_cell in scene.objects if obj_cell.select]
403 scene.update()
405 return objects_boolean
408 def cell_fracture_interior_handle(objects,
409 use_interior_vgroup=False,
410 use_sharp_edges=False,
411 use_sharp_edges_apply=False,
413 """Run after doing _all_ booleans"""
415 assert(use_interior_vgroup or use_sharp_edges or use_sharp_edges_apply)
417 for obj_cell in objects:
418 mesh = obj_cell.data
419 bm = bmesh.new()
420 bm.from_mesh(mesh)
422 if use_interior_vgroup:
423 for bm_vert in bm.verts:
424 bm_vert.tag = True
425 for bm_face in bm.faces:
426 if not bm_face.hide:
427 for bm_vert in bm_face.verts:
428 bm_vert.tag = False
430 # now add all vgroups
431 defvert_lay = bm.verts.layers.deform.verify()
432 for bm_vert in bm.verts:
433 if bm_vert.tag:
434 bm_vert[defvert_lay][0] = 1.0
436 # add a vgroup
437 obj_cell.vertex_groups.new(name="Interior")
439 if use_sharp_edges:
440 mesh.show_edge_sharp = True
441 for bm_edge in bm.edges:
442 if len({bm_face.hide for bm_face in bm_edge.link_faces}) == 2:
443 bm_edge.smooth = False
445 if use_sharp_edges_apply:
446 edges = [edge for edge in bm.edges if edge.smooth is False]
447 if edges:
448 bm.normal_update()
449 bmesh.ops.split_edges(bm, edges=edges)
451 for bm_face in bm.faces:
452 bm_face.hide = False
454 bm.to_mesh(mesh)
455 bm.free()