Пример #1
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)
Пример #2
0
def edl_reload():
    Window.WaitCursor(1)
    filename = PREF['filename'].val
    sce = bpy.data.scenes.active
    fps = sce.render.fps

    elist = EditList()

    if filename:
        if not elist.parse(filename, fps):
            Draw.PupMenu('Error%t|Could not open the file "' + filename + '"')
        reels = elist.getReels()
    else:
        reels = {}

    REEL_UI.clear()
    for reel_key, edits in reels.iteritems():

        if reel_key == 'bw':
            continue

        flag = 0
        for edit in edits:
            flag |= edit.edit_type

        reel_item = REEL_UI[reel_key] = ReelItemUI()

        reel_item.ui_text = '%s (%s): ' % (reel_key, editFlagsToText(flag))

    Window.WaitCursor(0)
Пример #3
0
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()
Пример #4
0
def loadImage(fileName):
    """
	Handles loading an image.  This method populates
	G.image, G.ibuf, G.iw, G.ih.
	
	@param fileName: Name of the file to load.
	"""

    Window.WaitCursor(True)

    # load the image and set up parameters
    global G
    try:
        iloaded = loadTGARAW(fileName)
    except Exception:
        menuError('Could not load image.')
        iloaded = None
    if iloaded is None:
        return
    (G.image, ) = iloaded
    G.iw, G.ih = G.image.size
    G.imagename = fileName

    # centre the image in the window rectangle
    xw, yw, ww, hw = getWinRect()
    G.imgpos[0] = (ww - G.iw) / 2
    G.imgpos[1] = (hw - G.ih) / 2

    Window.WaitCursor(False)
Пример #5
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

    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)
Пример #6
0
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()
Пример #7
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)
Пример #8
0
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)
Пример #9
0
    def export(self, scene):
        theObjects = scene.objects

        print "Starting OBJ export to " + self.filename
        if not checkFile(self.filename):
            return

        Blender.Window.WaitCursor(1)
        Window.DrawProgressBar(0, "Examining textures")
        self.texture = getTexture(self, theObjects, self.iscsl, 7)
        if self.regions:
            (pwidth, pheight) = PanelRegionHandler().panelimage().size
            for img, (n, x1, y1, width, height) in self.regions.iteritems():
                self.regions[img] = (float(x1) / pwidth, float(y1) / pheight,
                                     float(width) / pwidth,
                                     float(height) / pheight)

        #clock=time.clock()	# Processor time

        self.file = open(self.filename, "w")
        self.writeHeader()
        self.writeObjects(theObjects)
        checkLayers(self, theObjects)
        self.file.close()

        Window.DrawProgressBar(1, "Finished")
        #print "%s CPU time" % (time.clock()-clock)
        print "Finished - exported %s primitives\n" % self.nprim
        if self.log:
            r = Draw.PupMenu(("Exported %s primitives%%t|" % self.nprim) +
                             '|'.join([a[0] for a in self.log]))
            if r > 0: raise ExportError(None, self.log[r - 1][1])
        else:
            Draw.PupMenu("Exported %s primitives%%t|OK" % self.nprim)
Пример #10
0
def button_event(evt):
    global config_data

    if (evt == BROWSE_HOME_CLICKED):
        default_path = "C:\\"
        if (Blender.sys.exists(config_data["home"])):
            default_path = config_data["home"]
        Window.FileSelector(SetHomeDir, "Nebula Home", default_path)
    if (evt == BROWSE_PROJ_CLICKED):
        default_path = "C:\\"
        if (Blender.sys.exists(config_data["home"])):
            default_path = config_data["proj"]
        Window.FileSelector(SetProjDir, "Project Dir", default_path)

    if (evt == ASSIGN_DIR_CHANGED):
        for data in config_data:
            if (data != "home" and data != "texture_dir" and data != "proj"):
                config_data[data] = dir_assigns[data].val

    if (evt == OK_CLICKED):
        SaveConfig()
        result = Draw.PupMenu("Saved%t|Do you want to exit?")
        if (result != -1):
            Draw.Exit()
            return

    if (evt == CANCEL_CLICKED):
        result = Draw.PupMenu("Exit%t|Exit and Discard Changes?")
        if (result != -1):
            Draw.Exit()
            return
