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 traverse_dict(self, d): kids_dict = self.kids_dict exp_objs = self.exp_objs keys = d.keys() keys.sort() # sort for predictable output keys.reverse() for k in keys: objname = k[2:] klen = len(d[k]) kids_dict[objname] = klen if self.dont_export(objname): d.pop(k) parent = Object.Get(objname).getParent() if parent: kids_dict[parent.name] -= 1 REPORT_DATA['noexport'].append(objname) continue if klen: self.traverse_dict(d[k]) exp_objs.insert(0, objname) else: if k.find('Em', 0) == 0: # Empty w/o children d.pop(k) parent = Object.Get(objname).getParent() if parent: kids_dict[parent.name] -= 1 else: exp_objs.insert(0, objname)
def addprops(scene, lods): try: propobj=Object.Get('FSXProperties') propobj.removeAllProperties() except: propobj=Object.New('Empty', 'FSXProperties') scene.objects.link(propobj) propobj.layers=[] # invisible for layer in range(min(10,len(lods))): propobj.addProperty('LOD_%02d' % (layer+1), lods[layer])
def set_up(self, args): camera_target = Object.Get('camera_target') camera_target.RotX = math.radians(args['rotation_x']) camera_target.RotY = -math.radians(args['rotation_y']) camera_target.RotZ = math.radians(args['rotation_z']) camera = Camera.Get('camera') camera.angle = args['camera_lens_angle'] camera_ob = Object.Get('camera') camera_ob.LocX = args['camera_distance']
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 exportSelMesh(self): print "exporting ..." self.writeHeader() self.writeRootFrame() tex = [] objs = Object.GetSelected() for obj in objs: if obj.type == 'Mesh': mesh = obj.data self.writeTextures(obj, tex) self.writeMeshcoordArm(obj, arm_ob=None) self.writeMeshMaterialList(obj, mesh, tex) self.writeMeshNormals(obj, mesh) self.writeMeshTextureCoords(obj, mesh) self.writeMeshVertexColors(obj, mesh) self.file.write(" }\n") self.file.write("}\n") ind = objs.index(obj) if ind == len(objs) - 1: self.file.write("}\n") ip_list = obj.ipo if ip_list != None: self.file.write("AnimationSet AnimationSet0 {\n") self.writeAnimationObj(obj) self.file.write("}\n") else: print "The selected object is not a mesh" print "...finished"
def _calculate_edge_width_and_height(self): # cache -> to decorator? if self._width is not None and self._height is not None: return ob = Object.Get(self.tex_ob_name) me = ob.getData(mesh=True) tex_group = VertexGroup(me, self.name) tex_corner = VertexGroup(me, self.name + '_corner') connected_edges = tex_corner.find_connected_edges() common_edges = connected_edges.intersection(tex_group.edges) cross_product = cross(tex_corner.vertices.pop(), common_edges) face_normal = tex_group.faces.pop().no common_edges = list(common_edges) if vectors_on_same_side(cross_product, face_normal): e1, e2 = common_edges[0], common_edges[1] else: e1, e2 = common_edges[1], common_edges[0] # TODO: it would be better to use avg of edges # (top/bottom, left/right) here self._width, self._height = get_length(e1, ob), get_length(e2, 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 drawvc(ec): emptyname, coord = ec if Object.Get(emptyname) in G.selection: c = COLOR_VERTSEL else: c = COLOR_VERTUNSEL BGL.glColor4f(c[0], c[1], c[2], c[3]) BGL.glVertex2f(G.zoom * (coord[0] + x0), G.zoom * (coord[1] + y0))
def deform2rvk(): scn = Blender.Scene.GetCurrent() # ================================================================= # at leat 2 objects =============================================== # ================================================================= if len(scn.objects.selected) > 1: RVK1 = Object.GetSelected()[0] RVK2 = Object.GetSelected()[1] if RVK2.getType() == 'Mesh': copy_shapes(RVK1, RVK2) # ================================================================= # ... but if only one...=========================================== # ================================================================= elif len(scn.objects.selected) == 1: name = "At least 2 Meshes must be selected %t| Ok. %x1| Add one ? %x2" result = Draw.PupMenu(name) RVK1 = Object.GetSelected()[0] if result and RVK1.getType() == 'Mesh': Blender.Object.Duplicate(mesh=1) RVK2 = scn.objects.active mod = RVK2.modifiers for m in mod: RVK2.modifiers.remove(m) RVK2.LocX += 2.0 copy_shapes(RVK1, RVK2) scn.objects.selected = [] RVK2.sel = 1 RVK1.sel = 1 # ================================================================ # ... and not a mesh...=========================================== # ================================================================ elif result: name = "Selected object must be a mesh %t| Ok. %x1" result = Draw.PupMenu(name) return else: return # ================================================================ # ... if not object at all. ===================================== # ================================================================ else: name = "At least one Mesh object must be selected %t| Ok. %x1" result = Draw.PupMenu(name) return Blender.Redraw()
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 getbaseobjectname(): v = getValue('SCENE', 'baseobjectname') if v: return v else: # If there's no property, the base object is the active one. # Better get that right, then, my dear user. sel = Object.getSelected() return sel[0].name
def getbaseobjectname(): v = getValue('SCENE','baseobjectname') if v: return v else: # If there's no property, the base object is the active one. # Better get that right, then, my dear user. sel = Object.getSelected() return sel[0].name
def _adapt_proportions(self, args, image): ob = Object.Get(self.name).getParent() width, height = image.getSize() fac = height / 0.8 box_width = width / fac box_height = height / fac box_depth = max(float(args['box_depth']) / fac, 0.001) ob.setSize(box_depth, box_width, box_height)
def endDocument(self): """ Invoked when mesh processing is done. Used for realizing the mesh from collected vertex/faces and texturizing info. """ # report print("Finished loading file, constructing mesh...") Blender.Window.DrawProgressBar(0.9, "Building mesh...") # build object meshtools.create_mesh(self.verts, self.faces, self.objName, self.faceuvs, self.uvs) print("Done, object built") # load corresponding images and set texture Blender.Window.DrawProgressBar(0.95, "Loading/Applying Texture...") colorTex, specTex = None, None # convert images into textures if self.colorTexture: colTexFName = FindTexture(self.path, self.colorTexture) if colTexFName != None: colorImg = Image.Load(colTexFName) colorTex = Texture.New(self.objName + ".col.tx") colorTex.type = Texture.Types.IMAGE colorTex.image = colorImg if self.specTexture: specTexFName = FindTexture(self.path, self.specTexture) if specTexFName != None: specImg = Image.Load(specTexFName) specTex = Texture.New(self.objName + ".spe.tx") specTex.type = Texture.Types.IMAGE specTex.image = specImg # make material with them and all other previously collected data mat = Material.New(self.objName + ".mat") mat.mode |= Material.Modes.TEXFACE | Material.Modes.SHADOW | Material.Modes.TRACEABLE | Material.Modes.ZTRANSP mat.specTransp = 1.0 if self.alpha : mat.alpha = self.alpha if self.rgbCol : mat.rgbCol = self.rgbCol if self.amb : mat.amb = self.amb if self.emit : mat.emit = self.emit if self.spec : mat.spec = self.spec if self.specCol : mat.specCol = self.specCol if colorTex: mat.setTexture(0, colorTex, Texture.TexCo.UV, Texture.MapTo.COL) if specTex: mat.setTexture(1, specTex, Texture.TexCo.UV, Texture.MapTo.SPEC) # apply to mesh obj = Object.Get(self.objName) mesh = obj.data # mesh.mode = NMesh.Modes.NOVNORMALSFLIP # uncomment the following if you want models automatically sub-surfaced """for currFace in mesh.faces: currFace.smooth = 1 mesh.setSubDivLevels([1,2]) mesh.setMode("SubSurf", "TwoSided")""" mesh.setMode("TwoSided") mesh.addMaterial(mat) mesh.update(1) # Done, notify user Blender.Window.DrawProgressBar(1.0, "Done.")
def CheckSelection(): selob = Object.GetSelected() if not selob: Draw.PupMenu("Warning%t|Please make a selection.") elif ob and selob[0].name == ob.name: Draw.PupMenu("Warning%t|Object already selected.") else: return selob[0] return None
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 getoutputdirectory(): v = getValue('FILES','outputdirectory') if v: return v else: # None selected? Let's get it from the system. return os.getcwd() # If there's no property, the base object is the active one. # Better get that right, then, my dear user. sel = Object.getSelected() return sel[0].name
def getoutputdirectory(): v = getValue('FILES', 'outputdirectory') if v: return v else: # None selected? Let's get it from the system. return os.getcwd() # If there's no property, the base object is the active one. # Better get that right, then, my dear user. sel = Object.getSelected() return sel[0].name
def cleanMeshes(): objs = Object.Get() for o in objs: if o.getType( ) == 'Mesh': #Applies all scales and rotations (imitates CTRL+A behaviour) me = o.getData() mat = Mathutils.Matrix(o.matrix[0][:], o.matrix[1][:], o.matrix[2][:], [.0, .0, .0, 1.0]) me.transform(mat) me.update() o.setEuler(0.0, 0.0, 0.0) o.setSize(1.0, 1.0, 1.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 processdummy(model, parent): d = Object.Get(model) dt = d.getType() putlog(NBLog.INFO, "Processing %s (%s)" % (model, dt)) if dt != 'Empty': putlog(NBLog.CRITICAL, "Internal error: Can't process this type here!") return dummy = Dummy() if parent != "NULL": dummy.setParent(parent) dummy.setName(model) dummyloc = d.getLocation() dummy.setPosition(dummyloc) return dummy
def removeUnknownsFromCoords(): """ Checks that all names of empties in G.coordmap actually exist in the scene. If they don't, they're pruned from the map. """ global G for emptyname in G.coordmap.keys(): try: Object.Get(emptyname) except AttributeError: del G.coordmap[emptyname]
def addattach(scene, name, matrix): if name.startswith('attachpt_'): name=name[9:] if not name: name='AttachPoint' obj=Object.New('Empty', name) scene.objects.link(obj) obj.layers=[1] obj.addProperty('name', obj.name) # Need to convert between right and left handed coordinate systems. obj.setMatrix(RotationMatrix(-90,4,'x')*matrix*Matrix([1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1])) obj.LocY=-obj.LocY return obj
def processobject(model, parent, mfile): global scnobjchilds # Process this object #putlog(NBLog.DEBUG, "Processing object %s" % model) thismod = Object.Get(model) mtype = thismod.getType() if mtype == 'Empty': dummy = processdummy(model, parent) mfile.addObject(dummy) elif mtype == 'Mesh': # FIXME: Parent # new Trimesh class doesn't require processtrimesh #trimesh = processtrimesh(model, parent, 1) mfile.addObject(Trimesh(Object.Get(model), parent)) elif mtype == 'Armature': # Special code to handle armature: We process the armature's # children "by hand" to make them parent to the armature's # parent instead of the armature. try: childs = scnobjchilds[model] putlog(NBLog.DEBUG, "%s armature children: %s" % (model, join(childs, ", "))) for mchild in childs: processobject(mchild, parent, mfile) return except KeyError: return else: putlog(NBLog.CRITICAL, "Can't handle object of type %s" % mtype) # Process the children try: children = scnobjchilds[model] except KeyError: return processdownfrom(model, mfile)
def redrawScene(): """ Redraws the Scene. """ # Hide Armature from 3D-view # Disabled because the user might wish to view the armature movement. # for ob in scene.objects: # if ob.type == 'Armature': # ob.layers = [] # ob.makeDisplayList() # Set last frame of timeline to the last frame of the motion last imported. #frames = [ob for ob in scene.objects if ob.name == armature_name][0].getAction().getFrameNumbers() frames = Object.Get(armature_name).getProperty('num_frames').getData() scene.getRenderingContext().endFrame(frames) scene.update(1)
def main(): selected = Object.GetSelected() if len(selected) == 0: print "Nothing selected" return for obj in selected: if obj.getType() != "Mesh": continue file = open("%s.xml" % (obj.getName()), "w") file.write("<? xml version=\"1.0\" ?>\n") export(obj, file) file.close()
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 execute(self, input_image_path, blender_object): im = Image.Load(input_image_path) im_width, im_height = im.getSize() im_size_ratio = im_width / im_height tex_width = blender_object.texface.width tex_height = blender_object.texface.height tex_size_ratio = tex_width / tex_height ob = Object.Get(blender_object.name).getParent() if tex_size_ratio > im_size_ratio: # scale width scaling_ratio = im_size_ratio / tex_size_ratio ob.SizeY *= scaling_ratio else: # scale height scaling_ratio = tex_size_ratio / im_size_ratio ob.SizeZ *= scaling_ratio return im
def processSelected(): global outputdir if not os.path.isdir(outputdir): outputdir = os.curdir os.chdir(outputdir) objs = Object.GetSelected() if len(objs) == 0: print("Error: No Objects Selected") else: for obj in objs: if obj.getType() != "Mesh": print("Error: Object " + obj.name + " is a " + obj.getType() + ", not a mesh!") else: print("Object is a " + obj.getType()) exportObject(obj) print "Finished: xmesh files written to %s" % os.getcwd()
def shp_to_blender (shp, discretizer = None, mats = {}) : """Create a blender object for this shape :Parameters: - `shp` (Shape) - the shape to transform - `discretizer` (Discretizer) - algorithm to triangulate the geometry - `mats` (dict of (mat_id,Material) ) - precomputed pgl Material to avoid to recreate many instances of the same material :Returns Type: Object """ #name if shp.isNamed() : name = shp.getName() else : name = "pglshp%d" % shp.getId() #create material app = shp.appearance try : mat = mats[app.getId()] except KeyError : mat = material_to_blender(app) mats[app.getId()] = mat #create mesh mesh,mmat = geometry_to_blender(shp.geometry) #create object ob = Object.New('Mesh',name) ob.link(mesh) ob.setMaterials([mat]) if mmat is None : ob.colbits = 1 << 0 #return return ob
def centerNew(): objs = Object.Get() for o in objs: #Make all objects use 'Center New' if o.getType() == 'Mesh': me = o.getData() mat = o.getMatrix() me.transform(mat) me.update() mat = Blender.Mathutils.Matrix([1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]) o.setMatrix(mat) bb = o.getBoundBox() cu = [bb[0][n] + (bb[-2][n] - bb[0][n]) / 2.0 for n in [0, 1, 2]] mat = o.getMatrix() mat = Blender.Mathutils.Matrix(mat[0][:], mat[1][:], mat[2][:], [-cu[0], -cu[1], -cu[2], 1.0]) me.transform(mat) me.update() mat = Blender.Mathutils.Matrix(mat[0][:], mat[1][:], mat[2][:], [cu[0], cu[1], cu[2], 1.0]) o.setMatrix(mat)