def main(): # Gets the current scene, there can be many scenes in 1 blend file. sce = bpy.data.scenes.active # Get the active object, there can only ever be 1 # and the active object is always the editmode object. ob_act = sce.objects.active if not ob_act or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) Window.WaitCursor(1) me = ob_act.getData(mesh=1) # old NMesh api is default t = sys.time() # Run the mesh editing function my_mesh_util(me) # Restore editmode if it was enabled if is_editmode: Window.EditMode(1) # Timing the script is a good way to be aware on any speed hits when scripting print 'My Script finished in %.2f seconds' % (sys.time() - t) Window.WaitCursor(0)
def main(param_file): Window.WaitCursor(1) camera_parameters = load_camera(param_file) emode = int(Window.EditMode()) if emode: Window.EditMode(0) scene = Scene.GetCurrent() camera_data = create_camera(camera_parameters) scene.objects.new(camera_data) camera = Object.Get(camera_data.name) pose_camera(camera, camera_parameters) scene.objects.camera = camera context = scene.getRenderingContext() context.imageSizeX(int(camera_parameters.getroot().get('Width'))) context.imageSizeY(int(camera_parameters.getroot().get('Height'))) scene.update() Window.RedrawAll() if emode: Window.EditMode(1) Window.WaitCursor(0)
def main(): # get selected meshes obs = [ob for ob in self.context.selected_objects if ob.type == 'MESH'] # ask for weights to delete PREF_CUTOFF = Blender.Draw.Create(0.02) PREF_NBONES = Blender.Draw.Create(4) pup_block = [\ ('Weight Cutoff', PREF_CUTOFF, 0.001, 0.499, 'Vertices with weight less than this number will be deleted from the vertex group.'),\ ('Max Bones', PREF_NBONES, 1, 10, 'Also remove weakest influences so total number of bone influences is never larger than this number.'),\ ] if not Blender.Draw.PupBlock('Vertex Squash', pup_block): return # saves editmode state and exit editmode if it is enabled # (cannot make changes mesh data in editmode) is_editmode = Window.EditMode() Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # run script num_affected = 0 for ob in obs: me = ob.getData(mesh=1) # get Mesh, not NMesh num_affected += weight_squash(me, cutoff = PREF_CUTOFF.val, nbones = PREF_NBONES.val) print(f'Weight Squash finished in {(sys.time()-t):.2f} seconds') print(f'{num_affected} vertices removed from groups') Window.WaitCursor(0) if is_editmode: Window.EditMode(1)
def main(): # Gets the current scene, there can be many scenes in 1 blend file. sce = bpy.data.scenes.active # Get the active object, there can only ever be 1 # and the active object is always the editmode object. #ob_act = sce.objects.active ob_act = sce.objects.active if not ob_act or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return # Saves the editmode state and go's out of # editmode if its enabled, we cant make # changes to the mesh data while in editmode. is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) Window.WaitCursor(1) me = ob_act.getData(mesh=1) # old NMesh api is default t = sys.time() # Restore editmode if it was enabled if is_editmode: Window.EditMode(1) print 'ActionScript 3.0 Exporter Script finished in %.2f seconds' % ( sys.time() - t) Window.WaitCursor(0)
def main(): # Gets the current scene, there can be many scenes in 1 blend file. sce = bpy.data.scenes.active # Get the active object, there can only ever be 1 # and the active object is always the editmode object. ob_act = sce.objects.active if not ob_act or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return # Saves the editmode state and go's out of # editmode if its enabled, we cant make # changes to the mesh data while in editmode. is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # Run the mesh editing function report = find_unassigned_verts(ob_act) # Restore editmode if it was enabled if is_editmode: Window.EditMode(1) if report != "": report = report + "!!! I have selected all affected verts. Please lookup your mesh in edit mode !!!" text = "Report: %t|" + report +"|OK" Draw.PupMenu(text) Window.WaitCursor(0)
def read_main(filename): global counts counts = {'verts': 0, 'tris': 0} start = time.clock() file = open(filename, "r") print_boxed("----------------start-----------------") print 'Import Patch: ', filename editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode(0) # leave edit mode before getting the mesh lines = file.readlines() read_file(file, lines) Blender.Window.DrawProgressBar(1.0, '') # clear progressbar file.close() print "----------------end-----------------" end = time.clock() seconds = " in %.2f %s" % (end - start, "seconds") totals = "Verts: %i Tris: %i " % (counts['verts'], counts['tris']) print_boxed(totals) message = "Successfully imported " + Blender.sys.basename( filename) + seconds #meshtools.print_boxed(message) print_boxed(message)
def bevel(): """ The main function, which creates the bevel """ global me, NV, NV_ext, NE, NC, old_faces, old_dist ob = act_mesh_ob() if not ob: return Window.WaitCursor(1) # Change the Cursor t = Blender.sys.time() is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) me = ob.data NV = {} #PY23 NO SETS# NV_ext = set() NV_ext = {} NE = {} NC = {} old_faces = [] make_faces() make_edges() make_corners() clear_old() old_dist = dist.val print '\tbevel in %.6f sec' % (Blender.sys.time() - t) me.update(1) if is_editmode: Window.EditMode(1) Window.WaitCursor(0) Blender.Redraw()
def main(): # Gets the current scene, there can be many scenes in 1 blend file. sce = Scene.GetCurrent() # Get the active object, there can only ever be 1 # and the active object is always the editmode object. ob_act = sce.objects.active me = ob_act.getData(mesh=1) if not ob_act or ob_act.type != 'Mesh' or not me.faceUV: BPyMessages.Error_NoMeshUvActive() return # Saves the editmode state and go's out of # editmode if its enabled, we cant make # changes to the mesh data while in editmode. is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # Run the mesh editing function seams_from_islands(me) if is_editmode: Window.EditMode(1) # Timing the script is a good way to be aware on any speed hits when scripting print 'UV Seams from Islands finished in %.2f seconds' % (sys.time() - t) Window.WaitCursor(0)
def main(): # Gets the current scene, there can be many scenes in 1 blend file. sce = bpy.data.scenes.active # Get the active object, there can only ever be 1 # and the active object is always the editmode object. ob_act = sce.objects.active if not ob_act or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return # Saves the editmode state and go's out of # editmode if its enabled, we cant make # changes to the mesh data while in editmode. is_editmode = Window.EditMode() Window.EditMode(0) Window.WaitCursor(1) me = ob_act.getData(mesh=1) # old NMesh api is default t = sys.time() # Run the mesh editing function vgroup_invert(ob_act, me) # Timing the script is a good way to be aware on any speed hits when scripting print 'Invert VGroup in %.2f seconds' % (sys.time()-t) Window.WaitCursor(0) if is_editmode: Window.EditMode(1)
def main(arg): # get selected bones obs = [ob for ob in self.context.selected_objects if ob.type == 'ARMATURE'] if obs: boneitems = [(bonename, bone) for (bonename, bone) in list(obs[0].getPose().bones.items()) if bone.sel] else: boneitems = [] # exit if no bones selected if not boneitems: print("no bones selected in pose mode") Blender.Draw.PupMenu('ERROR%t|no bones selected in pose mode') return # ask for weights to delete PREF_PRIORITY = Blender.Draw.Create(30) pup_block = [\ ('Priority', PREF_PRIORITY, 0, 200, 'Bone priority.'),\ ] if not Blender.Draw.PupBlock('Set Bone Priority', pup_block): return # saves editmode state and exit editmode if it is enabled # (cannot make changes mesh data in editmode) is_editmode = Window.EditMode() Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # run script for bonename, bone in boneitems: # get priorty null constraint print(("setting priority %i on %s" % (PREF_PRIORITY.val, bonename))) priorityconstr = None for constr in bone.constraints: if constr.type == Blender.Constraint.Type.NULL \ and constr.name[:9] == "priority:": priorityconstr = constr break if not priorityconstr: priorityconstr = bone.constraints.append( Blender.Constraint.Type.NULL) priorityconstr.name = "priority:%i" % PREF_PRIORITY.val print('Set bone priority finished in %.2f seconds' % (sys.time() - t)) Window.WaitCursor(0) if is_editmode: Window.EditMode(1)
def setUpMesh(): """ Imports the mesh and connects it to the armature. """ print 'Setting up mesh...' t1= Blender.sys.time() # A little hack because import_obj.py doesnt provide the names of the imported objects objectsBefore = [ob for ob in scene.objects] import_obj.load_obj(MESHString) names = [ob.name for ob in scene.objects if ob not in objectsBefore] global mesh_name # The mesh created in makehuman is split up in parts, and these need to be # joined together before connecting it to the armature. Uses 'body' as the # main mesh part and connects all other parts to this. mesh_name = [s for s in names if 'body' in s][0] restmesh_name = [s for s in names if s is not mesh_name] armature = [ob for ob in scene.objects if ob.name == armature_name][0] armature.RotX = math.pi/2 bodymesh = [ob for ob in scene.objects if ob.name == mesh_name][0] restmesh = [ob for ob in scene.objects if ob.name in restmesh_name] bodymesh.join(restmesh) for ob in restmesh: scene.objects.unlink(ob) print 'done moving armature and joining mesh parts, it took %.4fs' % (Blender.sys.time()-t1) t2 = Blender.sys.time() editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode(0) # leave edit mode # Actual code for connection to armature. We still need to fix the remaining # verts though. This is done in fixVerts() armature.makeParent([bodymesh]) bodymesh.addVertexGroupsFromArmature(armature) mods = bodymesh.modifiers mod = mods.append(Modifier.Types.ARMATURE) mod[Modifier.Settings.OBJECT] = armature mod[Modifier.Settings.VGROUPS] = True mod[Modifier.Settings.ENVELOPES] = True print 'done adding mesh using bone heat, it took %.4fs' % (Blender.sys.time()-t2) if editmode: Window.EditMode(1) # optional, just being nice print 'Setting up mesh took %.4fs' % (Blender.sys.time()-t1)
def getparents(): global lookup, hierarchy, firstlevel, has_sim, armature, bones, theobject if Window.EditMode(): objects = [Scene.GetCurrent().objects.active] else: objects = Object.GetSelected() for theobject in objects: parent = theobject.parent if not parent or parent.getType() != 'Armature': Draw.PupMenu('Object "%s" is not a child of a bone.' % theobject.name) return None bonename = theobject.getParentBoneName() if not bonename: Draw.PupMenu( 'Object "%s" is the child of an armature. It should be the child of a bone.' % theobject.name) return None thisbones = parent.getData().bones if bonename in thisbones.keys(): bone = thisbones[bonename] else: Draw.PupMenu('Object "%s" has a deleted bone as its parent.' % theobject.name) return None if armature and (parent != armature or bone != bones[0]): Draw.PupMenu( 'You have selected multiple objects with different parents.') return None else: armature = parent bones = [bone] if not bones: return bone = bones[0] while bone.parent: bones.append(bone.parent) bone = bone.parent try: has_sim = False (lookup, hierarchy) = getDatarefs() firstlevel = [] for key in lookup: if lookup[key]: (path, n) = lookup[key] ref = path.split('/') if not ref[0] in firstlevel: firstlevel.append(ref[0]) if len(firstlevel) == 1: firstlevel = hierarchy['sim'].keys() has_sim = True firstlevel.sort(lambda x, y: -cmp(x.lower(), y.lower())) except IOError, e: Draw.PupMenu(str(e)) return None
def main(): THICK = Draw.Create(0.02) if not Draw.PupBlock('Cube wireframe', [\ ('Thick:', THICK, 0.0001, 10, 'Thickness of the skinned edges'),\ ]): return # Gets the current scene, there can be many scenes in 1 blend file. sce = bpy.data.scenes.active # Get the active object, there can only ever be 1 # and the active object is always the editmode object. ob_act = sce.objects.active if not ob_act or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return # Saves the editmode state and go's out of # editmode if its enabled, we cant make # changes to the mesh data while in editmode. is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) Window.WaitCursor(1) me = ob_act.getData(mesh=1) # old NMesh api is default t = sys.time() # Run the mesh editing function create_wired_mesh(me, THICK.val/2.0) ob_act.select(False) # Restore editmode if it was enabled if is_editmode: Window.EditMode(1) # Timing the script is a good way to be aware on any speed hits when scripting print 'My Script finished in %.2f seconds' % (sys.time()-t) Window.WaitCursor(0)
def CreateSegment(self, camera, nameSuffix, length): editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode(0) # leave edit mode before getting the mesh name = camera.getName() + nameSuffix # define vertices and faces for a pyramid coords = [[-length / 2, 0, 0], [length / 2, 0, 0]] edges = [[0, 1]] try: print "LOOKING FOR MESHDATA" me = Mesh.Get(name + 'mesh') print dir(me) except: print "COULD NOT FIND MESH" me = Mesh.New(name + 'mesh') #print "____ EDGES: ", len(me.edges), "____ VERTS: ", len(me.verts) me.verts = None me.edges.delete() #print "____ EDGES: ", len(me.edges), "____ VERTS: ", len(me.verts) me.verts.extend(coords) # add vertices to mesh me.edges.extend(edges) # add faces to the mesh (also adds edges) #print "____ EDGES: ", len(me.edges), "____ VERTS: ", len(me.verts) try: print "TRYING TO RECOVER OBJECT: " ob = Object.Get(name) print "++++++ OBJECT RECOVERED: " except: print "++++++ CREATING NEW OBJECT" ob = self.scene.objects.new(me, name) if editmode: Window.EditMode(1) # optional, just being nice return ob
def bevel_update(): """ Use NV to update the bevel """ global dist, old_dist if old_dist == None: # PupMenu('Error%t|Must bevel first.') return is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) fac = dist.val - old_dist old_dist = dist.val for old_v in NV.iterkeys(): for dir in NV[old_v].iterkeys(): for i in xrange(3): NV[old_v][dir].co[i] += fac * dir[i] me.update(1) if is_editmode: Window.EditMode(1) Blender.Redraw()
def my_callback( szFileName ): fScale = 0.1 print "\n\nImporting Into Blender ...\n" DrawProgressBar( 0.0, "Importing Into Blender ..." ) editmode = Window.EditMode() if editmode: # Leave Edit Mode Before Getting The Mesh Window.EditMode( 0 ) # scene = Blender.Scene.GetCurrent() v4Right = Blender.Mathutils.Vector( fScale, 0.0, 0.0, 0.0 ) v4Up = Blender.Mathutils.Vector( 0.0, fScale, 0.0, 0.0 ) v4At = Blender.Mathutils.Vector( 0.0, 0.0, fScale, 0.0 ) v4Position = Blender.Mathutils.Vector( 0.0, 0.0, 0.0, 1.0 ) matScale = Blender.Mathutils.Matrix( v4Right, v4Up, v4At, v4Position ) if -1 != szFileName.find( '.scene', -6 ): ximport = xImport( szFileName[ :-6 ] + ".x" ) ximport.Import( "BaseModel", matScale ) ximport = xImport( szFileName ) ximport.Import( "Mesh", matScale ) print "... Complete\n" elif -1 != szFileName.find( '.x', -2 ): ximport = xImport( szFileName ) ximport.Import( "Mesh", matScale ) print "... Complete\n" else: print "Not A Direct 3d .x File." DrawProgressBar( 1.0, "... Complete" ) if editmode: Window.EditMode( 1 )
def write_ui(filePath): Window.EditMode(0) slashPos = filePath.rfind('\\') directory = filePath[:slashPos + 1] filename = filePath[slashPos + 1:] if not filename.lower().endswith('.drk'): filename += '.drk' if not BPyMessages.Warning_SaveOver(filePath): return context = Scene.GetCurrent().getRenderingContext() orig_frame = Blender.Get('curframe') Blender.Set('curframe', context.startFrame()) write(directory, filename, Scene.GetCurrent().objects) Blender.Set('curframe', orig_frame) # Restore old active scene. Window.WaitCursor(0)
def main(): global USER_FILL_HOLES global USER_FILL_HOLES_QUALITY global USER_STRETCH_ASPECT global USER_ISLAND_MARGIN objects = bpy.data.scenes.active.objects # we can will tag them later. obList = [ob for ob in objects.context if ob.type == 'Mesh'] # Face select object may not be selected. ob = objects.active if ob and ob.sel == 0 and ob.type == 'Mesh': # Add to the list obList = [ob] del objects if not obList: Draw.PupMenu('error, no selected mesh objects') return # Create the variables. USER_PROJECTION_LIMIT = Draw.Create(66) USER_ONLY_SELECTED_FACES = Draw.Create(1) USER_SHARE_SPACE = Draw.Create(1) # Only for hole filling. USER_STRETCH_ASPECT = Draw.Create(1) # Only for hole filling. USER_ISLAND_MARGIN = Draw.Create(0.0) # Only for hole filling. USER_FILL_HOLES = Draw.Create(0) USER_FILL_HOLES_QUALITY = Draw.Create(50) # Only for hole filling. USER_VIEW_INIT = Draw.Create(0) # Only for hole filling. USER_AREA_WEIGHT = Draw.Create(1) # Only for hole filling. pup_block = [\ 'Projection',\ ('Angle Limit:', USER_PROJECTION_LIMIT, 1, 89, 'lower for more projection groups, higher for less distortion.'),\ ('Selected Faces Only', USER_ONLY_SELECTED_FACES, 'Use only selected faces from all selected meshes.'),\ ('Init from view', USER_VIEW_INIT, 'The first projection will be from the view vector.'),\ ('Area Weight', USER_AREA_WEIGHT, 'Weight projections vector by face area.'),\ '',\ '',\ '',\ 'UV Layout',\ ('Share Tex Space', USER_SHARE_SPACE, 'Objects Share texture space, map all objects into 1 uvmap.'),\ ('Stretch to bounds', USER_STRETCH_ASPECT, 'Stretch the final output to texture bounds.'),\ ('Island Margin:', USER_ISLAND_MARGIN, 0.0, 0.5, 'Margin to reduce bleed from adjacent islands.'),\ 'Fill in empty areas',\ ('Fill Holes', USER_FILL_HOLES, 'Fill in empty areas reduced texture waistage (slow).'),\ ('Fill Quality:', USER_FILL_HOLES_QUALITY, 1, 100, 'Depends on fill holes, how tightly to fill UV holes, (higher is slower)'),\ ] # Reuse variable if len(obList) == 1: ob = "Unwrap %i Selected Mesh" else: ob = "Unwrap %i Selected Meshes" # HACK, loop until mouse is lifted. ''' while Window.GetMouseButtons() != 0: sys.sleep(10) ''' if not Draw.PupBlock(ob % len(obList), pup_block): return del ob # Convert from being button types USER_PROJECTION_LIMIT = USER_PROJECTION_LIMIT.val USER_ONLY_SELECTED_FACES = USER_ONLY_SELECTED_FACES.val USER_SHARE_SPACE = USER_SHARE_SPACE.val USER_STRETCH_ASPECT = USER_STRETCH_ASPECT.val USER_ISLAND_MARGIN = USER_ISLAND_MARGIN.val USER_FILL_HOLES = USER_FILL_HOLES.val USER_FILL_HOLES_QUALITY = USER_FILL_HOLES_QUALITY.val USER_VIEW_INIT = USER_VIEW_INIT.val USER_AREA_WEIGHT = USER_AREA_WEIGHT.val USER_PROJECTION_LIMIT_CONVERTED = cos(USER_PROJECTION_LIMIT * DEG_TO_RAD) USER_PROJECTION_LIMIT_HALF_CONVERTED = cos( (USER_PROJECTION_LIMIT / 2) * DEG_TO_RAD) # Toggle Edit mode is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) # Assume face select mode! an annoying hack to toggle face select mode because Mesh dosent like faceSelectMode. if USER_SHARE_SPACE: # Sort by data name so we get consistant results try: obList.sort(key=lambda ob: ob.getData(name_only=1)) except: obList.sort(lambda ob1, ob2: cmp(ob1.getData(name_only=1), ob2.getData(name_only=1))) collected_islandList = [] Window.WaitCursor(1) time1 = sys.time() # Tag as False se we dont operate on teh same mesh twice. bpy.data.meshes.tag = False for ob in obList: me = ob.getData(mesh=1) if me.tag or me.lib: continue # Tag as used me.tag = True if not me.faceUV: # Mesh has no UV Coords, dont bother. me.faceUV = True if USER_ONLY_SELECTED_FACES: meshFaces = [thickface(f) for f in me.faces if f.sel] else: meshFaces = map(thickface, me.faces) if not meshFaces: continue Window.DrawProgressBar( 0.1, 'SmartProj UV Unwrapper, mapping "%s", %i faces.' % (me.name, len(meshFaces))) # ======= # Generate a projection list from face normals, this is ment to be smart :) # make a list of face props that are in sync with meshFaces # Make a Face List that is sorted by area. # meshFaces = [] # meshFaces.sort( lambda a, b: cmp(b.area , a.area) ) # Biggest first. try: meshFaces.sort(key=lambda a: -a.area) except: meshFaces.sort(lambda a, b: cmp(b.area, a.area)) # remove all zero area faces while meshFaces and meshFaces[-1].area <= SMALL_NUM: # Set their UV's to 0,0 for uv in meshFaces[-1].uv: uv.zero() meshFaces.pop() # Smallest first is slightly more efficient, but if the user cancels early then its better we work on the larger data. # Generate Projection Vecs # 0d is 1.0 # 180 IS -0.59846 # Initialize projectVecs if USER_VIEW_INIT: # Generate Projection projectVecs = [ Vector(Window.GetViewVector()) * ob.matrixWorld.copy().invert().rotationPart() ] # We add to this allong the way else: projectVecs = [] newProjectVec = meshFaces[0].no newProjectMeshFaces = [] # Popping stuffs it up. # Predent that the most unique angke is ages away to start the loop off mostUniqueAngle = -1.0 # This is popped tempMeshFaces = meshFaces[:] # This while only gathers projection vecs, faces are assigned later on. while 1: # If theres none there then start with the largest face # add all the faces that are close. for fIdx in xrange(len(tempMeshFaces) - 1, -1, -1): # Use half the angle limit so we dont overweight faces towards this # normal and hog all the faces. if newProjectVec.dot(tempMeshFaces[fIdx].no ) > USER_PROJECTION_LIMIT_HALF_CONVERTED: newProjectMeshFaces.append(tempMeshFaces.pop(fIdx)) # Add the average of all these faces normals as a projectionVec averageVec = Vector(0, 0, 0) if USER_AREA_WEIGHT: for fprop in newProjectMeshFaces: averageVec += (fprop.no * fprop.area) else: for fprop in newProjectMeshFaces: averageVec += fprop.no if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0: # Avoid NAN projectVecs.append(averageVec.normalize()) # Get the next vec! # Pick the face thats most different to all existing angles :) mostUniqueAngle = 1.0 # 1.0 is 0d. no difference. mostUniqueIndex = 0 # dummy for fIdx in xrange(len(tempMeshFaces) - 1, -1, -1): angleDifference = -1.0 # 180d difference. # Get the closest vec angle we are to. for p in projectVecs: temp_angle_diff = p.dot(tempMeshFaces[fIdx].no) if angleDifference < temp_angle_diff: angleDifference = temp_angle_diff if angleDifference < mostUniqueAngle: # We have a new most different angle mostUniqueIndex = fIdx mostUniqueAngle = angleDifference if mostUniqueAngle < USER_PROJECTION_LIMIT_CONVERTED: #print 'adding', mostUniqueAngle, USER_PROJECTION_LIMIT, len(newProjectMeshFaces) # Now weight the vector to all its faces, will give a more direct projection # if the face its self was not representive of the normal from surrounding faces. newProjectVec = tempMeshFaces[mostUniqueIndex].no newProjectMeshFaces = [tempMeshFaces.pop(mostUniqueIndex)] else: if len(projectVecs) >= 1: # Must have at least 2 projections break # If there are only zero area faces then its possible # there are no projectionVecs if not len(projectVecs): Draw.PupMenu( 'error, no projection vecs where generated, 0 area faces can cause this.' ) return faceProjectionGroupList = [[] for i in xrange(len(projectVecs))] # MAP and Arrange # We know there are 3 or 4 faces here for fIdx in xrange(len(meshFaces) - 1, -1, -1): fvec = meshFaces[fIdx].no i = len(projectVecs) # Initialize first bestAng = fvec.dot(projectVecs[0]) bestAngIdx = 0 # Cycle through the remaining, first alredy done while i - 1: i -= 1 newAng = fvec.dot(projectVecs[i]) if newAng > bestAng: # Reverse logic for dotvecs bestAng = newAng bestAngIdx = i # Store the area for later use. faceProjectionGroupList[bestAngIdx].append(meshFaces[fIdx]) # Cull faceProjectionGroupList, # Now faceProjectionGroupList is full of faces that face match the project Vecs list for i in xrange(len(projectVecs)): # Account for projectVecs having no faces. if not faceProjectionGroupList[i]: continue # Make a projection matrix from a unit length vector. MatProj = VectoMat(projectVecs[i]) # Get the faces UV's from the projected vertex. for f in faceProjectionGroupList[i]: f_uv = f.uv for j, v in enumerate(f.v): f_uv[j][:] = (MatProj * v.co)[:2] if USER_SHARE_SPACE: # Should we collect and pack later? islandList = getUvIslands(faceProjectionGroupList, me) collected_islandList.extend(islandList) else: # Should we pack the islands for this 1 object? islandList = getUvIslands(faceProjectionGroupList, me) packIslands(islandList) # update the mesh here if we need to. # We want to pack all in 1 go, so pack now if USER_SHARE_SPACE: Window.DrawProgressBar(0.9, "Box Packing for all objects...") packIslands(collected_islandList) print "Smart Projection time: %.2f" % (sys.time() - time1) # Window.DrawProgressBar(0.9, "Smart Projections done, time: %.2f sec." % (sys.time() - time1)) if is_editmode: Window.EditMode(1) Window.DrawProgressBar(1.0, "") Window.WaitCursor(0) Window.RedrawAll()
def main(): scn = bpy.data.scenes.active ob = scn.objects.active if not ob or ob.type != 'Mesh': return is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) mousedown_wait() # so the menu items clicking dosnt trigger the mouseclick Window.DrawProgressBar(0.0, '') Window.DrawProgressBar(0.1, '(1 of 3) Click on a face corner') # wait for a click mouse_buttons = Window.GetMouseButtons() while not mouse_buttons & LMB: sys.sleep(10) mouse_buttons = Window.GetMouseButtons() # Allow for RMB cancel if mouse_buttons & RMB: return while mouse_buttons & LMB: sys.sleep(10) mouse_buttons = Window.GetMouseButtons() Window.DrawProgressBar(0.2, '(2 of 3 ) Click confirms the U coords') mousedown_wait() obmat = ob.matrixWorld screen_x, screen_y = Window.GetMouseCoords() mouseInView, OriginA, DirectionA = mouseViewRay(screen_x, screen_y, obmat) if not mouseInView or not OriginA: return me = ob.getData(mesh=1) # Get the face under the mouse face_click, isect, side = BPyMesh.pickMeshRayFace(me, OriginA, DirectionA) if not face_click: return proj_z_component = face_click.no if not face_click: return # Find the face vertex thats closest to the mouse, # this vert will be used as the corner to map from. best_v = None best_length = 10000000 vi1 = None for i, v in enumerate(face_click.v): l = (v.co - isect).length if l < best_length: best_v = v best_length = l vi1 = i # now get the 2 edges in the face that connect to v # we can work it out fairly easerly if len(face_click) == 4: if vi1 == 0: vi2, vi3 = 3, 1 elif vi1 == 1: vi2, vi3 = 0, 2 elif vi1 == 2: vi2, vi3 = 1, 3 elif vi1 == 3: vi2, vi3 = 2, 0 else: if vi1 == 0: vi2, vi3 = 2, 1 elif vi1 == 1: vi2, vi3 = 0, 2 elif vi1 == 2: vi2, vi3 = 1, 0 face_corner_main = face_click.v[vi1].co face_corner_a = face_click.v[vi2].co face_corner_b = face_click.v[vi3].co line_a_len = (face_corner_a - face_corner_main).length line_b_len = (face_corner_b - face_corner_main).length orig_cursor = Window.GetCursorPos() Window.SetCursorPos(face_corner_main.x, face_corner_main.y, face_corner_main.z) SHIFT = Window.Qual.SHIFT MODE = 0 # firstclick, 1, secondclick mouse_buttons = Window.GetMouseButtons() project_mat = Matrix([0, 0, 0], [0, 0, 0], [0, 0, 0]) def get_face_coords(f): f_uv = f.uv return [(v.co - face_corner_main, f_uv[i]) for i, v in enumerate(f.v)] if me.faceUV == False: me.faceUV = True coords = [(co, uv) for f in me.faces if f.sel for co, uv in get_face_coords(f)] coords_orig = [uv.copy() for co, uv in coords] USE_MODIFIER = using_modifier(ob) while 1: if mouse_buttons & LMB: if MODE == 0: mousedown_wait() Window.DrawProgressBar( 0.8, '(3 of 3 ) Click confirms the V coords') MODE = 1 # second click # Se we cont continually set the length and get float error proj_y_component_orig = proj_y_component.copy() else: break elif mouse_buttons & RMB: # Restore old uvs for i, uv_orig in enumerate(coords_orig): coords[i][1][:] = uv_orig break mouse_buttons = Window.GetMouseButtons() screen_x, screen_y = Window.GetMouseCoords() mouseInView, OriginA, DirectionA = mouseViewRay( screen_x, screen_y, obmat) if not mouseInView: continue # Do a ray tri intersection, not clipped by the tri new_isect = Intersect(face_corner_main, face_corner_a, face_corner_b, DirectionA, OriginA, False) new_isect_alt = new_isect + DirectionA * 0.0001 # The distance from the mouse cursor ray vector to the edge line_isect_a_pair = LineIntersect(new_isect, new_isect_alt, face_corner_main, face_corner_a) line_isect_b_pair = LineIntersect(new_isect, new_isect_alt, face_corner_main, face_corner_b) # SHIFT to flip the axis. is_shift = Window.GetKeyQualifiers() & SHIFT if MODE == 0: line_dist_a = (line_isect_a_pair[0] - line_isect_a_pair[1]).length line_dist_b = (line_isect_b_pair[0] - line_isect_b_pair[1]).length if line_dist_a < line_dist_b: proj_x_component = face_corner_a - face_corner_main y_axis_length = line_b_len x_axis_length = (line_isect_a_pair[1] - face_corner_main).length else: proj_x_component = face_corner_b - face_corner_main y_axis_length = line_a_len x_axis_length = (line_isect_b_pair[1] - face_corner_main).length proj_y_component = proj_x_component.cross(proj_z_component) proj_y_component.length = 1 / y_axis_length proj_x_component.length = 1 / x_axis_length if is_shift: proj_x_component.negate() else: proj_y_component[:] = proj_y_component_orig if line_dist_a < line_dist_b: proj_y_component.length = 1 / (line_isect_a_pair[1] - new_isect).length else: proj_y_component.length = 1 / (line_isect_b_pair[1] - new_isect).length if is_shift: proj_y_component.negate() # Use the existing matrix to make a new 3x3 projecton matrix project_mat[0][:] = -proj_y_component project_mat[1][:] = -proj_x_component project_mat[2][:] = proj_z_component # Apply the projection matrix for proj_co, uv in coords: uv[:] = (project_mat * proj_co)[0:2] if USE_MODIFIER: me.update() Window.Redraw(Window.Types.VIEW3D) Window.SetCursorPos(*orig_cursor) if is_editmode: Window.EditMode(1) Window.RedrawAll()
def main(): scn = Scene.GetCurrent() act_ob = scn.objects.active if not act_ob or act_ob.type != 'Mesh': BPyMessages.Error_NoMeshActive() return act_me = act_ob.getData(mesh=1) if act_me.multires: BPyMessages.Error_NoMeshMultiresEdit() return act_group = act_me.activeGroup if not act_group: act_group = '' # Defaults PREF_REDUX = Draw.Create(0.5) PREF_BOUNDRY_WEIGHT = Draw.Create(5.0) PREF_REM_DOUBLES = Draw.Create(1) PREF_FACE_AREA_WEIGHT = Draw.Create(1.0) PREF_FACE_TRIANGULATE = Draw.Create(1) VGROUP_INF_ENABLE = Draw.Create(0) VGROUP_INF_REDUX = Draw.Create(act_group) VGROUP_INF_WEIGHT = Draw.Create(10.0) PREF_DO_UV = Draw.Create(1) PREF_DO_VCOL = Draw.Create(1) PREF_DO_WEIGHTS = Draw.Create(1) PREF_OTHER_SEL_OBS = Draw.Create(0) pup_block = [\ ('Poly Reduce:', PREF_REDUX, 0.05, 0.95, 'Scale the meshes poly count by this value.'),\ ('Boundry Weight:', PREF_BOUNDRY_WEIGHT, 0.0, 20.0, 'Weight boundry verts by this scale, 0.0 for no boundry weighting.'),\ ('Area Weight:', PREF_FACE_AREA_WEIGHT, 0.0, 20.0, 'Collapse edges effecting lower area faces first.'),\ ('Triangulate', PREF_FACE_TRIANGULATE, 'Convert quads to tris before reduction, for more choices of edges to collapse.'),\ '',\ ('VGroup Weighting', VGROUP_INF_ENABLE, 'Use a vertex group to influence the reduction, higher weights for higher quality '),\ ('vgroup name: ', VGROUP_INF_REDUX, 0, 32, 'The name of the vertex group to use for the weight map'),\ ('vgroup mult: ', VGROUP_INF_WEIGHT, 0.0, 100.0, 'How much to make the weight effect the reduction'),\ ('Other Selected Obs', PREF_OTHER_SEL_OBS, 'reduce other selected objects.'),\ '',\ '',\ '',\ ('UV Coords', PREF_DO_UV, 'Interpolate UV Coords.'),\ ('Vert Colors', PREF_DO_VCOL, 'Interpolate Vertex Colors'),\ ('Vert Weights', PREF_DO_WEIGHTS, 'Interpolate Vertex Weights'),\ ('Remove Doubles', PREF_REM_DOUBLES, 'Remove doubles before reducing to avoid boundry tearing.'),\ ] if not Draw.PupBlock("Poly Reducer", pup_block): return PREF_REDUX = PREF_REDUX.val PREF_BOUNDRY_WEIGHT = PREF_BOUNDRY_WEIGHT.val PREF_REM_DOUBLES = PREF_REM_DOUBLES.val PREF_FACE_AREA_WEIGHT = PREF_FACE_AREA_WEIGHT.val PREF_FACE_TRIANGULATE = PREF_FACE_TRIANGULATE.val VGROUP_INF_ENABLE = VGROUP_INF_ENABLE.val VGROUP_INF_WEIGHT = VGROUP_INF_WEIGHT.val if VGROUP_INF_ENABLE and VGROUP_INF_WEIGHT: VGROUP_INF_REDUX = VGROUP_INF_REDUX.val else: VGROUP_INF_WEIGHT = 0.0 VGROUP_INF_REDUX = None PREF_DO_UV = PREF_DO_UV.val PREF_DO_VCOL = PREF_DO_VCOL.val PREF_DO_WEIGHTS = PREF_DO_WEIGHTS.val PREF_OTHER_SEL_OBS = PREF_OTHER_SEL_OBS.val t = sys.time() is_editmode = Window.EditMode() # Exit Editmode. if is_editmode: Window.EditMode(0) Window.WaitCursor(1) print 'reducing:', act_ob.name, act_ob.getData(1) BPyMesh.redux(act_ob, PREF_REDUX, PREF_BOUNDRY_WEIGHT, PREF_REM_DOUBLES, PREF_FACE_AREA_WEIGHT, PREF_FACE_TRIANGULATE, PREF_DO_UV, PREF_DO_VCOL, PREF_DO_WEIGHTS, VGROUP_INF_REDUX, VGROUP_INF_WEIGHT) if PREF_OTHER_SEL_OBS: for ob in scn.objects.context: if ob.type == 'Mesh' and ob != act_ob: print 'reducing:', ob.name, ob.getData(1) BPyMesh.redux(ob, PREF_REDUX, PREF_BOUNDRY_WEIGHT, PREF_REM_DOUBLES, PREF_FACE_AREA_WEIGHT, PREF_FACE_TRIANGULATE, PREF_DO_UV, PREF_DO_VCOL, PREF_DO_WEIGHTS, VGROUP_INF_REDUX, VGROUP_INF_WEIGHT) Window.RedrawAll() if is_editmode: Window.EditMode(1) Window.WaitCursor(0) Window.RedrawAll() print 'Reduction done in %.6f sec.' % (sys.time() - t)
def main(arg): # get selected bones obs = [ob for ob in self.context.selected_objects if ob.type == 'ARMATURE'] if obs: boneitems = [(bonename, bone) for (bonename, bone) in list(obs[0].getPose().bones.items()) if bone.sel] else: boneitems = [] # exit if no bones selected if not boneitems: print("no bones selected in pose mode") Blender.Draw.PupMenu('ERROR%t|no bones selected in pose mode') return # ask for weights to delete PREF_BUFFER = Blender.Draw.Create("BonePose") pup_block = [\ ('Text Buffer', PREF_BUFFER, 0, 20, 'The text buffer where to store the bone poses.'),\ ] if not Blender.Draw.PupBlock('Save Bone Pose', pup_block): return # saves editmode state and exit editmode if it is enabled # (cannot make changes mesh data in editmode) is_editmode = Window.EditMode() Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # run script # open/clear text buffer try: posetxt = Blender.Text.Get(PREF_BUFFER.val) except NameError: posetxt = Blender.Text.New(PREF_BUFFER.val) posetxt.clear() for bonename, bone in boneitems: print(("saving pose of bone %s to %s" % (bonename, PREF_BUFFER.val))) matrix = bone.quat.toMatrix() matrix.resize4x4() matrix[3][0] = bone.loc[0] matrix[3][1] = bone.loc[1] matrix[3][2] = bone.loc[2] matrixtxt = '' for row in matrix: matrixtxt = '%s;%s,%s,%s,%s' % (matrixtxt, row[0], row[1], row[2], row[3]) # matrixtxt[1:] discards the first semi-colon posetxt.write("%s/%s\n" % (bonename, matrixtxt[1:])) # report finish and timing print('Save bone pose finished in %.2f seconds' % (sys.time() - t)) Window.WaitCursor(0) if is_editmode: Window.EditMode(1)
""" # # Copyright (c) 2004-2007 Jonathan Harris # # This code is licensed under version 2 of the GNU General Public License. # http://www.gnu.org/licenses/gpl-2.0.html # # See ReadMe-XPlane2Blender.html for usage. # import Blender from Blender import Draw, Window from XPlaneExport import OBJexport7, ExportError if Window.EditMode(): Window.EditMode(0) try: obj = None scene = Blender.Scene.GetCurrent() baseFileName = Blender.Get('filename') l = baseFileName.lower().rfind('.blend') if l == -1: raise ExportError('Save this .blend file first') baseFileName = baseFileName[:l] obj = OBJexport7(baseFileName + '.obj', __version__, False) obj.export(scene) except ExportError, e: for o in scene.objects: o.select(0) if e.objs: layers = []
def MakeMesh(image): """This takes an image as input and creates a mesh that is an extrusion of the mesh treated as a height field, with the zero value areas cut from the mesh. """ epsilon = 1.0 / 10000000.0 set_aspect_ratio = True scale_factor = 2.0 # scale the z value zscale = -1.2 xscale = 14.2 yscale = 14.2 xmax, ymax = image.getMaxXY() xmin, ymin = image.getMinXY() name = image.getName() depth = image.depth has_data = image.has_data xres, yres = image.getSize() inv_xres = 1.0 / float(xres) inv_yres = 1.0 / float(yres) # scale output mesh to have correct aspect ratio # to fit within a unit cube if set_aspect_ratio: aspect_ratio = float(xres) * inv_yres if aspect_ratio > 1.0: inv_xres *= 1.0 inv_yres *= 1.0 / aspect_ratio else: inv_xres *= aspect_ratio inv_yres *= 1.0 # scale the x and y together inv_xres *= scale_factor inv_yres *= scale_factor print("xres: %d, yres: %d, xinv %f, yinv %f" % (xres, yres, inv_xres, inv_yres)) print("depth: %d, has_data: %s, name: %s" % (depth, has_data, name)) coords = [] faces = [] zero_verts = {} # Create coordinate array, mark zero z vertices. count = 0 for y in range(yres): for x in range(xres): r, g, b, a = image.getPixelF(x, y) v = g + r * 256 + b * 256 * 256 if v > 125: v = 125 coords.append([(float(x) * inv_xres - 0.5) * xscale, (float(y) * inv_yres - 0.5) * yscale, v * zscale]) #if v < epsilon: if v < epsilon and False: print "Z: %d" % count, zero_verts[count] = 4 count += 1 # Create face list. Decrement zero verts. for y in range(yres - 1): for x in range(xres - 1): p1 = x + (y * xres) p2 = p1 + 1 # clockwise? p3 = x + (y + 1) * xres + 1 p4 = p3 - 1 if (coords[p1][2] < epsilon and coords[p2][2] < epsilon and coords[p3][2] < epsilon and coords[p4][2] < epsilon and False): zero_verts[p1] -= 1 zero_verts[p2] -= 1 zero_verts[p3] -= 1 zero_verts[p4] -= 1 else: faces.append([p1, p2, p3, p4]) # Adjust edges for unused zeros for y in range(yres): p1 = y * xres if zero_verts.has_key(p1): zero_verts[p1] -= 2 p1 = p1 + xres - 1 if zero_verts.has_key(p1): zero_verts[p1] -= 2 for x in range(xres): p1 = x if zero_verts.has_key(p1): zero_verts[p1] -= 2 p1 = x + xres * (yres - 1) if zero_verts.has_key(p1): zero_verts[p1] -= 2 p1 = 0 if zero_verts.has_key(p1): zero_verts[p1] += 1 p1 = xres - 1 if zero_verts.has_key(p1): zero_verts[p1] += 1 p1 = (yres - 1) * xres if zero_verts.has_key(p1): zero_verts[p1] += 1 p1 = p1 + xres - 1 if zero_verts.has_key(p1): zero_verts[p1] += 1 # Filter vert list and remove unused zeros new_verts = [] remap = {} new_count = 0 for v in range(len(coords)): is_zero = zero_verts.has_key(v) if not is_zero or zero_verts[v] > 0: remap[v] = new_count new_verts.append(coords[v]) new_count += 1 # Re Map old coords to new coords in face list new_faces = [] for f in faces: #print "Making face: %s" % f n1 = remap[f[0]] n2 = remap[f[1]] n3 = remap[f[2]] n4 = remap[f[3]] new_faces.append([n1, n2, n3, n4]) # Verbatim sample code from Blender.Mesh.__doc__ editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode(0) # leave edit mode before getting the mesh me = Mesh.New('myMesh') me.verts.extend(new_verts) # add vertices to mesh me.faces.extend(new_faces) # add faces to the mesh (also adds edges) #me.mesh.MFace.smooth(1) scn = Scene.GetCurrent() # link object to current scene ob = scn.objects.new(me, 'myObj') if editmode: Window.EditMode(1) # optional, just being nice # End Verbatim code return ob
def main(arg): # get armature and its bones obs = [ob for ob in self.context.selected_objects if ob.type == 'ARMATURE'] if obs: boneitems = [(bonename, bone) for (bonename, bone) in list(obs[0].getPose().bones.items())] else: boneitems = [] # exit if no bones selected if not boneitems: print("no armature selected") Blender.Draw.PupMenu('ERROR%t|no armature selected') return # ask for weights to delete PREF_BUFFER = Blender.Draw.Create("BonePose") pup_block = [\ ('Text Buffer: ', PREF_BUFFER, 0, 20, 'The text buffer to load the bone poses from.'),\ ] if not Blender.Draw.PupBlock('Load Bone Pose', pup_block): return # saves editmode state and exit editmode if it is enabled # (cannot make changes mesh data in editmode) is_editmode = Window.EditMode() Window.EditMode(0) Window.WaitCursor(1) t = sys.time() # run script # open text buffer try: posetxt = Blender.Text.Get(PREF_BUFFER.val) except NameError: Blender.Draw.PupMenu('ERROR%t|text buffer does not exist') return # reconstruct poses for matrixtxt in posetxt.asLines(): # skip empty lines if not matrixtxt: continue # reconstruct matrix from text bonename, matrixstr = matrixtxt.split('/') print(f"loading pose of bone {bonename:s} from {PREF_BUFFER.val:s}") try: matrix = mathutils.Matrix( *[[float(f) for f in row.split(',')] for row in matrixstr.split(';')]) except: Blender.Draw.PupMenu('ERROR%t|syntax error in buffer') return # save pose matrix for bonename2, bone in boneitems: if bonenamematch(bonename, bonename2): bone.quat = matrix.rotationPart().toQuat() bone.loc = matrix.translationPart() break else: print(f"WARNING: bone {bonename:s} not found in armature") # display the result obs[0].getPose().update() # report finish and timing print(f'Load bone pose finished in {(sys.time()-t):.2f} seconds') Window.WaitCursor(0) if is_editmode: Window.EditMode(1)
def main(): scn = Scene.GetCurrent() act_ob = scn.getActiveObject() if act_ob.getType() != 'Mesh': act_ob = None sel = [ ob for ob in Object.GetSelected() if ob.getType() == 'Mesh' if ob != act_ob ] if not sel and not act_ob: Draw.PupMenu('Error, select a mesh as your active object') return # Defaults PREF_EDITMESH_ONLY = Draw.Create(1) PREF_MIRROR_LOCATION = Draw.Create(1) PREF_XMID_SNAP = Draw.Create(1) PREF_MAX_DIST = Draw.Create(0.02) PREF_XZERO_THRESH = Draw.Create(0.002) #PREF_MODE= Draw.Create(0) # THIS IS TOOO CONFUSING, HAVE 2 BUTTONS AND MAKE THE MODE FROM THEM. PREF_MODE_L2R = Draw.Create(1) PREF_MODE_R2L = Draw.Create(0) PREF_SEL_ONLY = Draw.Create(1) PREF_EDGE_USERS = Draw.Create(0) # Weights PREF_MIRROR_WEIGHTS = Draw.Create(0) PREF_FLIP_NAMES = Draw.Create(1) PREF_CREATE_FLIP_NAMES = Draw.Create(1) pup_block = [\ ('EditMesh Only', PREF_EDITMESH_ONLY, 'If disabled, will mirror all selected meshes.'),\ 'Left (-), Right (+)',\ ('Left > Right', PREF_MODE_L2R, 'Copy from the Left to Right of the mesh. Enable Both for a mid loc/weight.'),\ ('Right > Left', PREF_MODE_R2L, 'Copy from the Right to Left of the mesh. Enable Both for a mid loc/weight.'),\ '',\ ('MaxDist:', PREF_MAX_DIST, 0.0, 1.0, 'Generate interpolated verts so closer vert weights can be copied.'),\ ('XZero limit:', PREF_XZERO_THRESH, 0.0, 1.0, 'Mirror verts above this distance from the middle, else lock to X/zero.'),\ ('Sel Verts Only', PREF_SEL_ONLY, 'Only mirror selected verts. Else try and mirror all'),\ ('Edge Users', PREF_EDGE_USERS, 'Only match up verts that have the same number of edge users.'),\ 'Location Prefs',\ ('Mirror Location', PREF_MIRROR_LOCATION, 'Mirror vertex locations.'),\ ('XMidSnap Verts', PREF_XMID_SNAP, 'Snap middle verts to X Zero (uses XZero limit)'),\ 'Weight Prefs',\ ('Mirror Weights', PREF_MIRROR_WEIGHTS, 'Mirror vertex locations.'),\ ('Flip Groups', PREF_FLIP_NAMES, 'Mirror flip names.'),\ ('New Flip Groups', PREF_CREATE_FLIP_NAMES, 'Make new groups for flipped names.'),\ ] if not Draw.PupBlock("X Mirror mesh tool", pup_block): return # WORK OUT THE MODE 0 # PREF_MODE, 0:middle, 1: Left. 2:Right. PREF_MODE_R2L = PREF_MODE_R2L.val PREF_MODE_L2R = PREF_MODE_L2R.val if PREF_MODE_R2L and PREF_MODE_L2R: PREF_MODE = 0 # Middle elif not PREF_MODE_R2L and PREF_MODE_L2R: PREF_MODE = 1 # Left to Right elif PREF_MODE_R2L and not PREF_MODE_L2R: PREF_MODE = 2 # Right to Left else: # Neither Selected. Do middle anyway PREF_MODE = 0 PREF_EDITMESH_ONLY = PREF_EDITMESH_ONLY.val PREF_MIRROR_LOCATION = PREF_MIRROR_LOCATION.val PREF_XMID_SNAP = PREF_XMID_SNAP.val PREF_MAX_DIST = PREF_MAX_DIST.val PREF_XZERO_THRESH = PREF_XZERO_THRESH.val PREF_SEL_ONLY = PREF_SEL_ONLY.val PREF_EDGE_USERS = PREF_EDGE_USERS.val # weights PREF_MIRROR_WEIGHTS = PREF_MIRROR_WEIGHTS.val PREF_FLIP_NAMES = PREF_FLIP_NAMES.val PREF_CREATE_FLIP_NAMES = PREF_CREATE_FLIP_NAMES.val t = sys.time() is_editmode = Window.EditMode() # Exit Editmode. if is_editmode: Window.EditMode(0) Mesh.Mode(Mesh.SelectModes['VERTEX']) Window.WaitCursor(1) if act_ob: mesh_mirror(act_ob.getData(mesh=1), 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) if (not PREF_EDITMESH_ONLY) and sel: for ob in sel: mesh_mirror(ob.getData(mesh=1), 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) if is_editmode: Window.EditMode(1) Window.WaitCursor(0) Window.DrawProgressBar(1.0, '') Window.RedrawAll() print 'Mirror done in %.6f sec.' % (sys.time() - t)
def write_ui(filename): if not filename.lower().endswith('.obj'): filename += '.obj' if not BPyMessages.Warning_SaveOver(filename): return global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\ EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\ EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\ EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\ EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER,\ EXPORT_POLYGROUPS, EXPORT_CURVE_AS_NURBS EXPORT_APPLY_MODIFIERS = Draw.Create(0) EXPORT_ROTX90 = Draw.Create(1) EXPORT_TRI = Draw.Create(0) EXPORT_EDGES = Draw.Create(1) EXPORT_NORMALS = Draw.Create(0) EXPORT_NORMALS_HQ = Draw.Create(0) EXPORT_UV = Draw.Create(1) EXPORT_MTL = Draw.Create(1) EXPORT_SEL_ONLY = Draw.Create(1) EXPORT_ALL_SCENES = Draw.Create(0) EXPORT_ANIMATION = Draw.Create(0) EXPORT_COPY_IMAGES = Draw.Create(0) EXPORT_BLEN_OBS = Draw.Create(0) EXPORT_GROUP_BY_OB = Draw.Create(0) EXPORT_GROUP_BY_MAT = Draw.Create(0) EXPORT_KEEP_VERT_ORDER = Draw.Create(1) EXPORT_POLYGROUPS = Draw.Create(0) EXPORT_CURVE_AS_NURBS = Draw.Create(1) # Old UI ''' # removed too many options are bad! # Get USER Options pup_block = [\ ('Context...'),\ ('Selection Only', EXPORT_SEL_ONLY, 'Only export objects in visible selection. Else export whole scene.'),\ ('All Scenes', EXPORT_ALL_SCENES, 'Each scene as a separate OBJ file.'),\ ('Animation', EXPORT_ANIMATION, 'Each frame as a numbered OBJ file.'),\ ('Object Prefs...'),\ ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\ ('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\ ('Keep Vert Order', EXPORT_KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\ ('Extra Data...'),\ ('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\ ('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\ ('High Quality Normals', EXPORT_NORMALS_HQ, 'Calculate high quality normals for rendering.'),\ ('UVs', EXPORT_UV, 'Export texface UV coords.'),\ ('Materials', EXPORT_MTL, 'Write a separate MTL file with the OBJ.'),\ ('Copy Images', EXPORT_COPY_IMAGES, 'Copy image files to the export directory, never overwrite.'),\ ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\ ('Grouping...'),\ ('Objects', EXPORT_BLEN_OBS, 'Export blender objects as "OBJ objects".'),\ ('Object Groups', EXPORT_GROUP_BY_OB, 'Export blender objects as "OBJ Groups".'),\ ('Material Groups', EXPORT_GROUP_BY_MAT, 'Group by materials.'),\ ] if not Draw.PupBlock('Export...', pup_block): return ''' # BEGIN ALTERNATIVE UI ******************* if True: EVENT_NONE = 0 EVENT_EXIT = 1 EVENT_REDRAW = 2 EVENT_EXPORT = 3 GLOBALS = {} GLOBALS['EVENT'] = EVENT_REDRAW #GLOBALS['MOUSE'] = Window.GetMouseCoords() GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()] def obj_ui_set_event(e,v): GLOBALS['EVENT'] = e def do_split(e,v): global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER, EXPORT_POLYGROUPS if EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val: EXPORT_KEEP_VERT_ORDER.val = 0 else: EXPORT_KEEP_VERT_ORDER.val = 1 def do_vertorder(e,v): global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER if EXPORT_KEEP_VERT_ORDER.val: EXPORT_BLEN_OBS.val = EXPORT_GROUP_BY_OB.val = EXPORT_GROUP_BY_MAT.val = EXPORT_APPLY_MODIFIERS.val = 0 else: if not (EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val): EXPORT_KEEP_VERT_ORDER.val = 1 def do_help(e,v): url = __url__[0] print 'Trying to open web browser with documentation at this address...' print '\t' + url try: import webbrowser webbrowser.open(url) except: print '...could not open a browser window.' def obj_ui(): ui_x, ui_y = GLOBALS['MOUSE'] # Center based on overall pup size ui_x -= 165 ui_y -= 140 global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\ EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\ EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\ EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\ EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER,\ EXPORT_POLYGROUPS, EXPORT_CURVE_AS_NURBS Draw.Label('Context...', ui_x+9, ui_y+239, 220, 20) Draw.BeginAlign() EXPORT_SEL_ONLY = Draw.Toggle('Selection Only', EVENT_NONE, ui_x+9, ui_y+219, 110, 20, EXPORT_SEL_ONLY.val, 'Only export objects in visible selection. Else export whole scene.') EXPORT_ALL_SCENES = Draw.Toggle('All Scenes', EVENT_NONE, ui_x+119, ui_y+219, 110, 20, EXPORT_ALL_SCENES.val, 'Each scene as a separate OBJ file.') EXPORT_ANIMATION = Draw.Toggle('Animation', EVENT_NONE, ui_x+229, ui_y+219, 110, 20, EXPORT_ANIMATION.val, 'Each frame as a numbered OBJ file.') Draw.EndAlign() Draw.Label('Output Options...', ui_x+9, ui_y+189, 220, 20) Draw.BeginAlign() EXPORT_APPLY_MODIFIERS = Draw.Toggle('Apply Modifiers', EVENT_REDRAW, ui_x+9, ui_y+170, 110, 20, EXPORT_APPLY_MODIFIERS.val, 'Use transformed mesh data from each object. May break vert order for morph targets.', do_split) EXPORT_ROTX90 = Draw.Toggle('Rotate X90', EVENT_NONE, ui_x+119, ui_y+170, 110, 20, EXPORT_ROTX90.val, 'Rotate on export so Blenders UP is translated into OBJs UP') EXPORT_COPY_IMAGES = Draw.Toggle('Copy Images', EVENT_NONE, ui_x+229, ui_y+170, 110, 20, EXPORT_COPY_IMAGES.val, 'Copy image files to the export directory, never overwrite.') Draw.EndAlign() Draw.Label('Export...', ui_x+9, ui_y+139, 220, 20) Draw.BeginAlign() EXPORT_EDGES = Draw.Toggle('Edges', EVENT_NONE, ui_x+9, ui_y+120, 50, 20, EXPORT_EDGES.val, 'Edges not connected to faces.') EXPORT_TRI = Draw.Toggle('Triangulate', EVENT_NONE, ui_x+59, ui_y+120, 70, 20, EXPORT_TRI.val, 'Triangulate quads.') Draw.EndAlign() Draw.BeginAlign() EXPORT_MTL = Draw.Toggle('Materials', EVENT_NONE, ui_x+139, ui_y+120, 70, 20, EXPORT_MTL.val, 'Write a separate MTL file with the OBJ.') EXPORT_UV = Draw.Toggle('UVs', EVENT_NONE, ui_x+209, ui_y+120, 31, 20, EXPORT_UV.val, 'Export texface UV coords.') Draw.EndAlign() Draw.BeginAlign() EXPORT_NORMALS = Draw.Toggle('Normals', EVENT_NONE, ui_x+250, ui_y+120, 59, 20, EXPORT_NORMALS.val, 'Export vertex normal data (Ignored on import).') EXPORT_NORMALS_HQ = Draw.Toggle('HQ', EVENT_NONE, ui_x+309, ui_y+120, 31, 20, EXPORT_NORMALS_HQ.val, 'Calculate high quality normals for rendering.') Draw.EndAlign() EXPORT_POLYGROUPS = Draw.Toggle('Polygroups', EVENT_REDRAW, ui_x+9, ui_y+95, 120, 20, EXPORT_POLYGROUPS.val, 'Export vertex groups as OBJ groups (one group per face approximation).') EXPORT_CURVE_AS_NURBS = Draw.Toggle('Nurbs', EVENT_NONE, ui_x+139, ui_y+95, 100, 20, EXPORT_CURVE_AS_NURBS.val, 'Export 3D nurbs curves and polylines as OBJ curves, (bezier not supported).') Draw.Label('Blender Objects as OBJ:', ui_x+9, ui_y+59, 220, 20) Draw.BeginAlign() EXPORT_BLEN_OBS = Draw.Toggle('Objects', EVENT_REDRAW, ui_x+9, ui_y+39, 60, 20, EXPORT_BLEN_OBS.val, 'Export blender objects as "OBJ objects".', do_split) EXPORT_GROUP_BY_OB = Draw.Toggle('Groups', EVENT_REDRAW, ui_x+69, ui_y+39, 60, 20, EXPORT_GROUP_BY_OB.val, 'Export blender objects as "OBJ Groups".', do_split) EXPORT_GROUP_BY_MAT = Draw.Toggle('Material Groups', EVENT_REDRAW, ui_x+129, ui_y+39, 100, 20, EXPORT_GROUP_BY_MAT.val, 'Group by materials.', do_split) Draw.EndAlign() EXPORT_KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+239, ui_y+39, 100, 20, EXPORT_KEEP_VERT_ORDER.val, 'Keep vert and face order, disables some other options. Use for morph targets.', do_vertorder) Draw.BeginAlign() Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 20, 'Load the wiki page for this script', do_help) Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 20, '', obj_ui_set_event) Draw.PushButton('Export', EVENT_EXPORT, ui_x+229, ui_y+9, 110, 20, 'Export with these settings', obj_ui_set_event) Draw.EndAlign() # hack so the toggle buttons redraw. this is not nice at all while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_EXPORT): Draw.UIBlock(obj_ui, 0) if GLOBALS['EVENT'] != EVENT_EXPORT: return # END ALTERNATIVE UI ********************* if EXPORT_KEEP_VERT_ORDER.val: EXPORT_BLEN_OBS.val = False EXPORT_GROUP_BY_OB.val = False EXPORT_GROUP_BY_MAT.val = False EXPORT_APPLY_MODIFIERS.val = False Window.EditMode(0) Window.WaitCursor(1) EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val EXPORT_ROTX90 = EXPORT_ROTX90.val EXPORT_TRI = EXPORT_TRI.val EXPORT_EDGES = EXPORT_EDGES.val EXPORT_NORMALS = EXPORT_NORMALS.val EXPORT_NORMALS_HQ = EXPORT_NORMALS_HQ.val EXPORT_UV = EXPORT_UV.val EXPORT_MTL = EXPORT_MTL.val EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.val EXPORT_ALL_SCENES = EXPORT_ALL_SCENES.val EXPORT_ANIMATION = EXPORT_ANIMATION.val EXPORT_COPY_IMAGES = EXPORT_COPY_IMAGES.val EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val EXPORT_KEEP_VERT_ORDER = EXPORT_KEEP_VERT_ORDER.val EXPORT_POLYGROUPS = EXPORT_POLYGROUPS.val EXPORT_CURVE_AS_NURBS = EXPORT_CURVE_AS_NURBS.val base_name, ext = splitExt(filename) context_name = [base_name, '', '', ext] # basename, scene_name, framenumber, extension # Use the options to export the data using write() # def write(filename, objects, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False, EXPORT_APPLY_MODIFIERS=True): orig_scene = Scene.GetCurrent() if EXPORT_ALL_SCENES: export_scenes = Scene.Get() else: export_scenes = [orig_scene] # Export all scenes. for scn in export_scenes: scn.makeCurrent() # If alredy current, this is not slow. context = scn.getRenderingContext() orig_frame = Blender.Get('curframe') if EXPORT_ALL_SCENES: # Add scene name into the context_name context_name[1] = '_%s' % BPySys.cleanName(scn.name) # WARNING, its possible that this could cause a collision. we could fix if were feeling parranoied. # Export an animation? if EXPORT_ANIMATION: scene_frames = xrange(context.startFrame(), context.endFrame()+1) # up to and including the end frame. else: scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. for frame in scene_frames: if EXPORT_ANIMATION: # Add frame to the filename. context_name[2] = '_%.6d' % frame Blender.Set('curframe', frame) if EXPORT_SEL_ONLY: export_objects = scn.objects.context else: export_objects = scn.objects full_path= ''.join(context_name) # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad. # EXPORT THE FILE. write(full_path, export_objects,\ EXPORT_TRI, EXPORT_EDGES, EXPORT_NORMALS,\ EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\ EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\ EXPORT_ROTX90, EXPORT_BLEN_OBS,\ EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER,\ EXPORT_POLYGROUPS, EXPORT_CURVE_AS_NURBS) Blender.Set('curframe', orig_frame) # Restore old active scene. orig_scene.makeCurrent() Window.WaitCursor(0)
def write_ui(filename): if not filename.lower().endswith('.obj'): filename += '.obj' if not BPyMessages.Warning_SaveOver(filename): return EXPORT_APPLY_MODIFIERS = Draw.Create(1) EXPORT_ROTX90 = Draw.Create(1) EXPORT_TRI = Draw.Create(1) EXPORT_EDGES = Draw.Create(1) EXPORT_NORMALS = Draw.Create(1) EXPORT_NORMALS_HQ = Draw.Create(1) EXPORT_UV = Draw.Create(1) EXPORT_MTL = Draw.Create(1) EXPORT_SEL_ONLY = Draw.Create(1) EXPORT_ALL_SCENES = Draw.Create(0) EXPORT_ANIMATION = Draw.Create(0) EXPORT_COPY_IMAGES = Draw.Create(0) EXPORT_BLEN_OBS = Draw.Create(1) EXPORT_GROUP_BY_OB = Draw.Create(1) EXPORT_GROUP_BY_MAT = Draw.Create(0) EXPORT_MORPH_TARGET = Draw.Create(0) EXPORT_VERTEX_GROUPS = Draw.Create(1) EXPORT_ARMATURE = Draw.Create(1) # removed too many options are bad! # Get USER Options pup_block = [\ ('Context...'),\ ('Selection Only', EXPORT_SEL_ONLY, 'Only export objects in visible selection. Else export whole scene.'),\ ('All Scenes', EXPORT_ALL_SCENES, 'Each scene as a separate OBJ file.'),\ ('Animation', EXPORT_ANIMATION, 'Each frame as a numbered OBJ file.'),\ ('Object Prefs...'),\ ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\ ('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\ ('Morph Target', EXPORT_MORPH_TARGET, 'Keep vert and face order, disables some other options.'),\ ('Extra Data...'),\ ('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\ ('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\ ('High Quality Normals', EXPORT_NORMALS_HQ, 'Calculate high quality normals for rendering.'),\ ('UVs', EXPORT_UV, 'Export texface UV coords.'),\ ('Materials', EXPORT_MTL, 'Write a separate MTL file with the OBJ.'),\ ('Copy Images', EXPORT_COPY_IMAGES, 'Copy image files to the export directory, never overwrite.'),\ ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\ ('Grouping...'),\ ('Objects', EXPORT_BLEN_OBS, 'Export blender objects as "OBJ objects".'),\ ('Object Groups', EXPORT_GROUP_BY_OB, 'Export blender objects as "OBJ Groups".'),\ ('Material Groups', EXPORT_GROUP_BY_MAT, 'Group by materials.'),\ ('Vertex Groups', EXPORT_VERTEX_GROUPS, 'Add influences & Weights.'),\ ('Armature', EXPORT_ARMATURE, 'Export Armature'),\ ] if not Draw.PupBlock('Export...', pup_block): return if EXPORT_MORPH_TARGET.val: EXPORT_BLEN_OBS.val = False EXPORT_GROUP_BY_OB.val = False EXPORT_GROUP_BY_MAT.val = False EXPORT_GROUP_BY_MAT.val = False EXPORT_APPLY_MODIFIERS.val = False Window.EditMode(0) Window.WaitCursor(1) EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val EXPORT_ROTX90 = EXPORT_ROTX90.val EXPORT_TRI = EXPORT_TRI.val EXPORT_EDGES = EXPORT_EDGES.val EXPORT_NORMALS = EXPORT_NORMALS.val EXPORT_NORMALS_HQ = EXPORT_NORMALS_HQ.val EXPORT_UV = EXPORT_UV.val EXPORT_MTL = EXPORT_MTL.val EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.val EXPORT_ALL_SCENES = EXPORT_ALL_SCENES.val EXPORT_ANIMATION = EXPORT_ANIMATION.val EXPORT_COPY_IMAGES = EXPORT_COPY_IMAGES.val EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val EXPORT_MORPH_TARGET = EXPORT_MORPH_TARGET.val EXPORT_VERTEX_GROUPS = EXPORT_VERTEX_GROUPS.val EXPORT_ARMATURE = EXPORT_ARMATURE.val base_name, ext = splitExt(filename) context_name = [base_name, '', '', ext] # basename, scene_name, framenumber, extension # Use the options to export the data using write() # def write(filename, objects, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False, EXPORT_APPLY_MODIFIERS=True): orig_scene = Scene.GetCurrent() if EXPORT_ALL_SCENES: export_scenes = Scene.Get() else: export_scenes = [orig_scene] # Export all scenes. for scn in export_scenes: scn.makeCurrent() # If alredy current, this is not slow. context = scn.getRenderingContext() orig_frame = Blender.Get('curframe') if EXPORT_ALL_SCENES: # Add scene name into the context_name context_name[1] = '_%s' % BPySys.cleanName(scn.name) # WARNING, its possible that this could cause a collision. we could fix if were feeling parranoied. # Export an animation? if EXPORT_ANIMATION: scene_frames = xrange(context.startFrame(), context.endFrame()+1) # up to and including the end frame. else: scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. for frame in scene_frames: if EXPORT_ANIMATION: # Add frame to the filename. context_name[2] = '_%.6d' % frame Blender.Set('curframe', frame) if EXPORT_SEL_ONLY: export_objects = scn.objects.context else: export_objects = scn.objects full_path= ''.join(context_name) # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad. # EXPORT THE FILE. write(full_path, export_objects,\ EXPORT_TRI, EXPORT_EDGES, EXPORT_NORMALS,\ EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\ EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\ EXPORT_ROTX90, EXPORT_BLEN_OBS,\ EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_MORPH_TARGET, EXPORT_ARMATURE) Blender.Set('curframe', orig_frame) # Restore old active scene. orig_scene.makeCurrent() Window.WaitCursor(0)
def ExportToC(file_name): file = open(file_name, "w") scene = Blender.Scene.GetCurrent() meshes = [] for ob in scene.objects: obtype = ob.type if obtype == "Mesh": meshes.append(ob) #Sort meshes alphabetically meshNames = [] sortedMeshNames = [] for mesh in meshes: meshNames.append(mesh.getName()) sortedMeshNames.append(mesh.getName()) sortedMeshNames.sort() sortedMeshes = [] for sortedMeshName in sortedMeshNames: sortedMeshes.append(meshes[meshNames.index(sortedMeshName)]) meshes = sortedMeshes global meshCnt global meshPointDataCnt #change to object mode in_editmode = Window.EditMode() if in_editmode: Window.EditMode(0) contentName = Blender.sys.splitext(Blender.sys.basename(file_name))[0] #Print the transformation data to file meshCnt = 0 file.write("//transformation data\n") file.write("//x, y, z, rotation\n") file.write("//x, y, z, location\n") file.write("//x, y, z, size\n") file.write("//y, z, unit circle coordinates for x rotation\n") file.write("//x, z, unit circle coordinates for y rotation\n") file.write("//x, y, unit circle coordinates for z rotation\n") file.write("//bounds radius,\n") file.write("float %s_TRANS[%i]={\n" % (contentName, len(meshes) * 16)) for mesh in meshes: file.write("//data block %i\n" % (meshCnt)) file.write("%f, %f, %f,\n" % (mesh.rot[0]*180.0/math.pi, mesh.rot[1]*180.0/math.pi, mesh.rot[2]*180.0/math.pi)) file.write("%f, %f, %f,\n" % (mesh.loc[0], mesh.loc[1], mesh.loc[2])) file.write("%f, %f, %f,\n" % (mesh.size[0], mesh.size[1], mesh.size[2])) file.write("%f, %f,\n" % (math.cos(mesh.rot[0]), math.sin(mesh.rot[0]))) file.write("%f, %f,\n" % (math.cos(mesh.rot[1]), math.sin(mesh.rot[1]))) file.write("%f, %f,\n" % (math.cos(mesh.rot[2]), math.sin(mesh.rot[2]))) xyLgth = math.sqrt(mesh.size[0]*mesh.size[0]+mesh.size[1]*mesh.size[1]) file.write("%f,\n" % (math.sqrt(xyLgth*xyLgth+mesh.size[2]*mesh.size[2]))) meshCnt += 1 file.write("};\n\n") #Get the number of corners of each polygon polyCornerCnt = 0 for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: polyCornerCnt += 3 elif len(face.v) == 4: polyCornerCnt += 4 #Count the number of quads quadCount = 0 for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 4: quadCount += 1 #Count the number of trigon trigonCount = 0 for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: trigonCount += 1 #Print the point data to file file.write("//point data\n") file.write("float %s_POINT[%i]={\n" % (contentName, polyCornerCnt * 3)) meshCnt = 0 for mesh in meshes: writeVertices(file, mesh) meshCnt += 1 file.write("};\n\n") #Print the quad data to file meshCnt = 0 meshPointDataCnt = 0 file.write("//quad data\n") file.write("short %s_QUAD[%i]={\n" % (contentName, quadCount * 4)) for mesh in meshes: WriteQuadFaces(file, mesh) meshCnt += 1 file.write("};\n\n") #Print the trigon data to file meshCnt = 0 meshPointDataCnt = 0 file.write("//trigon data\n") file.write("short %s_TRI[%i]={\n" % (contentName, trigonCount * 3)) for mesh in meshes: WriteTriFaces(file, mesh) meshCnt += 1 file.write("};\n\n") #Print the vertex color data to file file.write("//vertex color data\n") file.write("char %s_VCOLOR[%i]={\n" % (contentName, quadCount*4*4 + trigonCount*3*4)) meshCnt = 0 for mesh in meshes: WriteColors(file, mesh) meshCnt += 1 file.write("};\n\n") #Print the texture coordinate data to file file.write("//texture coordinate data\n") file.write("float %s_TEXCOORD[%i]={\n" % (contentName, quadCount*4*2 + trigonCount*3*2)) meshCnt = 0 for mesh in meshes: WriteTexCoords(file, mesh) meshCnt += 1 file.write("};\n\n") #Get the textures and the object to texture links imgUsedBuff = [] texBuff = [] imgFilename = [] for mesh in meshes: if mesh.getData().faces: if mesh.getData().faces[0].image: imgUsed = False imgNum = 0 for img in imgUsedBuff: imgFilename = mesh.getData().faces[0].image.getFilename().split("/") imgFilename = imgFilename[len(imgFilename)-1].split("\\") if imgFilename[len(imgFilename)-1] == img: imgUsed = True break imgNum += 1 texBuff.append(imgNum) if imgUsed == False: imgFilename = mesh.getData().faces[0].image.getFilename().split("/") imgFilename = imgFilename[len(imgFilename)-1].split("\\") imgUsedBuff.append(imgFilename[len(imgFilename)-1]) else: texBuff.append(-1) else: texBuff.append(-1) #Print object to texture links i = 0 file.write("//texture link number for each object\n") file.write("int %s_TEXLINKDAT[%i]={\n" % (contentName, len(meshes))) for tex in texBuff: file.write("%i,\n" % (tex)) i += 1 file.write("};\n\n") #Print the number of textures file.write("//number of textures\n") file.write("int %s_TEXCNT = %i;\n\n" % (contentName, len(imgUsedBuff))) #Print the point data array sizes to file polyCornerCnt = 0 file.write("//point data array sizes\n") file.write("int %s_POINTDATSZ[%i]={\n" % (contentName, len(meshes)+1)) file.write("0,\n") for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: polyCornerCnt += 3 elif len(face.v) == 4: polyCornerCnt += 4 file.write("%i,\n" % (polyCornerCnt * 3)) file.write("};\n\n") #Print the quad data array sizes to file polyCornerCnt = 0 file.write("//quad data array sizes\n") file.write("int %s_QUADDATSZ[%i]={\n" % (contentName, len(meshes)+1)) file.write("0,\n") for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 4: polyCornerCnt += 4 file.write("%i,\n" % (polyCornerCnt)) file.write("};\n\n") #Print the trigon data array sizes to file polyCornerCnt = 0 file.write("//trigon data array sizes\n") file.write("int %s_TRIDATSZ[%i]={\n" % (contentName, len(meshes)+1)) file.write("0,\n") for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: polyCornerCnt += 3 file.write("%i,\n" % (polyCornerCnt)) file.write("};\n\n") #Print the vertex color data array sizes to file polyCornerCnt = 0 file.write("//vertex color data array sizes\n") file.write("int %s_VCOLORDATSZ[%i]={\n" % (contentName, len(meshes)+1)) file.write("0,\n") for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: polyCornerCnt += 3 elif len(face.v) == 4: polyCornerCnt += 4 file.write("%i,\n" % (polyCornerCnt * 4)) file.write("};\n\n") #Print the texture coordinate data array sizes to file polyCornerCnt = 0 file.write("//texture coordinate data array sizes\n") file.write("int %s_TEXCOORDDATSZ[%i]={\n" % (contentName, len(meshes)+1)) file.write("0,\n") for mesh in meshes: for face in mesh.getData().faces: if len(face.v) == 3: polyCornerCnt += 3 elif len(face.v) == 4: polyCornerCnt += 4 file.write("%i,\n" % (polyCornerCnt * 2)) file.write("};\n\n") #Print visibility statis file.write("//visibility 0 = False 1 = True\n") file.write("int %s_HIDE[%i]={\n" % (contentName, len(meshes))) for mesh in meshes: file.write("%i,\n" % (0)) file.write("};\n\n") #Print the number of meshes file.write("//number of meshes\n") file.write("int %s_MESHCNT = %i;\n" % (contentName, len(meshes))) file.close() #Write the header file headerName = Blender.sys.dirname(file_name) headerName += '/' headerName += Blender.sys.splitext(Blender.sys.basename(file_name))[0] headerName += '.h' file = open(headerName, "w") file.write("extern float %s_TRANS[%i];\n" % (contentName, len(meshes) * 16)) file.write("extern float %s_POINT[%i];\n" % (contentName, quadCount*4*3 + trigonCount*3*3)) file.write("extern short %s_QUAD[%i];\n" % (contentName, quadCount*4)) file.write("extern short %s_TRI[%i];\n" % (contentName, trigonCount*3)) file.write("extern char %s_VCOLOR[%i];\n" % (contentName, quadCount*4*4 + trigonCount*3*4)) file.write("extern float %s_TEXCOORD[%i];\n\n" % (contentName, quadCount*4*2 + trigonCount*3*2)) file.write("extern int %s_TEXLINKDAT[%i];\n" % (contentName, len(meshes))) file.write("extern int %s_TEXCNT;\n" % (contentName)) file.write("int %s_TEX[%i];\n\n" % (contentName, len(imgUsedBuff))) file.write("extern int %s_POINTDATSZ[%i];\n" % (contentName, len(meshes)+1)) file.write("extern int %s_QUADDATSZ[%i];\n" % (contentName, len(meshes)+1)) file.write("extern int %s_TRIDATSZ[%i];\n" % (contentName, len(meshes)+1)) file.write("extern int %s_VCOLORDATSZ[%i];\n" % (contentName, len(meshes)+1)) file.write("extern int %s_TEXCOORDDATSZ[%i];\n\n" % (contentName, len(meshes)+1)) file.write("extern int %s_HIDE[%i];\n\n" % (contentName, len(meshes))) file.write("//unchanging transformation data\n") file.write("float %s_STATICTRANS[%i];\n\n" % (contentName, len(meshes) * 16)) file.write("//unchanging point data\n") file.write("float %s_STATICPOINT[%i];\n\n" % (contentName, quadCount*4*3 + trigonCount*3*3)) file.write("extern int %s_MESHCNT;\n\n" % (contentName)) #Print the names of the objects i = 0 file.write("//mesh names\n") for mesh in meshes: file.write("#define %s_" % (contentName)) for objNameChar in mesh.getName(): if objNameChar != ".": file.write("%c" % (objNameChar)) else: file.write("%c" % ("_")) file.write(" %i\n" % (i)) i += 1 file.write("\n") #Print texture names i = 0 file.write("//textures\n") for img in imgUsedBuff: file.write("#define %s_" % (contentName)) for imgChar in img: if imgChar != ".": file.write("%s" % (imgChar)) else: file.write("%s" % ("_")) file.write(" %i\n" % (i)) i += 1 file.close()
def main(): global CULL_METHOD is_editmode = Window.EditMode() if is_editmode: Window.EditMode(0) ob = bpy.data.scenes.active.objects.active if ob == None or ob.type != 'Mesh': BPyMessages.Error_NoMeshActive() return me = ob.getData(mesh=1) if me.multires: BPyMessages.Error_NoMeshMultiresEdit() return time1 = Blender.sys.time() selEdges = getSelectedEdges(me, ob) vertLoops = getVertLoops(selEdges, me) # list of lists of edges. if vertLoops == None: PupMenu( 'Error%t|Selection includes verts that are a part of more then 1 loop' ) if is_editmode: Window.EditMode(1) return # print len(vertLoops) if len(vertLoops) > 2: choice = PupMenu('Loft ' + str(len(vertLoops)) + ' edge loops%t|loop|segment') if choice == -1: if is_editmode: Window.EditMode(1) return elif len(vertLoops) < 2: PupMenu('Error%t|No Vertloops found!') if is_editmode: Window.EditMode(1) return else: choice = 2 # The line below checks if any of the vert loops are differenyt in length. if False in [len(v[0]) == len(vertLoops[0][0]) for v in vertLoops]: CULL_METHOD = PupMenu( 'Small to large edge loop distrobution method%t|remove edges evenly|remove smallest edges' ) if CULL_METHOD == -1: if is_editmode: Window.EditMode(1) return if CULL_METHOD == 1: # RESET CULL_METHOD CULL_METHOD = 0 # shortest else: CULL_METHOD = 1 # even time1 = Blender.sys.time() # Convert to special edge data. edgeLoops = [] for vloop, closed in vertLoops: edgeLoops.append(edgeLoop(vloop, me, closed)) # VERT LOOP ORDERING CODE # "Build a worm" list - grow from Both ends edgeOrderedList = [edgeLoops.pop()] # Find the closest. bestSoFar = BIG_NUM bestIdxSoFar = None for edLoopIdx, edLoop in enumerate(edgeLoops): l = (edgeOrderedList[-1].centre - edLoop.centre).length if l < bestSoFar: bestIdxSoFar = edLoopIdx bestSoFar = l edgeOrderedList.append(edgeLoops.pop(bestIdxSoFar)) # Now we have the 2 closest, append to either end- # Find the closest. while edgeLoops: bestSoFar = BIG_NUM bestIdxSoFar = None first_or_last = 0 # Zero is first for edLoopIdx, edLoop in enumerate(edgeLoops): l1 = (edgeOrderedList[-1].centre - edLoop.centre).length if l1 < bestSoFar: bestIdxSoFar = edLoopIdx bestSoFar = l1 first_or_last = 1 # last l2 = (edgeOrderedList[0].centre - edLoop.centre).length if l2 < bestSoFar: bestIdxSoFar = edLoopIdx bestSoFar = l2 first_or_last = 0 # last if first_or_last: # add closest Last edgeOrderedList.append(edgeLoops.pop(bestIdxSoFar)) else: # Add closest First edgeOrderedList.insert(0, edgeLoops.pop(bestIdxSoFar)) # First faces = [] for i in xrange(len(edgeOrderedList) - 1): faces.extend( skin2EdgeLoops(edgeOrderedList[i], edgeOrderedList[i + 1], me, ob, 0)) if choice == 1 and len(edgeOrderedList) > 2: # Loop faces.extend( skin2EdgeLoops(edgeOrderedList[0], edgeOrderedList[-1], me, ob, 0)) # REMOVE SELECTED FACES. MESH_MODE = Blender.Mesh.Mode() if MESH_MODE & Blender.Mesh.SelectModes.EDGE or MESH_MODE & Blender.Mesh.SelectModes.VERTEX: pass elif MESH_MODE & Blender.Mesh.SelectModes.FACE: try: me.faces.delete(1, [f for f in me.faces if f.sel]) except: pass me.faces.extend(faces, smooth=True) print '\nSkin done in %.4f sec.' % (Blender.sys.time() - time1) if is_editmode: Window.EditMode(1)
def doapply(evt, val): global bonecount editmode = Window.EditMode() if editmode: Window.EditMode(0) armobj = armature.getData() armobj.makeEditable() armbones = armobj.bones # rescan object's parents - hope that the user hasn't reparented bone = armbones[theobject.getParentBoneName()] editbones = [bone] while bone.parent: editbones.append(bone.parent) bone = bone.parent bonecount = min(bonecount, len(editbones)) # in case user has reparented # Rename bones - see armature_bone_rename in editarmature.c oldnames = [bone.name for bone in editbones] othernames = armbones.keys() for name in oldnames: othernames.remove(name) newnames = [] action = armature.getAction() if action: for boneno in range(bonecount): # rename this Action's channels to prevent error on dupes if oldnames[boneno] in action.getChannelNames(): action.renameChannel(oldnames[boneno], 'TmpChannel%d' % boneno) for boneno in range(bonecount - 1, -1, -1): # do in reverse order in case of duplicate names name = datarefs[boneno].split('/')[-1] # bone name getting up toward trouble? use PT name. We'd rather be ambiguous - and readable. if len(name) > 26: name = make_short_name(datarefs[boneno]) if indices[boneno] != None: name = '%s[%d]' % (name, indices[boneno]) # Have to manually avoid duplicate names i = 0 base = name while True: if name in othernames: i += 1 name = '%s.%03d' % (base, i) else: break editbones[boneno].name = name othernames.append(name) newnames.insert(0, name) # Update this Action's channels if action: oldchannel = 'TmpChannel%d' % boneno if oldchannel in action.getChannelNames(): # Delete keys ipo = action.getChannelIpo(oldchannel) for icu in ipo: i = 0 while i < len(icu.bezierPoints): if icu.bezierPoints[i].pt[0] > len(vals[boneno]): icu.delBezier(i) else: i += 1 # Rename action.renameChannel(oldchannel, name) # Update any other Actions' channels? armobj.update() # apply new bone names # Reparent children - have to do this after new bone names are applied for obj in Scene.GetCurrent().objects: if obj.parent == armature and obj.parentbonename in oldnames: obj.parentbonename = newnames[oldnames.index(obj.parentbonename)] # Now do properties props = {} # First do dataref paths for datarefs and hide/show for dataref in datarefs + hideshow: ref = dataref.split('/') if len(ref) > 1 and (ref[-1] not in lookup or not lookup[ref[-1]]): # not a standard dataref props[ref[-1]] = '/'.join(ref[:-1]) # datarefs values for boneno in range(len(datarefs)): ref = datarefs[boneno].split('/') name = make_short_name(datarefs[boneno]) #name=ref[-1] if indices[boneno] != None: name = '%s[%d]' % (name, indices[boneno]) if len(ref) > 1 or name in lookup: # write vals for ambiguous and unusable datarefs, but not invalid for frameno in range(len(vals[boneno])): if not ((frameno == 0 and vals[boneno][frameno] == 0) or (frameno == (len(vals[boneno]) - 1) and vals[boneno][frameno] == 1)): props['%s_v%d' % (name, frameno + 1)] = vals[boneno][frameno] if loops[boneno]: props[name + '_loop'] = loops[boneno] # Apply armature.removeAllProperties() keys = props.keys() keys.sort() for key in keys: armature.addProperty(key, props[key]) # Create properties for the manipulators manipulator = manipulators[0] sub_dict = sorted(manipulator_dict[manipulator].keys()) armature.addProperty('manipulator_type', manipulator) for field_id in sub_dict: field_name = field_id.split('@')[1] field_val = manipulator_dict[manipulator][field_id] property_name = manipulator + '_' + field_name if field_name == 'cursor': armature.addProperty(property_name, cursors[0]) else: armature.addProperty(property_name, field_val) # Hide/Show - order is significant h = 1 s = 1 for hs in range(len(hideshow)): name = hideshow[hs].split('/')[-1] if hideshowindices[hs] != None: name = '%s[%d]' % (name, hideshowindices[hs]) if hideorshow[hs]: armature.addProperty('%s_show_v%d' % (name, s), hideshowfrom[hs]) armature.addProperty('%s_show_v%d' % (name, s + 1), hideshowto[hs]) s += 2 else: armature.addProperty('%s_hide_v%d' % (name, h), hideshowfrom[hs]) armature.addProperty('%s_hide_v%d' % (name, h + 1), hideshowto[hs]) h += 2 Draw.Exit() if editmode: Window.EditMode(1) Window.RedrawAll() # in case bone names have changed return