Пример #11
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)
Пример #12
0
def copy_act_vgroup(me, PREF_NAME, PREF_SEL_ONLY):
    Window.WaitCursor(1)
    groupNames, vWeightDict = BPyMesh.meshWeight2Dict(me)
    act_group = me.activeGroup

    if not PREF_SEL_ONLY:
        for wd in vWeightDict:
            try:
                wd[PREF_NAME] = wd[act_group]
            except:
                pass
    else:
        # Selected faces only
        verts = {}  # should use set
        for f in me.faces:
            if f.sel:
                for v in f:
                    verts[v.index] = None

        for i in verts.iterkeys():
            wd = vWeightDict[i]
            try:
                wd[PREF_NAME] = wd[act_group]
            except:
                pass

    groupNames.append(PREF_NAME)
    # Copy weights back to the mesh.
    BPyMesh.dict2MeshWeight(me, groupNames, vWeightDict)
    Window.WaitCursor(0)
Пример #13
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
    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)
Пример #14
0
    def get_coordinates(self):
        win_id = Window.GetAreaID()
        win_data = Window.GetScreenInfo()

        for win in win_data:
            if win["id"] == win_id:
                return win["vertices"]
Пример #15
0
def file_callback(filename):
    obj = NETimport(filename)
    try:
        obj.doimport()
        Blender.Scene.GetCurrent().update()
    except ParseError, e:
        Window.WaitCursor(0)
        Window.DrawProgressBar(0, 'ERROR')
        if e.type == ParseError.HEADER:
            msg = 'This is not a valid X-Plane v6, v7 or v8 OBJ file'
        elif e.type == ParseError.NAME:
            msg = 'Missing dataref or light name at line %s\n' % obj.m.lineno
        elif e.type == ParseError.MISC:
            msg = '%s at line %s' % (e.value, obj.m.lineno)
        else:
            thing = ParseError.TEXT[e.type]
            if e.value:
                msg = 'Expecting a %s, found "%s" at line %s' % (
                    thing, e.value, obj.m.lineno)
            else:
                msg = 'Missing %s at line %s' % (thing, obj.m.lineno)
        print "ERROR:\t%s\n" % msg
        Draw.PupMenu("ERROR%%t|%s" % msg)
        Window.RedrawAll()
        Window.DrawProgressBar(1, 'ERROR')
Пример #16
0
def read_ui(filename):

    global guiTable, IMPORT_VC, IMPORT_UV
    guiTable = {'VC': 1, 'UV': 1}

    for s in Window.GetScreenInfo():
        Window.QHandle(s['id'])

    IMPORT_VC = Draw.Create(guiTable['VC'])
    IMPORT_UV = Draw.Create(guiTable['UV'])

    # Get USER Options
    pup_block = [
        ('Import Options'),
        ('Vertex Color', IMPORT_VC, 'Import Vertex Colors if exist'),
        ('UV', IMPORT_UV, 'Import UV if exist'),
    ]

    if not Draw.PupBlock('Import...', pup_block):
        return

    Window.WaitCursor(1)

    guiTable['VC'] = IMPORT_VC.val
    guiTable['UV'] = IMPORT_UV.val

    read_main(filename)

    Window.WaitCursor(0)
