def execute(self, context):
from .model import SelectModel
from .rigid_bodies import SelectGeometry, AssignGeometry
from .segments import SelectSegment
C = bpy.context
D = bpy.data
model_name = C.active_object.name
segment_names = [i.name for i in C.active_object.data.bones if i.parent]
for segment in segment_names:
SelectModel.run(model_name=model_name)
SelectSegment.run(segment_name=segment)
GenerateMeshFromSegment.run()
return {'FINISHED'}
# operator to select mesh
python类data()的实例源码
def drawCallback(self, context, path):
with cm_draw.bglWrapper:
obj = bpy.data.objects[path.objectName]
M = obj.matrix_world
up = Vector((0.0, 0.0, 1.0))
for edge in obj.data.edges:
a = M * obj.data.vertices[edge.vertices[0]].co
b = M * obj.data.vertices[edge.vertices[1]].co
if str(edge.index) in path.revDirec:
a, b = b, a
close = (2 * a + b) / 3
far = (a + 2 * b) / 3
mid = (a + b) / 2
edgeVec = a - b
perp = edgeVec.cross(up).normalized() * (edgeVec.length / 12)
cm_draw.drawLine3D((0, 1, 0, 0.7), close + perp, far)
cm_draw.drawLine3D((0, 1, 0, 0.7), close - perp, far)
def format_text(self):
global TW
out = []
if self.text:
lines = self.text.splitlines()
elif self.text_file:
text_file = bpy.data.texts.get(self.text_file)
if text_file:
lines = get_lines(text_file)
else:
return []
else:
return []
width = self.width
TW.width = int(width) // TEXT_WIDTH
for t in lines:
out.extend(TW.wrap(t))
out.append("")
return out
def build(self, buildRequest):
t = time.time()
obj = bpy.context.scene.objects[self.settings["inputObject"]]
if buildRequest.deferGeo:
cp = bpy.data.objects.new("Empty", None)
cp.matrix_world = obj.matrix_world
cp["cm_deferObj"] = obj.name
cp["cm_materials"] = buildRequest.materials
else:
cp = obj.copy()
for m in cp.material_slots:
if m.name in buildRequest.materials:
replacement = buildRequest.materials[m.name]
m.material = bpy.data.materials[replacement]
buildRequest.group.objects.link(cp)
bpy.context.scene.objects.link(cp)
cm_timings.placement["GeoTemplateOBJECT"] += time.time() - t
cm_timings.placementNum["GeoTemplateOBJECT"] += 1
return GeoReturn(cp)
def build(self, buildRequest):
t = time.time()
ob = bpy.context.scene.objects[self.settings["PointObject"]]
pos = buildRequest.pos
if self.settings["PointType"] == "OBJECT":
point = ob.location
else: # self.settings["PointObject"] == "MESH":
if self.kdtree is None:
mesh = ob.data
self.kdtree = KDTree(len(mesh.vertices))
for i, v in enumerate(mesh.vertices):
self.kdtree.insert(v.co, i)
self.kdtree.balance()
co, ind, dist = self.kdtree.find(ob.matrix_world.inverted() * pos)
point = ob.matrix_world * co
direc = point - pos
rotQuat = direc.to_track_quat('Y', 'Z')
buildRequest.rot = rotQuat.to_euler()
cm_timings.placement["TemplatePOINTTOWARDS"] += time.time() - t
cm_timings.placementNum["TemplatePOINTTOWARDS"] += 1
self.inputs["Template"].build(buildRequest)
def check(self):
if "Template" not in self.inputs:
return False
if not isinstance(self.inputs["Template"], Template):
return False
if isinstance(self.inputs["Template"], GeoTemplate):
return False
if self.settings["targetType"] == "object":
if self.settings["targetGroups"] not in bpy.data.groups:
return False
elif self.settings["targetType"] == "vertex":
if self.settings["targetObject"] not in bpy.context.scene.objects:
return False
if bpy.context.scene.objects[self.settings["targetObject"]].type != 'MESH':
return False
return True
def build(self, buildRequest):
t = time.time()
if self.octree is None:
objs = bpy.data.groups[self.settings["obstacleGroup"]].objects
margin = self.settings["margin"]
mVec = Vector((margin, margin, margin))
radii = [(o.dimensions / 2) + mVec for o in objs]
self.octree = createOctreeFromBPYObjs(objs, allSpheres=False,
radii=radii)
intersections = self.octree.checkPoint(buildRequest.pos)
cm_timings.placement["TemplateOBSTACLE"] += time.time() - t
cm_timings.placementNum["TemplateOBSTACLE"] += 1
if len(intersections) == 0:
self.inputs["Template"].build(buildRequest)
def format_text(self):
global TW
out = []
if self.text:
lines = self.text.splitlines()
elif self.text_file:
text_file = bpy.data.texts.get(self.text_file)
if text_file:
lines = get_lines(text_file)
else:
return []
else:
return []
width = self.width
TW.width = int(width) // TEXT_WIDTH
for t in lines:
out.extend(TW.wrap(t))
out.append("")
return out
def _get_namelist_items(self, context, nl): # FIXME move from here
"""Get namelist IDs available in Free Text File"""
# Get Free Text File
value = str()
sc = context.scene
if sc.bf_head_free_text:
value = bpy.data.texts[sc.bf_head_free_text].as_string()
# Tokenize value and manage exception
try: tokens = fds.to_py.tokenize(value)
except Exception as err: pass # FIXME not good
# Select MATL tokens, get IDs, return
ids = list()
for token in tokens:
if token[1] != nl: continue
for param in token[2]:
if param[1] == "ID":
# Built like this: (("Steel", "Steel", "",) ...)
ids.append((param[2],param[2],"",))
ids.sort(key=lambda k:k[1])
return ids
def layout_id_prop(layout, data, prop):
prop_obj = data.bl_rna.properties[prop]
prop_name = prop_obj.name
value_key = _create_value_key(prop_name)
ref_id = data.get(value_key, None)
field_name = json.loads(prop_obj.description)["field_name"]
row = layout.row(align=True)
row.prop_search(data, prop, bpy.data, field_name)
if field_name == "objects":
op_props = row.operator(SelectedToIdProperty.bl_idname, emboss=True, icon="EYEDROPPER")
op_props.to_populate_data = repr(data)
op_props.to_populate_field = prop
op_props = row.operator(FindSelected.bl_idname, emboss=True, icon="VIEWZOOM")
op_props.to_populate_data = repr(data)
op_props.to_populate_field = prop
def create_getter(data_field, value_key):
def fn(self):
data = getattr(bpy.data, data_field)
ob_id = self.get(value_key, None)
id_to_hash = ID_TO_HASH[data_field]
hash_to_name = HASH_TO_NAME[data_field]
ob_hash = id_to_hash.get(ob_id, None)
ob_name = hash_to_name.get(ob_hash, None)
exists = ob_name is not None and ob_name in data
if not exists:
for name, ob in data.items():
if ob_hash == hash(ob):
hash_to_name[ob_hash] = name
ob_name = name
break
if ob_name is None:
ob_name = ""
return ob_name
return fn
def load_file(_=None):
for col_name, _ in SUPPORTED_COLLECTIONS:
id_to_hash = {}
hash_to_name = {}
ID_TO_HASH[col_name] = id_to_hash
HASH_TO_NAME[col_name] = hash_to_name
col = getattr(bpy.data, col_name)
all_obs = sorted(list(col), key=lambda ob: ob.name, reverse=True)
for ob in all_obs:
# on load, if we encounter an object with a dup id. unset it and let it
# regenerate as a unique id
if ob.id in id_to_hash:
ob["id"] = 0
id_to_hash[ob.id] = hash(ob)
hash_to_name[hash(ob)] = ob.name
def create_mesh(self,context,name="Sprite",width=100,height=100,pos=Vector((0,0,0))):
me = bpy.data.meshes.new(name)
me.show_double_sided = True
obj = bpy.data.objects.new(name,me)
context.scene.objects.link(obj)
context.scene.objects.active = obj
obj.select = True
self.create_verts(width,height,pos,me,tag_hide=False)
v_group = obj.vertex_groups.new("coa_base_sprite")
v_group.add([0,1,2,3],1.0,"REPLACE")
v_group.lock_weight = True
mod = obj.modifiers.new("coa_base_sprite","MASK")
mod.vertex_group = "coa_base_sprite"
mod.invert_vertex_group = True
mod.show_in_editmode = True
mod.show_render = False
mod.show_viewport = False
mod.show_on_cage = True
obj.data.coa_hide_base_sprite = False
obj.data.uv_textures.new("UVMap")
set_uv_default_coords(context,obj)
obj.location = Vector((pos[0],pos[1],-pos[2]))*self.scale + Vector((self.offset[0],self.offset[1],self.offset[2]))*self.scale
obj["coa_sprite"] = True
if self.parent != "None":
obj.parent = bpy.data.objects[self.parent]
return obj
def create_material(self,context,obj,name="Sprite"):
mat = bpy.data.materials.new(name)
#mat.use_shadeless = True
mat.use_transparency = True
mat.alpha = 0.0
mat.specular_intensity = 0.0
mat.diffuse_intensity = 1.0
mat.emit = 1.0
mat.use_object_color = True
mat.diffuse_color = (1.0,1.0,1.0)
obj.data.materials.append(mat)
return mat
def create_texture(self,context,mat,img,name="Sprite"):
tex = bpy.data.textures.new(name,"IMAGE")
tex.extension = "CLIP"
tex.filter_type = "BOX"
tex.image = img
tex_slot = mat.texture_slots.add()
tex_slot.texture = tex
tex_slot.use_map_alpha = True
if img.source == "MOVIE":
tex.image_user.frame_duration = img.frame_duration
tex.image_user.frame_start = 0
tex.image_user.use_auto_refresh = True
def execute(self,context):
if os.path.exists(self.path):
data = bpy.data
sprite_name = os.path.basename(self.path)
sprite_found = False
for image in bpy.data.images:
if os.path.exists(bpy.path.abspath(image.filepath)) and os.path.exists(self.path):
if os.path.samefile(bpy.path.abspath(image.filepath),self.path):
sprite_found = True
img = image
img.reload()
break
if not sprite_found:
img = data.images.load(self.path)
obj = self.create_mesh(context,name=img.name,width=img.size[0],height=img.size[1],pos=self.pos)
mat = self.create_material(context,obj,name=img.name)
tex = self.create_texture(context,mat,img,name=img.name)
msg = sprite_name + " Sprite created."
assign_tex_to_uv(img,obj.data.uv_textures.active)
obj.coa_sprite_dimension = Vector((get_local_dimension(obj)[0],0,get_local_dimension(obj)[1]))
obj.coa_tiles_x = self.tilesize[0]
obj.coa_tiles_y = self.tilesize[1]
selected_objects = []
for obj2 in context.selected_objects:
selected_objects.append(obj2)
if obj2 != context.active_object:
obj2.select = False
obj.coa_z_value = -self.pos[1]
for obj2 in selected_objects:
obj2.select = True
self.report({'INFO'},msg)
return{'FINISHED'}
else:
self.report({'WARNING'},'File does not exist.')
return{'CANCELLED'}
def execute(self, context):
sprite_found = False
for image in bpy.data.images:
if os.path.exists(bpy.path.abspath(image.filepath)) and os.path.exists(self.filepath):
if os.path.samefile(bpy.path.abspath(image.filepath),self.filepath):
sprite_found = True
img = image
img.reload()
break
if not sprite_found:
img = bpy.data.images.load(self.filepath)
scale = get_addon_prefs(context).sprite_import_export_scale
active_obj = bpy.data.objects[context.active_object.name]
obj = context.active_object
if self.name != "" and self.name in bpy.data.objects:
obj = bpy.data.objects[self.name]
bpy.context.scene.objects.active = obj
mat = obj.active_material
tex = mat.texture_slots[0].texture
tex.image = img
tiles_x = int(obj.coa_tiles_x)
tiles_y = int(obj.coa_tiles_y)
obj.coa_tiles_x = 1
obj.coa_tiles_y = 1
img_dimension = img.size
sprite_dimension = Vector(obj.coa_sprite_dimension) * (1/scale)
ratio_x = img_dimension[0] / sprite_dimension[0]
ratio_y = img_dimension[1] / sprite_dimension[2]
self.move_verts(obj,ratio_x,ratio_y)
bpy.context.scene.objects.active = active_obj
return {'FINISHED'}
def adjust_selected_image(self, context):
scene = context.scene
try:
image = bpy.data.images.load(scene.cubester_load_image)
scene.cubester_image = image.name
except RuntimeError:
self.report({"ERROR"}, "CubeSter: '{}' could not be loaded".format(scene.cubester_load_image))
# load color image if possible
def adjust_selected_color_image(self, context):
scene = context.scene
try:
image = bpy.data.images.load(scene.cubester_load_color_image)
scene.cubester_color_image = image.name
except RuntimeError:
self.report({"ERROR"}, "CubeSter: '{}' could not be loaded".format(scene.cubester_load_color_image))
# crate block at center position x, y with block width 2*hx and 2*hy and height of h
def create_f_curves(mesh, frames, frame_step_size, style):
# use data to animate mesh
action = bpy.data.actions.new("CubeSterAnimation")
mesh.animation_data_create()
mesh.animation_data.action = action
data_path = "vertices[%d].co"
vert_index = 4 if style == "blocks" else 0 # index of first vertex
# loop for every face height value
for frame_start_vert in range(len(frames[0])):
# only go once if plane, otherwise do all four vertices that are in top plane if blocks
end_point = frame_start_vert + 4 if style == "blocks" else frame_start_vert + 1
# loop through to get the four vertices that compose the face
for frame_vert in range(frame_start_vert, end_point):
fcurves = [action.fcurves.new(data_path % vert_index, i) for i in range(3)] # fcurves for x, y, z
frame_counter = 0 # go through each frame and add position
temp_v = mesh.vertices[vert_index].co
# loop through frames
for frame in frames:
vals = [temp_v[0], temp_v[1], frame[frame_start_vert]] # new x, y, z positions
for i in range(3): # for each x, y, z set each corresponding fcurve
fcurves[i].keyframe_points.insert(frame_counter, vals[i], {'FAST'})
frame_counter += frame_step_size # skip frames for smoother animation
vert_index += 1
# only skip vertices if made of blocks
if style == "blocks":
vert_index += 4
# create material with given name, apply to object