def addCustomScriptLink(): """ Adds a custom script link to the scene so that all script windows are redrawn whenever the scene is redrawn. """ txt = Text.New(SCRIPTLINK_NAME) txt.write('import Blender\n') txt.write('from Blender import Window\n') txt.write('Window.Redraw(Window.Types.SCRIPT)\n') Scene.GetCurrent().addScriptLink(SCRIPTLINK_NAME, 'Redraw') # do a full scene update Scene.GetCurrent().update(1)
def write(filename, objects): def veckey3d(v): return round(v.x, 6), round(v.y, 6), round(v.z, 6) def veckey2d(v): return round(v.x, 6), round(v.y, 6) print 'OBJ Export path: "%s"' % filename temp_mesh_name = '~tmp-mesh' time1 = sys.time() scn = Scene.GetCurrent() file = open(filename, "w") # Write Header file.write('# Blender3D v%s EOL Armature File: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1])) file.write('# www.blender3d.org\n') # Get all armatures for ob_main in objects: for ob, ob_mat in BPyObject.getDerivedObjects(ob_main): write_armature(file, ob) write_poses(file, ob) file.close() print "Armature Export time: %.2f" % (sys.time() - time1)
def main(): scn = Scene.GetCurrent() ob = scn.objects.active if not ob or ob.type != 'Mesh': Draw.PupMenu('Error, no active mesh object, aborting.') return me = ob.getData(mesh=1) act_group = me.activeGroup PREF_NAME = Draw.Create(act_group + '_copy') PREF_SEL_ONLY = Draw.Create(0) pup_block= [\ ('', PREF_NAME, 0, 31, 'Name of group copy.'),\ ('Only Selected', PREF_SEL_ONLY, 'Only include selected faces in the new grop.'),\ ] if not Draw.PupBlock('New Name...', pup_block): return PREF_NAME = PREF_NAME.val PREF_SEL_ONLY = PREF_SEL_ONLY.val copy_act_vgroup(me, PREF_NAME, PREF_SEL_ONLY) try: me.activeGroup = PREF_NAME except: pass
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(): scn = Scene.GetCurrent() ob = scn.objects.active if not ob or ob.type != 'Mesh': Draw.PupMenu('Error, no active mesh object, aborting.') return me = ob.getData(mesh=1) PREF_PEAKWEIGHT = Draw.Create(1.0) PREF_ACTIVE_ONLY = Draw.Create(1) PREF_KEEP_PROPORTION = Draw.Create(1) PREF_ARMATURE_ONLY = Draw.Create(0) pup_block= [\ ('Peak Weight:', PREF_PEAKWEIGHT, 0.01, 1.0, 'Upper weight for normalizing.'),\ ('Active Only', PREF_ACTIVE_ONLY, 'Only Normalize groups that have matching bones in an armature (when an armature is used).'),\ ('Proportional', PREF_KEEP_PROPORTION, 'Scale other weights so verts (Keep weights with other groups in proportion).'),\ ('Armature Only', PREF_ARMATURE_ONLY, 'Only Normalize groups that have matching bones in an armature (when an armature is used).'),\ ] if not Draw.PupBlock('Clean Selected Meshes...', pup_block): return actWeightNormalize(me, ob, PREF_PEAKWEIGHT.val, PREF_ACTIVE_ONLY.val, PREF_ARMATURE_ONLY.val, PREF_KEEP_PROPORTION.val)
def main(): scn= Scene.GetCurrent() ob= scn.objects.active if not ob or ob.type != 'Mesh': Draw.PupMenu('Error, no active mesh object, aborting.') return me= ob.getData(mesh=1) PREF_MAXDIST= Draw.Create(0.0) PREF_STRENGTH= Draw.Create(1.0) PREF_MODE= Draw.Create(0) PREF_ITERATIONS= Draw.Create(1) pup_block= [\ ('Bleed Dist:', PREF_MAXDIST, 0.0, 1.0, 'Set a distance limit for bleeding.'),\ ('Bleed Strength:', PREF_STRENGTH, 0.01, 1.0, 'Bleed strength between adjacent verts weight. 1:full, 0:None'),\ ('Iterations', PREF_ITERATIONS, 1, 20, 'Number of times to run the blending calculation.'),\ ('Contract (Shrink)', PREF_MODE, 'Shrink instead of growing.'),\ ] if not Draw.PupBlock('Grow/Shrink...', pup_block): return actWeightNormalize(me, PREF_MODE.val, PREF_MAXDIST.val, PREF_STRENGTH.val, PREF_ITERATIONS.val)
def load_point_set(filename): """Read a point set and duplicate obj for each location. Insert every created object in sc """ Window.WaitCursor(True) sc = Scene.GetCurrent() ref_obj = sc.getActiveObject() #unselect everything except ref for obj in Object.GetSelected(): obj.sel = 0 ref_obj.sel = 1 #read points pts = load(open(filename, 'rb')) for pid, vec in pts.iteritems(): Object.Duplicate() obj = sc.getActiveObject() obj.setLocation(*vec) #return Window.RedrawAll()
def mdd_import_ui(filepath): if BPyMessages.Error_NoFile(filepath): return scn = Scene.GetCurrent() ob_act = scn.objects.active if ob_act == None or ob_act.type != 'Mesh': BPyMessages.Error_NoMeshActive() return PREF_IPONAME = Blender.Draw.Create( filepath.split('/')[-1].split('\\')[-1].split('.')[0]) PREF_START_FRAME = Blender.Draw.Create(1) PREF_JUMP = Blender.Draw.Create(1) block = [\ ("Ipo Name: ", PREF_IPONAME, 0, 30, "Ipo name for the new shape key"),\ ("Start Frame: ", PREF_START_FRAME, 1, 3000, "Start frame for the animation"),\ ("Key Skip: ", PREF_JUMP, 1, 100, "KeyReduction, Skip every Nth Frame")\ ] if not Blender.Draw.PupBlock("Import MDD", block): return orig_frame = Blender.Get('curframe') mdd_import(filepath, ob_act, PREF_IPONAME.val, PREF_START_FRAME.val, PREF_JUMP.val) Blender.Set('curframe', orig_frame)
def write_poses(file,ob): if ob.getType() != "Armature": return scn = Scene.GetCurrent() context = scn.getRenderingContext() scene_frames = xrange(context.startFrame(), context.endFrame()+1) file.write('framecount %i\n' % len(scene_frames)) for frame in scene_frames: Blender.Set('curframe', frame) file.write('frame: %i\n' % frame) pose = ob.getPose() for b in pose.bones.values(): file.write('posebone: %s\n' % b.name) for i in b.localMatrix: file.write('lm: %.6f %.6f %.6f %.6f\n' % tuple(i)) file.write('scale: %.6f %.6f %.6f\n' % tuple(b.size)) # file.write('keyframes: %s\n' % ob.name) # for ipo in Blender.Ipo.Get(): # if ipo.getNcurves() == 0: # continue # # adapted from the ogre 3D exporter # # too bad, there is no clean way to get the ipo for a bone :( # file.write('Ipo: %s\n' % ipo.name) # ipoName = ipo.getName() # for c in ipo.curves: # file.write('curve type: %s\n' % c.name) file.write('\n')
def delRegion(self, img): r = self.isRegion(img) if not r: return False (n, x1, y1, width, height) = r mesh = self.obj.getData(mesh=True) panelimage = mesh.faces[0].image try: (pwidth, pheight) = panelimage.size xoff = float(x1) / pwidth yoff = float(y1) / pheight xscale = float(width) / pwidth yscale = float(height) / pheight except: xoff = yoff = 0 xscale = yscale = 1 # Reassign UV mappings back to panel image for obj in Scene.GetCurrent().objects: if obj != self.obj and obj.getType() == "Mesh": mesh2 = obj.getData(mesh=True) if mesh2.faceUV: for face in mesh2.faces: if face.image == img: face.image = panelimage face.uv = [ Vector( [xoff + v.x * xscale, yoff + v.y * yscale]) for v in face.uv ] mesh2.update() mesh.faces[n].image = panelimage img.reload() # blank old region self.obj.removeProperty('x%d' % n) self.obj.removeProperty('y%d' % n) return True
def layer_objects_constraint(root_layout): object_filter = ObjectFilter(scene=Scene.GetCurrent()) layers = root_layout.find_child(name='layers') assign_all_objects_to_layer(layer=20) for layer in layers.children: filtered_objects = None filters = layer.find_child(name='filters') layer_number = layer.find_child(name='layer_number') for child in filters.children: if child.name == 'filter': filter_type = child.find_child(name='filter_type') filter_name = child.find_child(name='filter_name') if filter_type.value == 1: print 'filter data' filtered_objects = object_filter.data( filter_name.value) if filter_type.value == 2: print 'filter name. TO BE IMPLEMENTED' #filtered_objects = object_filter.name_is(filter_name.value) if filter_type.value == 3: print 'filter group. TO BE IMPLEMENTED' try: for ob in filtered_objects: layers = ob.layers layers.append(int(layer_number.label)) ob.layers = layers except TypeError: pass
def assign_all_objects_to_layer(layer): scn = Scene.GetCurrent() for ob in scn.objects: ob.layers = [ layer, ]
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(): scn = Scene.GetCurrent() if not scn.objects.context: return PREF_LOC = Draw.Create(0.0) PREF_SIZE = Draw.Create(0.0) PREF_ROT = Draw.Create(0.0) PREF_LINK_AXIS = Draw.Create(0) PREF_X_AXIS = Draw.Create(1) PREF_Y_AXIS = Draw.Create(1) PREF_Z_AXIS = Draw.Create(1) pup_block = [\ ('loc:', PREF_LOC, 0.0, 100.0, 'Amount to randomize the location'),\ ('size:', PREF_SIZE, 0.0, 100.0, 'Amount to randomize the size'),\ ('rot:', PREF_ROT, 0.0, 360.0, 'Amount to randomize the rotation'),\ '',\ ('Link Axis', PREF_LINK_AXIS, 'Use the same random value for each objects XYZ'),\ ('X Axis', PREF_X_AXIS, 'Enable X axis randomization'),\ ('Y Axis', PREF_Y_AXIS, 'Enable Y axis randomization'),\ ('Z Axis', PREF_Z_AXIS, 'Enable Z axis randomization'),\ ] if not Draw.PupBlock('Object Randomize', pup_block): return randomize(scn.objects.context, PREF_LOC.val, PREF_SIZE.val, PREF_ROT.val, PREF_LINK_AXIS.val, PREF_X_AXIS.val, PREF_Y_AXIS.val, PREF_Z_AXIS.val)
def sc_to_blender(sc): """Export each shape in the scene as a new object :Parameters: - `sc` (Scene) - the scene to transform :Returns Type: None """ bldsc = Scene.GetCurrent() #fill with shapes t = time.time() d = Discretizer() for ind, shp in enumerate(sc): if ind % 10 == 0: print ind, sys.stdout.flush() ob = shp_to_blender(shp, d) bldsc.link(ob) ob.sel = True print print 'Time :', time.time() - t #return print "created" bldsc.update(1) Blender.Redraw() return ob
def __init__(self): self.obj = None try: self.obj = Object.Get(PanelRegionHandler.NAME) # Suppress regeneration of panels in v3.0x Scene.GetCurrent().clearScriptLinks(PanelRegionHandler.NAME) except: pass
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 render(self): scene = Scene.GetCurrent() script = imp.load_source(self.args['script'], self.args['script_path']) blender_initializer = script.BlenderInitializer() blender_initializer.set_up_render(self.args, scene) self.set_up_render_context(scene) blender_initializer.clean_up()
def addRegion(self, xoff, yoff, width, height): mesh = self.obj.getData(mesh=True) panelimage = mesh.faces[0].image name = 'PanelRegion' for img in Image.get(): # try to re-use existing deleted panel region if img.size == [ width, height ] and img.source == Image.Sources.GENERATED and img.filename == name and not self.isRegion( img): break else: img = Image.New(name, width, height, 24) for y in range(height): for x in range(width): rgba = panelimage.getPixelI(xoff + x, yoff + y) if not rgba[3]: img.setPixelI(x, y, (102, 102, 255, 255)) # hilite transparent else: img.setPixelI(x, y, rgba[:3] + [255]) img.pack() for n in range(1, PanelRegionHandler.REGIONCOUNT + 1): if mesh.faces[n].image == panelimage: mesh.faces[n].image = img self.obj.addProperty('x%d' % n, xoff) self.obj.addProperty('y%d' % n, yoff) (width, height) = img.size (pwidth, pheight) = panelimage.size xoff = float(xoff) / pwidth yoff = float(yoff) / pheight xscale = float(pwidth) / width yscale = float(pheight) / height # Assign UV mappings from panel image for obj in Scene.GetCurrent().objects: if obj != self.obj and obj.getType() == "Mesh": mesh2 = obj.getData(mesh=True) if mesh2.faceUV: for face in mesh2.faces: if face.image == panelimage: uv = [] for v in face.uv: x = (v.x - xoff) * xscale y = (v.y - yoff) * yscale if not -UV.LIMIT <= x <= 1 + UV.LIMIT or not -UV.LIMIT <= y <= 1 + UV.LIMIT: break uv.append( Vector(min(max(x, 0), 1), min(max(y, 0), 1))) else: face.uv = uv face.image = img mesh2.update() break return img
def create_topomesh(filename): Window.WaitCursor(True) #current object sc = Scene.GetCurrent() ref_obj = sc.getActiveObject() save_topomesh(filename, ref_obj.data) Window.RedrawAll()
def setSubsurf(): scn = Scene.GetCurrent() # link object to current scene for potential_ob in scn.objects: if potential_ob.name == 'myObj': ob = potential_ob break mods = ob.modifiers mod = mods.append(Modifier.Types.SUBSURF) mod[Modifier.Settings.LEVELS] = 1 mod[Modifier.Settings.RENDLEVELS] = 2
def NewObject(flag): global ob, me, sc if flag == 1: DumpData() DeselectAllObjects() sc = Scene.GetCurrent() cursorpos = Window.GetCursorPos() ob = Object.New('Mesh', 'Cyl_') me = NMesh.New('MyCylMesh') ob.setLocation(cursorpos) ob.link(me) sc.link(ob)
def act_mesh_ob(): scn = Scene.GetCurrent() ob = scn.objects.active if ob == None or ob.type != 'Mesh': BPyMessages.Error_NoMeshActive() return if ob.getData(mesh=1).multires: BPyMessages.Error_NoMeshMultiresEdit() return return ob
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 create_topomesh(filename): Window.WaitCursor(True) #link to object obj = Object.New('Mesh', 'myObj') #link to scene sc = Scene.GetCurrent() sc.link(obj) me = load_topomesh(filename, obj) Window.RedrawAll()
def render(path="//myRenderdir/", imageName="001.tga"): scn = Scene.GetCurrent() context = scn.getRenderingContext() Render.EnableDispWin() context.extensions = True context.renderPath = path context.sizePreset(Render.PC) context.imageType = Render.TARGA context.render() context.saveRenderedImage(imageName) Render.CloseRenderWindow()
def __init__(self, scene=None, objects=None): self.scene = None self.objects = None try: self.scene = Scene.Get(scene) self.objects = self.scene.objects except (NameError, TypeError): pass if type(scene) == type(Scene.GetCurrent()): self.scene = scene if objects: self.objects = objects
def export(filename): trace("Exporting to file: '" + filename) verbose("Configuration:") indent() verbose("_rotationLimit='%f'" % _rotationLimit) verbose("_quaternionWLimit='%f'" % _quaternionWLimit) unindent() exporter = XamlExporter() fileout = open(filename, 'w') try: exporter.writeScene(Scene.GetCurrent(), fileout) finally: fileout.close()
def removeCustomScriptLink(): """ Removes the custom script link (if it is present) from the scene. """ try: txt = Text.Get(SCRIPTLINK_NAME) except NameError: # script link not found return scene = Scene.GetCurrent() slinks = scene.getScriptLinks('Redraw') if slinks is not None: scene.clearScriptLinks() if SCRIPTLINK_NAME in slinks: slinks.remove(SCRIPTLINK_NAME) for link in slinks: scene.addScriptLink(link, 'Redraw') Text.unlink(txt) # do a full scene update Scene.GetCurrent().update(1)
def __init__(self, filename): global errmsg self.scene = Scene.GetCurrent() self.i = 0 errmsg = '' self.importdir = bsys.dirname(filename) try: file = open(filename, 'r') except IOError, (errno, strerror): errmsg = "IOError #%s: %s" % (errno, strerror) Blender.Draw.PupMenu('ERROR: %s' % errmsg) inform(errmsg) return None