Пример #17
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)
Пример #18
0
def write_ui(filename):

    global guiTable, EXPORT_MOD, EXPORT_MTL, EXPORT_UV, EXPORT_VC, EXPORT_SELO, EXPORT_UVI, EXPORT_VG2SG
    guiTable = {
        'MOD': 1,
        'MTL': 1,
        'UV': 1,
        'VC': 1,
        'SELO': 1,
        'UVI': 0,
        'VG2SG': 1,
        'RECENTER': 0
    }

    EXPORT_MOD = Draw.Create(guiTable['MOD'])
    EXPORT_MTL = Draw.Create(guiTable['MTL'])
    EXPORT_UV = Draw.Create(guiTable['UV'])
    EXPORT_VC = Draw.Create(guiTable['VC'])
    EXPORT_SELO = Draw.Create(guiTable['SELO'])
    EXPORT_VG2SG = Draw.Create(guiTable['VG2SG'])
    EXPORT_REC = Draw.Create(guiTable['RECENTER'])

    # Get USER Options
    pup_block = [
        ('Mesh Options...'),
        ('Apply Modifiers', EXPORT_MOD,
         'Use modified mesh data from each object.'),
        ('Materials', EXPORT_MTL, 'Export Materials.'),
        ('Face UV', EXPORT_UV, 'Export texface UV coords.'),
        ('Vertex Colors', EXPORT_VC, 'Export vertex colors'), ('Context...'),
        ('Selection Only', EXPORT_SELO,
         'Only export objects in visible selection, else export all mesh object.'
         ), ('Bonus...'),
        ('VertGr. as SmoothGr.', EXPORT_VG2SG,
         'Make SmoothGroups by VertGroups. See doc.'),
        ('Center Objects', EXPORT_REC,
         'Center ALL objects to World-Grid-Origin-Center-Point-(0,0,0). ;)')
    ]

    if not Draw.PupBlock('Export...', pup_block):
        return

    Window.WaitCursor(1)

    guiTable['MOD'] = EXPORT_MOD.val
    guiTable['MTL'] = EXPORT_MTL.val
    guiTable['UV'] = EXPORT_UV.val
    guiTable['VC'] = EXPORT_VC.val
    guiTable['SELO'] = EXPORT_SELO.val
    guiTable['VG2SG'] = EXPORT_VG2SG.val
    guiTable['RECENTER'] = EXPORT_REC.val

    if not filename.lower().endswith('.ase'):
        filename += '.ase'

    write(filename)

    Window.WaitCursor(0)
Пример #19
0
def actWeightNormalize(me, PREF_MODE, PREF_MAX_DIST, PREF_STRENGTH, PREF_ITERATIONS):
	Window.WaitCursor(1)
	groupNames, vWeightDict= BPyMesh.meshWeight2Dict(me)
	act_group= me.activeGroup
	
	# Start with assumed zero weights
	orig_vert_weights= [0.0] * len(vWeightDict) # Will be directly assigned to orig_vert_weights
	
	
	# fill in the zeros with real weights.
	for i, wd in enumerate(vWeightDict):
		try:
			orig_vert_weights[i]= wd[act_group]
		except:
			pass
	
	new_vert_weights= list(orig_vert_weights)
	
	for dummy in xrange(PREF_ITERATIONS):
		# Minimize or maximize the weights. connection based.
		
		if PREF_MODE==0: # Grow
			op= max
		else: # Shrink
			op= min
		
		for ed in me.edges:
			if not PREF_MAX_DIST or ed.length < PREF_MAX_DIST:
			
				i1= ed.v1.index
				i2= ed.v2.index
				new_weight= op(orig_vert_weights[i1], orig_vert_weights[i2])
				
				if PREF_STRENGTH==1.0: # do a full copy
					new_vert_weights[i1]= op(new_weight, new_vert_weights[i1])
					new_vert_weights[i2]= op(new_weight, new_vert_weights[i2])
					
				else: # Do a faded copy
					new_vert_weights[i1]= op(new_weight, new_vert_weights[i1])
					new_vert_weights[i2]= op(new_weight, new_vert_weights[i2])
					
					# Face the copy with the original (orig is updated per iteration)
					new_vert_weights[i1]= (new_vert_weights[i1]*PREF_STRENGTH) + (orig_vert_weights[i1]*(1-PREF_STRENGTH))
					new_vert_weights[i2]= (new_vert_weights[i2]*PREF_STRENGTH) + (orig_vert_weights[i2]*(1-PREF_STRENGTH))
		
		
		for i, wd in enumerate(vWeightDict):
			new_weight= new_vert_weights[i]
			if new_weight != orig_vert_weights[i]:
				wd[act_group]= new_weight
		
		if dummy+1 != PREF_ITERATIONS: # dont copy the list on the last round.
			orig_vert_weights= list(new_vert_weights)
		
		
	# Copy weights back to the mesh.
	BPyMesh.dict2MeshWeight(me, groupNames, vWeightDict)
	Window.WaitCursor(0)
