def polymesh(self, en, bm):
"""
en: POLYMESH entitiy
bm: Blender bmesh instance
"""
mc = en.mcount if not en.is_mclosed else en.mcount + 1
nc = en.ncount if not en.is_nclosed else en.ncount + 1
for i in range(1, mc):
i = i % en.mcount
i_ = (i - 1) % en.mcount
for j in range(1, nc):
j = j % en.ncount
j_ = (j - 1) % en.ncount
face = []
face.append(bm.verts.new(en.get_location((i_, j_))))
face.append(bm.verts.new(en.get_location((i, j_))))
face.append(bm.verts.new(en.get_location((i, j))))
face.append(bm.verts.new(en.get_location((i_, j))))
bm.faces.new(face)
python类new()的实例源码
def mesh(self, en, bm):
"""
mesh: dxf entity
m: Blender MESH data (object.data) to which the dxf-mesh should be added
"""
# verts:
for v in en.vertices:
bm.verts.new(v)
# edges:
bm.verts.ensure_lookup_table()
if any((c < 0 for c in en.edge_crease_list)):
layerkey = bm.edges.layers.crease.new("SubsurfCrease")
for i, edge in enumerate(en.edges):
bme = bm.edges.new([bm.verts[edge[0]], bm.verts[edge[1]]])
bme[layerkey] = -en.edge_crease_list[i]
else:
for i, edge in enumerate(en.edges):
bm.edges.new([bm.verts[edge[0]], bm.verts[edge[1]]])
# faces:
for face in en.faces:
bm.faces.new([bm.verts[i] for i in face])
def light(self, en, scene, name):
"""
en: dxf entity
name: ignored; exists to make separate and merged objects methods universally callable from _call_types()
Creates, links and returns a new light object depending on the type and color of the dxf entity.
"""
# light_type : distant = 1; point = 2; spot = 3
if self.import_light:
type_map = ["NONE", "SUN", "POINT", "SPOT"]
layer = self.dwg.layers[en.layer]
lamp = bpy.data.lamps.new(en.name, type_map[en.light_type])
if en.color != 256:
aci = en.color
else:
aci = layer.color
c = dxfgrabber.aci_to_true_color(aci)
lamp.color = Color(c.rgb())
if en.light_type == 3:
lamp.spot_size = en.hotspot_angle
o = bpy.data.objects.new(en.name, lamp)
o.location = self.proj(en.position)
dir = self.proj(en.target) - self.proj(en.position)
o.rotation_quaternion = dir.rotation_difference(Vector((0, 0, -1)))
scene.objects.link(o)
return o
def text(self, en, scene, name):
"""
en: dxf entity
name: ignored; exists to make separate and merged objects methods universally callable from _call_types()
Returns a new single line text object.
"""
if self.import_text:
name = en.text[:8]
d = bpy.data.curves.new(name, "FONT")
d.body = en.plain_text()
d.size = en.height
o = bpy.data.objects.new(name, d)
o.rotation_euler = Euler((0, 0, radians(en.rotation)), 'XYZ')
basepoint = self.proj(en.basepoint) if hasattr(en, "basepoint") else self.proj((0, 0, 0))
o.location = self.proj((en.insert)) + basepoint
if hasattr(en, "thickness"):
et = en.thickness / 2
d.extrude = abs(et)
if et > 0:
o.location.z += et
elif et < 0:
o.location.z -= et
return o
def polys_to_mesh(self, entities, scene, name):
d = bpy.data.meshes.new(name)
bm = bmesh.new()
m = Matrix(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)))
for en in entities:
t = m
verts = []
if is_.extrusion(en):
t = convert.extrusion_to_matrix(en)
for p in en.points:
verts.append(bm.verts.new(self.proj((t*Vector(p)).to_3d())))
if len(verts) > 2:
bm.faces.new(verts)
elif len(verts) == 2:
bm.edges.new(verts)
bm.to_mesh(d)
o = bpy.data.objects.new(name, d)
scene.objects.link(o)
return o
def get_lowest_world_co_from_mesh(ob, mat_parent=None):
bme = bmesh.new()
bme.from_mesh(ob.data)
mat_to_world = ob.matrix_world.copy()
if mat_parent:
mat_to_world = mat_parent * mat_to_world
lowest = None
for v in bme.verts:
if not lowest:
lowest = v
if (mat_to_world * v.co).z < (mat_to_world * lowest.co).z:
lowest = v
lowest_co = mat_to_world * lowest.co
bme.free()
return lowest_co
def connectArcTogetherWithEdge(self, edge, arcVertices, bm, mesh, parameters):
lastVert = len(arcVertices) - 1
if parameters["drawArcCenters"]:
lastVert = lastVert - 1 # center gets added as last vert of arc
edgeV1 = edge.verts[0].co
edgeV2 = edge.verts[1].co
arcV1 = arcVertices[0].co
arcV2 = arcVertices[lastVert].co
bmv1 = bm.verts.new(edgeV1)
bmv2 = bm.verts.new(arcV1)
bmv3 = bm.verts.new(edgeV2)
bmv4 = bm.verts.new(arcV2)
if parameters["connectArcWithEdgeFlip"] is False:
bme = bm.edges.new([bmv1, bmv2])
bme2 = bm.edges.new([bmv3, bmv4])
else:
bme = bm.edges.new([bmv1, bmv4])
bme2 = bm.edges.new([bmv3, bmv2])
self.sel.refreshMesh(bm, mesh)
def selectEdgesAfterRoundifier(self, context, edges):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
mesh = context.scene.objects.active.data
bmnew = bmesh.new()
bmnew.from_mesh(mesh)
self.deselectEdges(bmnew)
for selectedEdge in edges:
for e in bmnew.edges:
if (e.verts[0].co - selectedEdge.verts[0].co).length <= self.threshold \
and (e.verts[1].co - selectedEdge.verts[1].co).length <= self.threshold:
e.select_set(True)
bpy.ops.object.mode_set(mode='OBJECT')
bmnew.to_mesh(mesh)
bmnew.free()
bpy.ops.object.mode_set(mode='EDIT')
def execute(self, context):
# In edit mode
edit_object = context.edit_object
bpy.ops.object.mode_set(mode="OBJECT")
me = edit_object.data
bm = bmesh.new()
bm.from_mesh(me)
offset_infos, edges_orig = self.get_offset_infos(bm, edit_object)
if offset_infos is False:
bpy.ops.object.mode_set(mode="EDIT")
return {'CANCELLED'}
self.do_offset_and_free(bm, me, offset_infos, edges_orig)
return {'FINISHED'}
def make_one_inset(self, context, bm=None, ringvectors=None, center=None,
normal=None, t=None, base_height=0):
# a face will get 'inserted' faces to create (normaly) a hole if t is > 0 and < 1)
tmp = []
for el in ringvectors:
tmp.append((el * (1 - t) + center * t) + normal * base_height)
tmp = [bm.verts.new(v) for v in tmp] # the new corner bmvectors
# PKHG>INFO so to say sentinells, to use ONE for ...
tmp.append(tmp[0])
vectorsFace_i = [bm.verts.new(v) for v in ringvectors]
vectorsFace_i.append(vectorsFace_i[0])
myres = []
for ii in range(len(vectorsFace_i) - 1):
# PKHG>INFO next line: sequence is important! for added edge
bmvecs = [vectorsFace_i[ii], vectorsFace_i[ii + 1], tmp[ii + 1], tmp[ii]]
res = bm.faces.new(bmvecs)
myres.append(res.edges[2])
myres[-1].select = True # PKHG>INFO to be used later selected!
return (myres)
def boolean_difference():
ActiveObj = bpy.context.active_object
if bpy.context.selected_objects[0] != bpy.context.active_object:
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="CT_SOLIDIFY")
BoolMod = ActiveObj.modifiers.new("CT_" + bpy.context.selected_objects[0].name, "BOOLEAN")
BoolMod.object = bpy.context.selected_objects[0]
BoolMod.operation = "DIFFERENCE"
BoolMod.solver = bpy.context.scene.CarverSolver
bpy.context.selected_objects[0].draw_type = 'WIRE'
else:
BoolMod = ActiveObj.modifiers.new("CT_" + bpy.context.selected_objects[1].name, "BOOLEAN")
BoolMod.object = bpy.context.selected_objects[1]
BoolMod.operation = "DIFFERENCE"
BoolMod.solver = bpy.context.scene.CarverSolver
bpy.context.selected_objects[1].draw_type = 'WIRE'
def register():
bpy.types.Scene.DepthCursor = bpy.props.BoolProperty(name="DepthCursor", default=False)
bpy.types.Scene.OInstanciate = bpy.props.BoolProperty(name="Obj_Instantiate", default=False)
bpy.types.Scene.ORandom = bpy.props.BoolProperty(name="Random_Rotation", default=False)
bpy.types.Scene.DontApply = bpy.props.BoolProperty(name="Dont_Apply", default=False)
bpy.types.Scene.nProfile = bpy.props.IntProperty(name="Num_Profile", default=0)
bpy.utils.register_class(CarverPrefs)
bpy.utils.register_class(Carver)
# add keymap entry
kcfg = bpy.context.window_manager.keyconfigs.addon
if kcfg:
km = kcfg.keymaps.new(name='3D View', space_type='VIEW_3D')
kmi = km.keymap_items.new("object.carver", 'X', 'PRESS', shift=True, ctrl=True)
addon_keymaps.append((km, kmi))
def vefm_add_object(selfobj):
for i in range(len(selfobj.verts)):
selfobj.verts[i].index = i
v = [el.vector for el in selfobj.verts]
e = [[edge.a.index, edge.b.index] for edge in selfobj.edges]
if type(selfobj.faces[0]) == type([]):
# PKHG should be a list of vertices, which have an index
f = [[v.index for v in face] for face in selfobj.faces]
else:
f = [[v.index for v in face.vertices] for face in selfobj.faces]
m = bpy.data.meshes.new(name=selfobj.name)
m.from_pydata(v, e, f)
# useful for development when the mesh may be invalid.
m.validate(verbose=False)
object_data_add(bpy.context, m, operator=None)
# extra test phase
def initialise():
global_undo = bpy.context.user_preferences.edit.use_global_undo
bpy.context.user_preferences.edit.use_global_undo = False
object = bpy.context.active_object
if 'MIRROR' in [mod.type for mod in object.modifiers if mod.show_viewport]:
# ensure that selection is synced for the derived mesh
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(object.data)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
return(global_undo, object, bm)
# move the vertices to their new locations
def create_texture(self, fullpath):
try:
teximage = bpy.data.images.load(fullpath, True)
if teximage.users > 0:
for tex in bpy.data.textures:
if tex.type == 'IMAGE' and tex.image == teximage:
return tex
name,ext = os.path.splitext(os.path.basename(fullpath))
texobj = bpy.data.textures.new(name, type='IMAGE')
texobj.image = teximage
return texobj
except Exception as e:
for tex in bpy.data.textures:
if tex.type == 'IMAGE' and tex.name == fullpath:
return tex
return bpy.data.textures.new(fullpath, type='IMAGE')
def create_object(self, rip, obj_name, mesh, mat):
nobj = bpy.data.objects.new(obj_name, mesh)
if mat:
if self.dedup.is_sharing_mesh():
nobj.material_slots[0].link = 'OBJECT'
nobj.material_slots[0].material = mat
else:
mesh.materials.append(mat)
if 'ninjarip_vgroups' in mesh:
for vname in mesh["ninjarip_vgroups"].split(','):
nobj.vertex_groups.new('blendweight'+vname)
for i in range(len(rip.shaders)):
nobj["shader_"+str(i)] = rip.shaders[i]
return nobj
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 set_models(ob, name):
# If possible, attach child mesh objects (requires models to be available, io_scene_bfres and no existing children).
if name in _empty_models or not addon_utils.check("io_scene_bfres")[1] or len(ob.children):
return
# Get the model or load it if it does not exist yet.
model_ob = bpy.data.objects.get("MK8.{}".format(name))
if not model_ob:
model_ob = _load_model(name)
if not model_ob:
log(0, "Warning: No model found for '{}'.".format(name))
_empty_models.append(name)
return
model_ob.name = "MK8.{}".format(name)
# Link-clone the child objects and attach them to the given parent.
for child in model_ob.children:
child_ob = bpy.data.objects.new(child.name, child.data)
child_ob.mk8.object_type = "ADDON_VISUALIZER"
child_ob.parent = ob
child_ob.lock_location = [True] * 3
child_ob.lock_rotation = [True] * 3
child_ob.lock_scale = [True] * 3
bpy.context.scene.objects.link(child_ob)
bpy.context.scene.update() # Required to find the children at the parent's transform eventually.
def _load_model(name_or_id):
# Find the path to the BFRES file of the Obj model and load it.
model_ob = None
for res_name in objflow.get_res_names_by_id(name_or_id):
model_path = _get_model_path(res_name)
if not model_path:
continue
# Create the object which will hold all child mesh objects.
if not model_ob:
model_ob = bpy.data.objects.new("MK8.{}".format(name_or_id), None)
# Load the BFRES with the special parent object to which all FSHP mesh objects become children of.
all_tex = bpy.context.user_preferences.addons[__package__].preferences.import_all_textures
lod_idx = bpy.context.user_preferences.addons[__package__].preferences.lod_model_index
bpy.ops.import_scene.bfres(filepath=model_path, parent_ob_name=model_ob.name, mat_name_prefix=res_name, lod_model_index=lod_idx,
tex_import_normal=all_tex, tex_import_specular=all_tex, tex_import_emissive=all_tex)
return model_ob
def add_lattice(self, coordinates):
lattice_data = bpy.data.lattices.new(name='fast-lattice')
lattice_object = bpy.data.objects.new(name='fast-lattice', object_data=lattice_data)
lattice_object.rotation_euler = self.rotation(coordinates).to_euler()
lattice_object.location = self.location(coordinates)
lattice_object.scale = self.scale(coordinates, self.minimum_matrix)
lattice_object.show_x_ray = True
lattice_data.interpolation_type_u = self.interpolation_type
lattice_data.interpolation_type_v = self.interpolation_type
lattice_data.interpolation_type_w = self.interpolation_type
lattice_data.use_outside = True
return lattice_object