def blenderstructure(self, ): for i in range(len(self.xyz.atomtypes)): me = Mesh.Primitives.Icosphere(spheresubdivisions, atomicradii[self.xyz.atomtypes[i]]) me.materials = [materials[self.xyz.atomtypes[i]]] for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Mesh') obj.setLocation(self.xyz.coord[i][0], self.xyz.coord[i][1], self.xyz.coord[i][2]) for i in range(len(self.xyz.atomtypes)): for j in range(i + 1, len(self.xyz.atomtypes)): vec1 = Mathutils.Vector(self.xyz.coord[i]) vec2 = Mathutils.Vector(self.xyz.coord[j]) vec = vec2 - vec1 distcovalent = covalentradii[self.xyz.atomtypes[ i]] + covalentradii[self.xyz.atomtypes[j]] if (vec.length - distcovalent) <= 0.10 * distcovalent: me = Mesh.Primitives.Tube(32, stickradius, vec.length) for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Cylinder') axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec) angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec) rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis) obj.setMatrix(obj.matrix * rotmat) obj.setLocation((vec1 + vec2) * 0.5)
def blenderstructure(self, ): nat = len(self.xyz.atomtypes) # create atoms for i in range(0, nat): loc = Mathutils.Vector(self.xyz.coord[i]) me = Mesh.Primitives.Icosphere(spheresubdivisions, atomicradii[self.xyz.atomtypes[i]]) me.materials = [materials[self.xyz.atomtypes[i]]] for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Atom') obj.setLocation(loc) # form bonds between atoms for i in range(0, nat): for j in range(i + 1, nat): vec1 = Mathutils.Vector(self.xyz.coord[i]) vec2 = Mathutils.Vector(self.xyz.coord[j]) vec = vec2 - vec1 distcovalent = covalentradii[self.xyz.atomtypes[ i]] + covalentradii[self.xyz.atomtypes[j]] print "vec.length = %s distcovalent = %s" % (vec.length, distcovalent) if (vec.length - distcovalent) <= 0.10 * distcovalent: me = Mesh.Primitives.Tube(32, stickradius, vec.length) for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Bond') axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec) angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec) rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis) obj.setMatrix(obj.matrix * rotmat) obj.setLocation((vec1 + vec2) * 0.5) # vectors scale = 1.0 #1000.0 #1.0 #1000.0 for i in range(0, nat): loc = Mathutils.Vector(self.xyz.coord[i]) vec = Mathutils.Vector(self.xyz.vectors[i]) * scale # arrow tail me = Mesh.Primitives.Tube(32, arrowradius, vec.length) me.materials = [materials["arrow"]] for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, "Arrow-Tail") axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec) angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec) rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis) obj.setMatrix(obj.matrix * rotmat) obj.setLocation(loc + 0.5 * vec) # arrow head me = Mesh.Primitives.Cone(32, 2 * arrowradius, 0.5) me.materials = [materials["arrow"]] for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, "Arrow-Head") axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec) angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec) rotmat = Mathutils.RotationMatrix(angle + 180.0, 4, "R", axis) obj.setMatrix(obj.matrix * rotmat) obj.setLocation(loc + vec)
def exportCurve(ob, mx): entities = [] curve = ob.getData() for cur in curve: #print 'deb: START cur=', cur #-------------- if 1: #not cur.isNurb(): #print 'deb: START points' #-------------- points = [] org_point = [0.0,0.0,0.0] for point in cur: #print 'deb: point=', point #--------- if cur.isNurb(): vec = point[0:3] else: point = point.getTriple() #print 'deb: point=', point #--------- vec = point[1] #print 'deb: vec=', vec #--------- pkt = Mathutils.Vector(vec) * mx #print 'deb: pkt=', pkt #--------- #pkt *= SCALE_FACTOR if 0: #FLATTEN: pkt = projected_co(pkt, mw) points.append(pkt) if cur.isCyclic(): closed = 1 else: closed = 0 if len(points)>1: #print 'deb: points', points #-------------- if POLYLINES: dxfPLINE = PolyLine(points,org_point,closed) else: dxfPLINE = LineList(points,org_point,closed) entities.append(dxfPLINE) return entities
def eulToVecRot(self, RotX, RotY, RotZ): ti = RotX * 0.5 tj = RotY * 0.5 th = RotZ * 0.5 ci = math.cos(ti) cj = math.cos(tj) ch = math.cos(th) si = math.sin(ti) sj = math.sin(tj) sh = math.sin(th) cc = ci * ch cs = ci * sh sc = si * ch ss = si * sh q0 = cj * cc + sj * ss q1 = cj * sc - sj * cs q2 = cj * ss + sj * cc q3 = cj * cs - sj * sc angle = 2 * math.acos(q0) if (math.fabs(angle) < 0.000001): axis = [1.0, 0.0, 0.0] else: sphi = 1.0 / math.sqrt(1.0 - (q0 * q0)) axis = [q1 * sphi, q2 * sphi, q3 * sphi] a = Mathutils.Vector(axis) a.normalize() return ([a.x, a.y, a.z], angle)
def bone_transform(self, bone_name="Root"): """ Return 4x4 transform matrix giving bone's chage. """ frames = self.action.getFrameNumbers() (first, last) = (frames[0], frames[-1]) ipo = self.action.getChannelIpo(bone_name) position_first = Mathutils.Vector( \ list(ipo[key][first] for key in act_position_keys)) position_last = Mathutils.Vector( \ list(ipo[key][last] for key in act_position_keys)) rotation_first = Mathutils.Quaternion( \ list(ipo[key][first] for key in act_rotation_keys)) rotation_last = Mathutils.Quaternion( \ list(ipo[key][last] for key in act_rotation_keys)) delta_position = position_last - position_first delta_rotation = Mathutils.DifferenceQuats(rotation_last, rotation_first) return offset_and_rotation_to_matrix(delta_position, delta_rotation)
def writeCoordinates(self, me, meshName): coordName = "coord_%s" % (meshName) # look up coord name, use it if available if self.coordNames.has_key(coordName): self.writeIndented("coord USE %s\n" % coordName, 0) self.coordNames[coordName] += 1 return self.coordNames[coordName] = 1 #-- vertices self.writeIndented("coord DEF %s Coordinate {\n" % (coordName), 1) self.writeIndented("point [\n", 1) meshVertexList = me.verts for vertex in meshVertexList: vrmlvert = blenvert = Mathutils.Vector(vertex.co) if export_rotate_z_to_y.val: vrmlvert = M_blen2vrml * vrmlvert self.writeUnindented("%s %s %s\n " % \ (vrmlvert[0], \ vrmlvert[1], \ vrmlvert[2])) self.writeIndented("]\n", -1) self.writeIndented("}\n", -1) self.writeIndented("\n")
def transform_verts(verts, m): vecs = [] for v in verts: x, y, z = v.co vec = Mathutils.Vector([x, y, z, 1]) vecs.append(vec*m) return vecs
def _get_local_pos(self, pos, parent): p_scale = parent.scale return (pos[0]/p_scale[0], pos[1]/p_scale[1], pos[2]/p_scale[2]) parent_imatrix = parent.matrix_world.copy().invert() pos_v = mathutils.Vector(pos) l_pos = pos_v*parent_imatrix return (l_pos[0], l_pos[1], l_pos[2])
def calc_drop_loc(ob, terrain_tris, axis): pt = Mathutils.Vector(ob.loc) isect = None isect_best = None isect_best_len = 0.0 for t1, t2, t3 in terrain_tris: #if Geometry.PointInTriangle2D(pt, t1,t2,t3): isect = Mathutils.Intersect(t1, t2, t3, axis, pt, 1) # 1==clip if isect: if not GLOBALS['DROP_OVERLAP_CHECK'].val: # Find the first location return isect else: if isect_best: isect_len = (pt - isect).length if isect_len < isect_best_len: isect_best_len = isect_len isect_best = isect else: isect_best_len = (pt - isect).length isect_best = isect return isect_best
def export_camera(cam): global IBLLIGHT # get the camera camera = cam.getData() print "o exporting Camera " + camera.getName() + "..." # get the object matrix so we can calculate to and up objmatrix = cam.matrix eyeV = Mathutils.Vector([0, 0, 0, 1]) targetV = Mathutils.Vector([0, 0, -1, 1]) upV = Mathutils.Vector([0, 1, 0, 0]) eyeV = eyeV * objmatrix targetV = targetV * objmatrix upV = upV * objmatrix # get the fov value fov = 360.0 * atan(16.0 / camera.getLens()) / pi FILE.write("\n\ncamera {\n") camtype = "pinhole" if (DOF.val == 1): camtype = "thinlens" if (SPHERICALCAMERA.val == 1): camtype = "spherical" FILE.write("\ttype %s\n" % camtype) FILE.write("\teye %s %s %s\n" % (eyeV[0], eyeV[1], eyeV[2])) FILE.write("\ttarget %s %s %s\n" % (targetV[0], targetV[1], targetV[2])) FILE.write("\tup %s %s %s\n" % (upV[0], upV[1], upV[2])) if SPHERICALCAMERA.val == 0: FILE.write("\tfov %s \n" % fov) if SPHERICALCAMERA.val == 0: FILE.write("\taspect %s \n" % (1.0 * IM_WIDTH / IM_HEIGHT)) if DOF.val == 1: FILE.write("\tfdist %s \n" % DOFDIST) FILE.write("\tlensr %s \n" % DOFRADIUS) FILE.write("}") if IBLLIGHT <> "": print "o exporting ibllight..." FILE.write("\n\nlight {\n") FILE.write("\ttype ibl\n") FILE.write("\timage \"%s\"\n" % (IBLLIGHT)) FILE.write("\tcenter 1 0 0\n") FILE.write("\tup 0 0 1\n") FILE.write("\tlock true\n") FILE.write("\tsamples %s\n" % DSAMPLES.val) FILE.write("}")
def writeCamera(o, scene): camobj = scene.objects.camera camera = Blender.Camera.Get()[0] o.write("transform { lookAt {\n") mat = camobj.getMatrix() eyeV = Mathutils.Vector([0, 0, 0, 1]) targetV = Mathutils.Vector([0, 0, -1, 1]) upV = Mathutils.Vector([0, 1, 0, 0]) eyeV = eyeV * mat targetV = targetV * mat upV = upV * mat # eye position can just be read out of the matrix w = mat[3][3] eye = (mat[3][0] / w, mat[3][1] / w, mat[3][2] / w) o.write(" pos %f %f %f\n" % (eyeV.x, eyeV.y, eyeV.z)) # get the dir vector (camera looking down z) d = (mat[2][0], mat[2][1], mat[2][2]) print(d) print(d[0]) # look is just the eye position - the direction look = (eye[0] - d[0], eye[1] - d[1], eye[2] - d[2]) o.write(" look %f %f %f\n" % (targetV.x, targetV.y, targetV.z)) # up vector can just be read out of the matrix (y axis) up = (mat[1][0], mat[1][1], mat[1][2]) o.write(" up %f %f %f\n" % (upV.x, upV.y, upV.z)) o.write("}}\n\n") o.write("camera {\n") o.write(" perspective") factor = 1 fov = 360.0 * math.atan(factor * 16.0 / camera.lens) / math.pi o.write(" fov %f\n" % fov) o.write(" lensRadius 0\n") o.write(" focalDistance 10 }\n\n") o.write("transform { identity }\n\n")
def write_objects(filepath): """Write all selected objects to filepath""" # get all selected objects objects = Blender.Object.GetSelected() f = file(filepath, 'w') # write header to file f.write('# Generated by sketch_export.py v %s \n' % (__version__)) # iterate over each object # Todo: Should I group meshes and objects? s = "" s += "% Mesh section\n\n" for obj in objects: s += write_object(obj) if used_materials: c = write_materials(used_materials) s = c + "\n" + s groups = Group.Get() c = "" if EXPORT_GROUPS and groups: s += "% Group section" for group in groups: objects = group.objects if objects: for obj in objects: obj_name = sketchify(obj.name) if obj_name in drawables: c += " {%s}\n" % obj_name if c: group_name = sketchify(group.name) s += "\ndef %s {\n%s}\n" % (group_name, c) c = "" # Write scene to file if drawables: s += "\ndef scene {\n" if EXPORT_CAMERA: scn = Blender.Scene.GetCurrent() cam = scn.objects.camera vec = Mathutils.Vector([0, 0, -1]) direction = cam.matrix.rotationPart() * vec loc = cam.getLocation('worldspace') s += " put {view((%f,%f,%f),(%f,%f,%f),[0,0,1])}{\n" % \ tuple(list(loc) + list(direction)) for name in drawables: s += " {%s}\n" % name if EXPORT_CAMERA: s += " }\n" s += "}\n" if STANDALONE: s += "\n" s += "{scene}\n" if OUTPUT_LANGUAGE == 'tikz': s += "global {language tikz}\n" f.write(s) f.close()
def terrain_clamp(event, value): sce = bpy.data.scenes.active if GLOBALS['GROUND_SOURCE'][0].val: obs_terrain = [sce.objects.active] if not obs_terrain[0]: error_noact() return else: try: obs_terrain = bpy.data.groups[ GLOBALS['GROUND_GROUP_NAME'].val].objects except: error_nogroup() return obs_clamp = [ ob for ob in sce.objects.context if ob not in obs_terrain and not ob.lib ] if not obs_clamp: error_no_obs() return terrain_tris = collect_terrain_triangles(obs_terrain) if not terrain_tris: error_noground() return if GLOBALS['DROP_AXIS'][0].val: axis = Mathutils.Vector(0, 0, -1) else: axis = Mathutils.Vector(Window.GetViewVector()) for ob in obs_clamp: loc = calc_drop_loc(ob, terrain_tris, axis) if loc: ob.loc = loc # to make the while loop exist GLOBALS['EVENT'] = EVENT_EXIT
def MakeVertexRing(vertex_list, angle): m = Mathutils.RotationMatrix(angle, 3, "z") for i in xrange(MinorDivisions): phi = (pi * 2 * i / MinorDivisions) + StartMinorAngle x = MajorRadius + MinorRadius * cos(phi) y = 0.0 z = MinorRadius * sin(phi) v = Mathutils.Vector([x, y, z]) v = Mathutils.VecMultMat(v, m) vertex_list.append(NMesh.Vert(v.x, v.y, v.z))
def average_normals(faces): ret = Mathutils.Vector(0.0, 0.0, 0.0) for face in faces: normal = face.no ret.x = ret.x + normal.x ret.y = ret.y + normal.y ret.z = ret.z + normal.z ret.x = ret.x / len(faces) ret.y = ret.y / len(faces) ret.z = ret.z / len(faces) return ret
def _get_local_scale(self, scale, parent): p_scale = parent.scale return (scale[0]/p_scale[0], scale[1]/p_scale[1], scale[2]/p_scale[2]) parent_imatrix = parent.matrix_world.to_euler().to_matrix() parent_imatrix.invert() p_scale = parent.scale scale = (scale[0]/p_scale[0], scale[1]/p_scale[1], scale[2]/p_scale[2]) scale = mathutils.Vector(scale) #scale_x = mathutils.Matrix.Scale(scale[0], 3, mathutils.Vector((1,0,0))) #scale_y = mathutils.Matrix.Scale(scale[1], 3, mathutils.Vector((0,1,0))) #scale_z = mathutils.Matrix.Scale(scale[2], 3, mathutils.Vector((0,0,1))) #scale_m = scale_x * scale_y * scale_z scale = scale * parent_imatrix l_pos = scale return (l_pos[0], l_pos[1], l_pos[2])
def exportFrame(_armature, i, bone, out): print "===Frame :"+ str(i)+"========" Blender.Set("curframe",i) pose = _armature.getPose() tail = pose.bones[bone.name].tail head = pose.bones[bone.name].head print "tail:" print tail print "head:" print head initial = bone.matrix['ARMATURESPACE'] initial.invert() flipMatrix = Mathutils.Matrix([1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]) finalmatrix = Mathutils.Matrix(bone.matrix['ARMATURESPACE']) * pose.bones[bone.name].poseMatrix #* flipMatrix#initial * matrix print "Euler:" print matrixToEuler(finalmatrix) print "Pos:" print vector_by_matrix(finalmatrix, Mathutils.Vector( [ 0, 0, 0 ] )) floats = array('f') #print finalmatrix for a in range(4): for b in range(4): floats.append(finalmatrix[a][b]) #floats = array('f') floats.append(tail[0]) floats.append(tail[1]) floats.append(tail[2]) floats.append(head[0]) floats.append(head[1]) floats.append(head[2]) floats.tofile(out)
import Blender.Mathutils as MU # Get orientation of the Body_Point Orientation_Body_Point = GL.Globals['Body_Point'].getOrientation() # Get orientation of the Body Orientation_Body = GL.Globals['Body'].getOrientation() # Adjust z GL.Globals['z'] = (GL.Globals['Body_Point'].getPosition()[2] - GL.Globals['z_0']) * GL.Globals['Blender_Factor_Position'] # Adjust phi_x if Orientation_Body[2][1] > 0: phi_x_Body = (M.pi / 180.0) * MU.AngleBetweenVecs( MU.Vector(Orientation_Body[0][1], Orientation_Body[1][1], Orientation_Body[2][1]), MU.Vector(Orientation_Body_Point[0][1], Orientation_Body_Point[1][1], Orientation_Body_Point[2][1])) else: phi_x_Body = -(M.pi / 180.0) * MU.AngleBetweenVecs( MU.Vector(Orientation_Body[0][1], Orientation_Body[1][1], Orientation_Body[2][1]), MU.Vector(Orientation_Body_Point[0][1], Orientation_Body_Point[1][1], Orientation_Body_Point[2][1])) GL.Globals['phi_x'] = phi_x_Body * GL.Globals['Blender_Factor_Angle'] # Adjust phi_y if Orientation_Body[2][0] > 0: phi_y_Body = -(M.pi / 180.0) * MU.AngleBetweenVecs( MU.Vector(Orientation_Body[0][0], Orientation_Body[1][0], Orientation_Body[2][0]),
def export(filename): out = file(filename,'wb+') scene = bpy.data.scenes.active Objects = scene.objects ints = array('i') ints.append(ObjectCount(Objects, 'Mesh')) ints.tofile(out) ints.pop for ob in Objects: if (ob.getType()== 'Mesh'): mesh = ob.getData() ExportGeometry(mesh, out) if (ob.parent != None): parent = ob.parent if (parent.getType() == 'Armature'): ArmatureData = parent.getData() RootBone = getRootBone(ArmatureData) print 'root bone name is:' + RootBone.name PrintBones(RootBone) WriteBoneTree(RootBone, mesh, out) Bones = ArmatureData.bones BoneData = Bones.values() totalFrames = Blender.Get("endframe") -\ Blender.Get("staframe") + 1 framec = array('i') framec.append(totalFrames) framec.tofile(out) framec.pop for bone in BoneData: bnameLen = array('i') bnameLen.append(len(bone.name)) bnameLen.tofile(out) bname = array('c') bname.fromstring(bone.name) print '-----------------------------' print bname bname.tofile(out) floats = array('f') floats.append(bone.head['ARMATURESPACE'].x) floats.append(bone.head['ARMATURESPACE'].y) floats.append(bone.head['ARMATURESPACE'].z) floats.append(bone.tail['ARMATURESPACE'].x) floats.append(bone.tail['ARMATURESPACE'].y) floats.append(bone.tail['ARMATURESPACE'].z) floats.tofile(out) print "--------------------------" m = Mathutils.Matrix(bone.matrix['ARMATURESPACE']) m = m.invert() fm = array('f') for a in range(4): for b in range(4): fm.append(m[a][b]) fm.tofile(out) print "Euler values:" print matrixToEuler(m) print "translation:" print vector_by_matrix(m, Mathutils.Vector( [ 0, 0, 0 ] )) print "----------------------------" for i in range(Blender.Get("staframe"),Blender.Get("endframe")+1): exportFrame(parent, i, bone, out) #for each frame #if armature out.close()
def vector_by_matrix( m, p ): return Mathutils.Vector( [ p[0] * m[0][0] + p[1] * m[1][0] + p[2] * m[2][0] + m[3][0], p[0] * m[0][1] + p[1] * m[1][1] + p[2] * m[2][1] + m[3][1], p[0] * m[0][2] + p[1] * m[1][2] + p[2] * m[2][2] + m[3][2] ] )
def matrixToEuler( matrix ): euler = matrix.toEuler() return Mathutils.Vector( -euler.x, euler.y, -euler.z )
def export_lights(lmp): # only lamp type 0 supported at the moment # lamp types are: 0 - Lamp, 1 - Sun, 2 - Spot, 3 - Hemi, 4 - Area lamp = lmp.getData() if lamp.type == 0: print "o exporting lamp " + lmp.name + "..." # get the rgb component for the lamp red = lamp.col[0] green = lamp.col[1] blue = lamp.col[2] power = lamp.energy # get the location of the lamp objmatrix = lmp.matrix lampV = Mathutils.Vector([0, 0, 0, 1]) lampV = lampV * objmatrix FILE.write("\n\nlight {\n") FILE.write("\ttype point\n") FILE.write("\tcolor { \"sRGB nonlinear\" %s %s %s }\n" % (red, green, blue)) FILE.write("\tpower %s\n" % (power)) FILE.write("\tp %s %s %s\n" % (lampV[0], lampV[1], lampV[2])) FILE.write("}") elif lamp.type == 1: print "o exporting sun-light " + lmp.name + "..." invmatrix = Mathutils.Matrix(lmp.getInverseMatrix()) FILE.write("\nlight {\n") FILE.write("\ttype sunsky\n") FILE.write("\tup 0 0 1\n") FILE.write("\teast 0 1 0\n") FILE.write("\tsundir %f %f %f\n" % (invmatrix[0][2], invmatrix[1][2], invmatrix[2][2])) FILE.write("\tturbidity 6\n") FILE.write("\tsamples %s\n" % DSAMPLES.val) FILE.write("}") elif lamp.type == 4: print "o exporting area-light " + lmp.name + "..." objmatrix = lmp.matrix size = lamp.areaSizeX * 0.5 lampV0 = Mathutils.Vector([-size, size, 0, 1]) lampV1 = Mathutils.Vector([size, size, 0, 1]) lampV2 = Mathutils.Vector([size, -size, 0, 1]) lampV3 = Mathutils.Vector([-size, -size, 0, 1]) lampV0 = lampV0 * objmatrix lampV1 = lampV1 * objmatrix lampV2 = lampV2 * objmatrix lampV3 = lampV3 * objmatrix red = lamp.col[0] green = lamp.col[1] blue = lamp.col[2] radiance = lamp.energy * MESHLIGHTPOWER.val FILE.write("\n\nlight {\n") FILE.write("\ttype meshlight\n") FILE.write("\tname \"%s\"\n" % (lmp.name)) FILE.write("\temit { \"sRGB nonlinear\" %s %s %s }\n" % (red, green, blue)) FILE.write("\tradiance %s\n" % (radiance)) FILE.write("\tsamples %s\n" % DSAMPLES.val) FILE.write("\tpoints 4\n") FILE.write("\t\t%s %s %s\n" % (lampV0[0], lampV0[1], lampV0[2])) FILE.write("\t\t%s %s %s\n" % (lampV1[0], lampV1[1], lampV1[2])) FILE.write("\t\t%s %s %s\n" % (lampV2[0], lampV2[1], lampV2[2])) FILE.write("\t\t%s %s %s\n" % (lampV3[0], lampV3[1], lampV3[2])) FILE.write("\ttriangles 2\n") FILE.write("\t\t0 1 2\n") FILE.write("\t\t0 2 3\n") FILE.write("}")
result = Draw.PupMenu(convert) if result == 1: camob = scn.objects.camera else: cam = Camera.New('persp', 'TCam') camob = scn.objects.new(cam) scn.objects.camera = camob camob.setLocation(Window.GetCursorPos()) if camob: target = scn.objects.new('Empty', (camob.name + '.target')) matrix = camob.getMatrix() tvect = Mathutils.Vector([0,0,-10]) targetv = tvect*matrix target.setLocation(targetv) cam = camob.data #cam.drawLimits = 1 cam.drawSize = 2.0 campos = Mathutils.Vector([camob.dloc[0],camob.dloc[1],camob.dloc[2]]) dofdistv = campos-targetv dofdist = dofdistv.length #cam.dofDist = dofdist cam.clipEnd = 1500 const = camob.constraints.append(Constraint.Type.TRACKTO) const[Constraint.Settings.TARGET] = target const[Constraint.Settings.TRACK] = Constraint.Settings.TRACKNEGZ const[Constraint.Settings.UP] = Constraint.Settings.UPY
def animatedensity(self, filenamelist, renderingpath, isovalue): context = self.scene.getRenderingContext() context.extensions = True context.renderPath = renderingpath #context.imageType=Render.JPEG context.sFrame = 1 context.eFrame = 1 context.sizeX = width context.sizeY = height cubeobject = cube(filenamelist[0]) cubeobject.readCube() atoms = [] ipokeytypeloc = Object.IpoKeyTypes.LOC ipokeytyperot = Object.IpoKeyTypes.ROT for i in range(len(cubeobject.atomtypes)): me = Mesh.Primitives.Icosphere( spheresubdivisions, atomicradii.get(cubeobject.atomtypes[i], 2.0)) me.materials = [ materials.get(cubeobject.atomtypes[i], materials["default"]) ] for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Atom') obj.setLocation(cubeobject.coord[i][0], cubeobject.coord[i][1], cubeobject.coord[i][2]) atoms.append(obj) bonds = [] for i in range(len(cubeobject.atomtypes)): for j in range(i + 1, len(cubeobject.atomtypes)): vec1 = Mathutils.Vector(cubeobject.coord[i]) vec2 = Mathutils.Vector(cubeobject.coord[j]) vec = vec2 - vec1 distcovalent = covalentradii.get( cubeobject.atomtypes[i], 2.0) + covalentradii.get( cubeobject.atomtypes[j], 2.0) if (vec.length - distcovalent) <= 0.10 * distcovalent: me = Mesh.Primitives.Tube(32, stickradius, vec.length) for face in me.faces: face.smooth = True obj = self.scene.objects.new(me, 'Cylinder') axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec) angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec) rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis) obj.setMatrix(obj.matrix * rotmat) obj.setLocation((vec1 + vec2) * 0.5) bonds.append([i, j, vec, obj, vec.length]) self.isosurface(cubeobject, isovalue) context.render() filename = "RENDER/image_0000.jpg" context.saveRenderedImage(filename) for j in range(1, len(filenamelist)): print(("Rendering:", j)) filename = "RENDER/image_%04d.jpg" % (j) for ob in self.scene.objects: if "Lobe" in ob.name: self.scene.unlink(ob) cubeobject = cube(filenamelist[j]) cubeobject.readCube() for i in range(len(atoms)): atoms[i].setLocation(cubeobject.coord[i][0], cubeobject.coord[i][1], cubeobject.coord[i][2]) atoms[i].insertIpoKey(ipokeytypeloc) for i in range(len(bonds)): vec1 = Mathutils.Vector(cubeobject.coord[bonds[i][0]]) vec2 = Mathutils.Vector(cubeobject.coord[bonds[i][1]]) vec = vec2 - vec1 dist = vec.length axis = Mathutils.CrossVecs(bonds[i][2], vec) angle = Mathutils.AngleBetweenVecs(bonds[i][2], vec) rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis) bonds[i][3].setMatrix(bonds[i][3].matrix * rotmat) bonds[i][3].setLocation((vec1 + vec2) * 0.5) bonds[i][3].setSize(1.0, 1.0, dist / bonds[i][4]) bonds[i][3].insertIpoKey(ipokeytypeloc) bonds[i][3].insertIpoKey(ipokeytyperot) bonds[i][2] = vec bonds[i][4] = dist self.isosurface(cubeobject, isovalue) context.render() context.saveRenderedImage(filename)
def import_submesh(self, meshId, new_mesh, vertex, vbuffer, indices, materialName, matIdx): """ Import submesh info and fill blender face and vertex information. """ vertex_legend = get_vertex_legend(vertex) pos_offset = vertex_legend[VES_POSITION][1] no_offset = vertex_legend[VES_NORMAL][1] image = None if materialName in self._imported_ogre_materials: ogremat = self._imported_ogre_materials[materialName] if ogremat.btex and ogremat.btex.image: image = ogremat.btex.image if VES_TEXTURE_COORDINATES in vertex_legend: uvco_offset = vertex_legend[VES_TEXTURE_COORDINATES][1] vertmaps = {} indices_map = [] # vertices for idx in range(max(indices)+1): coords = get_vcoords(vbuffer, idx, pos_offset) if coords: if not coords in vertmaps: new_mesh.verts.extend(*coords) vertmaps[coords] = len(new_mesh.verts)-1 indices_map.append(vertmaps[coords]) else: new_mesh.verts.extend(0.0,0.0,0.0) indices_map.append(len(new_mesh.verts)-1) if not len(new_mesh.verts): logger.debug("mesh with no vertex!!") # faces for idx in range(len(indices)/3): idx = idx*3 new_mesh.vertexUV = False face = [indices_map[indices[idx]], indices_map[indices[idx+1]], indices_map[indices[idx+2]]] new_mesh.faces.extend(face, ignoreDups=True) if len(new_mesh.faces) == 0: logger.debug("Degenerate face!") continue face = new_mesh.faces[len(new_mesh.faces)-1] if image: face.image = image try: no1 = get_nor(indices[idx], vbuffer, no_offset) except: no1 = [0.0,0.0,0.0] try: no2 = get_nor(indices[idx+1], vbuffer, no_offset) except: no2 = [0.0,0.0,0.0] try: no3 = get_nor(indices[idx+2], vbuffer, no_offset) except: no3 = [0.0,0.0,0.0] if VES_TEXTURE_COORDINATES in vertex_legend: uv1 = get_uv(indices[idx], vbuffer, uvco_offset) uv2 = get_uv(indices[idx+1], vbuffer, uvco_offset) uv3 = get_uv(indices[idx+2], vbuffer, uvco_offset) face.uv = (mathutils.Vector(uv1), mathutils.Vector(uv2), mathutils.Vector(uv3)) if not len(new_mesh.faces): logger.warning("mesh with no faces!!") #sys.stderr.write("*") #sys.stderr.flush() return new_mesh
def mesh_mirror(me, PREF_MIRROR_LOCATION, PREF_XMID_SNAP, PREF_MAX_DIST, PREF_XZERO_THRESH, PREF_MODE, PREF_SEL_ONLY, PREF_EDGE_USERS, PREF_MIRROR_WEIGHTS, PREF_FLIP_NAMES, PREF_CREATE_FLIP_NAMES): ''' PREF_MIRROR_LOCATION, Will we mirror locations? PREF_XMID_SNAP, Should we snap verts to X-0? PREF_MAX_DIST, Maximum distance to test snapping verts. PREF_XZERO_THRESH, How close verts must be to the middle before they are considered X-Zero verts. PREF_MODE, 0:middle, 1: Left. 2:Right. PREF_SEL_ONLY, only snap the selection PREF_EDGE_USERS, match only verts with the same number of edge users. PREF_MIRROR_LOCATION, ''' # Operate on all verts if not PREF_SEL_ONLY: for v in me.verts: v.sel = 1 if PREF_EDGE_USERS: edge_users = [0] * len(me.verts) for ed in me.edges: edge_users[ed.v1.index] += 1 edge_users[ed.v2.index] += 1 if PREF_XMID_SNAP: # Do we snap locations at all? for v in me.verts: if v.sel: if abs(v.co.x) <= PREF_XZERO_THRESH: v.co.x = 0 v.sel = 0 # alredy de-selected verts neg_vts = [v for v in me.verts if v.sel and v.co.x < 0] pos_vts = [v for v in me.verts if v.sel and v.co.x > 0] else: # Use a small margin verts must be outside before we mirror them. neg_vts = [v for v in me.verts if v.sel if v.co.x < -PREF_XZERO_THRESH] pos_vts = [v for v in me.verts if v.sel if v.co.x > PREF_XZERO_THRESH] #*Mirror Location*********************************************************# if PREF_MIRROR_LOCATION: mirror_pairs = [] # allign the negative with the positive. flipvec = Mathutils.Vector() len_neg_vts = float(len(neg_vts)) for i1, nv in enumerate(neg_vts): if nv.sel: # we may alredy be mirrored, if so well be deselected nv_co = nv.co for i2, pv in enumerate(pos_vts): if pv.sel: # Enforce edge users. if not PREF_EDGE_USERS or edge_users[i1] == edge_users[ i2]: flipvec[:] = pv.co flipvec.x = -flipvec.x l = (nv_co - flipvec).length if l == 0.0: # Both are alredy mirrored so we dont need to think about them. # De-Select so we dont use again/ pv.sel = nv.sel = 0 # Record a match. elif l <= PREF_MAX_DIST: # We can adjust the length by the normal, now we know the length is under the limit. # DISABLED, WASNT VERY USEFULL ''' if PREF_NOR_WEIGHT>0: # Get the normal and flipm reuse flipvec flipvec[:]= pv.no flipvec.x= -flipvec.x try: ang= Mathutils.AngleBetweenVecs(nv.no, flipvec)/180.0 except: # on rare occasions angle between vecs will fail.- zero length vec. ang= 0 l=l*(1+(ang*PREF_NOR_WEIGHT)) ''' # Record the pairs for sorting to see who will get joined mirror_pairs.append((l, nv, pv)) # Update every 20 loops if i1 % 10 == 0: Window.DrawProgressBar( 0.8 * (i1 / len_neg_vts), 'Mirror verts %i of %i' % (i1, len_neg_vts)) Window.DrawProgressBar(0.9, 'Mirror verts: Updating locations') # Now we have a list of the pairs we might use, lets find the best and do them first. # de-selecting as we go. so we can makke sure not to mess it up. try: mirror_pairs.sort(key=lambda a: a[0]) except: mirror_pairs.sort(lambda a, b: cmp(a[0], b[0])) for dist, v1, v2 in mirror_pairs: # dist, neg, pos if v1.sel and v2.sel: if PREF_MODE == 0: # Middle flipvec[:] = v2.co # positive flipvec.x = -flipvec.x # negatve v2.co = v1.co = (flipvec + v1.co) * 0.5 # midway v2.co.x = -v2.co.x elif PREF_MODE == 2: # Left v2.co = v1.co v2.co.x = -v2.co.x elif PREF_MODE == 1: # Right v1.co = v2.co v1.co.x = -v1.co.x v1.sel = v2.sel = 0 #*Mirror Weights**********************************************************# if PREF_MIRROR_WEIGHTS: groupNames, vWeightDict = BPyMesh.meshWeight2Dict(me) mirror_pairs_l2r = [] # Stor a list of matches for these verts. mirror_pairs_r2l = [] # Stor a list of matches for these verts. # allign the negative with the positive. flipvec = Mathutils.Vector() len_neg_vts = float(len(neg_vts)) # Here we make a tuple to look through, if were middle well need to look through both. if PREF_MODE == 0: # Middle find_set = ((neg_vts, pos_vts, mirror_pairs_l2r), (pos_vts, neg_vts, mirror_pairs_r2l)) elif PREF_MODE == 1: # Left find_set = ((neg_vts, pos_vts, mirror_pairs_l2r), ) elif PREF_MODE == 2: # Right find_set = ((pos_vts, neg_vts, mirror_pairs_r2l), ) # Do a locational lookup again :/ - This isnt that good form but if we havnt mirrored weights well need to do it anyway. # The Difference with this is that we dont need to have 1:1 match for each vert- just get each vert to find another mirrored vert # and use its weight. # Use "find_set" so we can do a flipped search L>R and R>L without duplicate code. for vtls_A, vtls_B, pair_ls in find_set: for i1, vA in enumerate(vtls_A): best_len = 1 << 30 # BIGNUM best_idx = -1 # Find the BEST match vA_co = vA.co for i2, vB in enumerate(vtls_B): # Enforce edge users. if not PREF_EDGE_USERS or edge_users[i1] == edge_users[i2]: flipvec[:] = vB.co flipvec.x = -flipvec.x l = (vA_co - flipvec).length if l < best_len: best_len = l best_idx = i2 if best_idx != -1: pair_ls.append((vtls_A[i1].index, vtls_B[best_idx].index)) # neg, pos. # Now we can merge the weights if PREF_MODE == 0: # Middle newVWeightDict = [vWeightDict[i] for i in xrange(len(me.verts)) ] # Have empty dicts just incase for pair_ls in (mirror_pairs_l2r, mirror_pairs_r2l): if PREF_FLIP_NAMES: for i1, i2 in pair_ls: flipWeight, groupNames = BPyMesh.dictWeightFlipGroups( vWeightDict[i2], groupNames, PREF_CREATE_FLIP_NAMES) newVWeightDict[i1] = BPyMesh.dictWeightMerge( [vWeightDict[i1], flipWeight]) else: for i1, i2 in pair_ls: newVWeightDict[i1] = BPyMesh.dictWeightMerge( [vWeightDict[i1], vWeightDict[i2]]) vWeightDict = newVWeightDict elif PREF_MODE == 1: # Left if PREF_FLIP_NAMES: for i1, i2 in mirror_pairs_l2r: vWeightDict[i2], groupNames = BPyMesh.dictWeightFlipGroups( vWeightDict[i1], groupNames, PREF_CREATE_FLIP_NAMES) else: for i1, i2 in mirror_pairs_l2r: vWeightDict[i2] = vWeightDict[ i1] # Warning Multiple instances of the same data, its ok in this case but dont modify later. elif PREF_MODE == 2: # Right if PREF_FLIP_NAMES: for i1, i2 in mirror_pairs_r2l: vWeightDict[i2], groupNames = BPyMesh.dictWeightFlipGroups( vWeightDict[i1], groupNames, PREF_CREATE_FLIP_NAMES) else: for i1, i2 in mirror_pairs_r2l: vWeightDict[i2] = vWeightDict[i1] # Warning, ditto above BPyMesh.dict2MeshWeight(me, groupNames, vWeightDict) me.update()
def run_tests(self): """ The unit tests. """ self.tests_run = 0 self.tests_ok = 0 print "=== Starting tests. ===" # --- start of tests -------------------------------------------------- # ... ok infrastructure self.ok(1==1, "ok itself") # ... get() self.ok(get("mannequin").name=="mannequin", "get('mannequin')") self.ok(get("default action").name=="default action", " get('default action')") act1 = bpy.data.actions['step forward L to R'] self.ok(get(act1).name=='step forward L to R', ' get(action)') s1 = Step('step forward L to R') self.ok(get(s1).name=='step forward L to R', ' get(Step())') get_blank = True try: get("") except: get_blank = False self.ok(not get_blank, " get('') raises exception.") # ... blender_frame() ... Blender.Set('curframe', 1) self.ok(1 == blender_frame(), 'frame()') blender_frame(2) self.ok(2 == blender_frame(), ' frame(2)') # ... max_matrix() ... self.ok(max_matrix([[1,2,3],[-4,3,2]])==4, 'max_matrix()') # ... Step().bone_transform ... action_name = 'step back L to R' position = Mathutils.Vector(0.0, 4.91, 0.0) rotation = Mathutils.Quaternion(1,0,0,0) # no rotation transform = offset_and_rotation_to_matrix(position, rotation) motion = Step(action_name).bone_transform() # print " transform = '%s' " % str(transform) # print " motion = '%s' " % str(motion) max_diff = max_matrix(motion - transform) allowed_diff = 1.0e-3 self.ok( max_diff < allowed_diff, "Step('%s').bone_transform()" % action_name) step1 = Step('forward') self.ok(step1.action.name=='step forward L to R', " Step('forward')") step2 = Step('forward', 'L', mirror=True) self.ok(step2.action.name=='step back R to L', " step mirrored") self.ok(Step.flip('forward')=='back', " Step.flip()") # ... model ... man = Model("man") self.ok(man != None, "Model('man')") man.reset() self.ok(len(man.model.actionStrips)==1, " reset() actionstrips") self.ok(len(man.model.ipo.curves[0].bezierPoints)==1, " reset() ipo") frames = 12 action_name = 'step forward L to R' man.add_motion(action_name, frames) ## print " step : '%s'" % str(step_L_to_R) ## print " name : '%s'" % step_L_to_R.action.name ## print " strip1 : '%s'" % str(man.model.actionStrips[1]) ## print " name : '%s'" % str(man.model.actionStrips[1].action.name) # actionstrip objects are different ... that surprized me. # but name is OK; I guess it makes a copy somewhere. # self.ok(man.model.actionStrips[1] == step_L_to_R, " add_motion()") step_L_to_R = man.model.actionStrips[-1] self.ok(step_L_to_R.action.name == action_name, " add_motion()") actual_frames = step_L_to_R.stripEnd - step_L_to_R.stripStart self.ok(actual_frames == frames, " frame length") man.housekeeping() end0 = man.model.actionStrips[0].stripEnd self.ok(end0 == start_frame + frames, " housekeeping() strip0") action_name_2 = 'step side R to L' man.add_motion(action_name_2, frames) man.housekeeping() blender_frame(25) self.ok(abs(man.model.LocY - (-1.007)) < 0.01, ' add_location moves obj') ## ... # woman walking backwards ... used for manual testing if (False): woman = Model('woman') woman.reset() # woman makes 3 steps; let's see if object follows backward motion # ... looking at blender window, appears to work, # but RotZ jumps between +180 and -180, # and ipo points are left selected. steps = ('step back L to R', 'step shift R to L', 'step back L to R') for s in steps: woman.add_motion(s, frames) woman.housekeeping() # ... # couple walk sequence woman = Model('woman') seq = ['forward', 'side', 'shift', 'back', 'side', 'shift'] man.walk_sequence('L', seq, woman)
def vector(list): return Mathutils.Vector(*list)
def toBlenderVec(v): return bMath.Vector(v[0], v[1], v[2])
def rotToDirection(rot): euler = rotToEuler(rot) matrix = euler.toMatrix() restDirection = Mathutils.Vector(0, -1, 0) return tuple(restDirection * matrix)