Пример #20
0
def do_export(sel_group, filepath):
	Window.WaitCursor(1)
	t = sys.time()

	#init Drawing ---------------------
	d=Drawing()
	#add Tables -----------------
	#d.blocks.append(b)					#table blocks
	d.styles.append(Style())			#table styles
	d.views.append(View('Normal'))		#table view
	d.views.append(ViewByWindow('Window',leftBottom=(1,0),rightTop=(2,1)))  #idem

	#add Entities --------------------
	something_ready = False
	#ViewVector = Mathutils.Vector(Window.GetViewVector())
	#print 'deb: ViewVector=', ViewVector #------------------
	mw0 = Window.GetViewMatrix()
	#mw0 = Window.GetPerspMatrix() #TODO: how get it working?
	mw = mw0.copy()
	if FLATTEN:
		m0 = Mathutils.Matrix()
		m0[2][2]=0.0
		mw *= m0 #flatten ViewMatrix

	for ob in sel_group:
		entities = []
		mx = ob.matrix.copy()
		mb = mx.copy()
		#print 'deb: mb    =\n', mb     #---------
		#print 'deb: mw0    =\n', mw0     #---------
		mx_n = mx.rotationPart() * mw0.rotationPart() #trans-matrix for normal_vectors
		if SCALE_FACTOR!=1.0: mx *= SCALE_FACTOR
		if FLATTEN:	mx *= mw
			
		#mx_inv = mx.copy().invert()
		#print 'deb: mx    =\n', mx     #---------
		#print 'deb: mx_inv=\n', mx_inv #---------

		if (ob.type == 'Mesh'):
			entities = exportMesh(ob, mx, mx_n)
		elif (ob.type == 'Curve'):
			entities = exportCurve(ob, mx)

		for e in entities:
			d.append(e)
			something_ready = True

	if something_ready:
		d.saveas(filepath)
		Window.WaitCursor(0)
		#Draw.PupMenu('DXF Exporter: job finished')
		print 'exported to %s' % filepath
		print 'finished in %.2f seconds' % (sys.time()-t)
	else:
		Window.WaitCursor(0)
		print "Abort: selected objects dont mach choosen export option, nothing exported!"
		Draw.PupMenu('DXF Exporter:   nothing exported!|selected objects dont mach choosen export option!')
Пример #21
0
def filesel_callback(filename):

	inform("\nTrying to import AC3D model(s) from:\n%s ..." % filename)
	Window.WaitCursor(1)
	starttime = bsys.time()
	test = AC3DImport(filename)
	Window.WaitCursor(0)
	endtime = bsys.time() - starttime
	inform('Done! Data imported in %.3f seconds.\n' % endtime)
def mouseup():
    # Loop until click
    mouse_buttons = Window.GetMouseButtons()
    while not mouse_buttons & LMB:
        sys.sleep(10)
        mouse_buttons = Window.GetMouseButtons()
    while mouse_buttons & LMB:
        sys.sleep(10)
        mouse_buttons = Window.GetMouseButtons()
Пример #23
0
def buttonEventHandler(button):
    """
	Event handler for button presses.
	
	@param button: Button ID.
	"""

    global G
    G.havebupclik = False

    if button == BUTTON_QUIT:
        removeCustomScriptLink()
        writeDataToRegistry()
        Draw.Exit()
        Window.RedrawAll()

    elif button == BUTTON_LOAD:
        G.havebupclik = True
        Window.ImageSelector(loadImage)

    elif button == BUTTON_ZOOM:
        x, y, w, h = getWinRect()
        setZoom((w / 2, h / 2), G.buttons.zoom.val)

    elif button == BUTTON_FULLOPT:
        G.fullopt = G.buttons.fullopt.val

    elif button == BUTTON_COPLANAR:
        G.coplanar = G.buttons.coplanar.val

    elif button == BUTTON_OFSX:
        G.ofsx = G.buttons.ofsx.val

    elif button == BUTTON_OFSY:
        G.ofsy = G.buttons.ofsy.val

    elif button == BUTTON_OFSZ:
        G.ofsz = G.buttons.ofsz.val

    elif button == BUTTON_ADD:
        G.mode = MODE_ADD
        Draw.Redraw(1)

    elif button == BUTTON_DELETE:

        def delmap(x):
            del G.coordmap[x.getName()]
            x.select(False)

        map(delmap, G.selection)
        Window.RedrawAll()

    elif button == BUTTON_CALIBRATE:
        Window.WaitCursor(True)
        G.last_camera = G.selection[0]
        calibrate()
def create_topomesh(filename):
    Window.WaitCursor(True)

    #current object
    sc = Scene.GetCurrent()
    ref_obj = sc.getActiveObject()

    save_topomesh(filename, ref_obj.data)

    Window.RedrawAll()
Пример #25
0
    def layer_number(elem):
        layer_number = int(elem.name)
        visible_layers = Window.ViewLayers()

        if layer_number in visible_layers:
            if len(visible_layers) > 1:
                visible_layers.remove(layer_number)
        else:
            visible_layers.append(layer_number)

        Window.ViewLayers(visible_layers)
Пример #26
0
def runAsTextPlugin():
    '''Called when run as a text plugin.'''

    import Blender
    from Blender import Window, sys, Draw
    import BPyTextPlugin, bpy

    message = ("Convert Game Engine script from 4.48 API to 2.49 API%t|"
               "Run on active script only%x1|"
               "Run on ALL text buffers%x2")
    convertAllBuffers = Draw.PupMenu(message) == 2

    Window.WaitCursor(1)
    try:
        nconverted = 0
        nerrors = 0

        if convertAllBuffers:
            texts = bpy.data.texts
        else:
            if not bpy.data.texts.active:
                Draw.PupMenu("No active buffer.")
                return
            texts = [bpy.data.texts.active]

        Blender.SaveUndoState('Convert BGE 2.49')

        for txt in texts:
            bufName = txt.name
            if txt.lib:
                bufName = txt.lib + '/' + bufName
            lines = txt.asLines()
            for i in range(0, len(lines)):
                if not lines[i].endswith('\n'):
                    lines[i] = lines[i] + '\n'

            nc, ne = convert248to249(lines, fileName=bufName)
            nconverted = nconverted + nc
            nerrors = nerrors + ne
            txt.clear()
            for line in lines:
                txt.write(line)

    finally:
        Window.WaitCursor(0)

        message = "Converted %d attributes." % nconverted
        if nerrors == 1:
            message = message + " There was 1 error (see console)."
        if nerrors > 1:
            message = message + " There were %d errors (see console)." % nerrors
        message = message + "|Please review all the changes."
        Draw.PupMenu(message)
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 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()
Пример #29
0
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)
Пример #30
0
def build(type):
    global shapes, widmenu, rangename
    sce = bpy.data.scenes.active
    ob = sce.objects.active

    try:
        ob.getData(mesh=1).key
    except:
        Blender.Draw.PupMenu('Aborting%t|Object has no keys')
        return

    loc = Window.GetCursorPos()
    range = makeRange(sce, type, rangename.val)
    controller = makeController(sce, rangename.val)
    text = makeText(sce, rangename.val)

    range.restrictRender = True
    controller.restrictRender = True
    text.restrictRender = True

    range.setLocation(loc)
    controller.setLocation(loc)
    text.setLocation(loc)

    range.makeParent([controller], 1)
    range.makeParent([text], 0)

    sce.update()

    setupDrivers(ob, controller, widmenu.val)
Пример #31
0
 def progress(self, message=None):
   if message==None:
     message=self.status
   Window.drawProgressBar(1.0-len(self.lines)/self.length, message)