def file_callback(filename): if not filename.lower().endswith('.ply'): filename += '.ply' scn = bpy.data.scenes.active ob = scn.objects.active if not ob: Blender.Draw.PupMenu('Error%t|Select 1 active object') return file = open(filename, 'wb') EXPORT_APPLY_MODIFIERS = Draw.Create(1) EXPORT_NORMALS = Draw.Create(1) EXPORT_UV = Draw.Create(1) EXPORT_COLORS = Draw.Create(1) #EXPORT_EDGES = Draw.Create(0) pup_block = [\ ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.'),\ ('Normals', EXPORT_NORMALS, 'Export vertex normal data.'),\ ('UVs', EXPORT_UV, 'Export texface UV coords.'),\ ('Colors', EXPORT_COLORS, 'Export vertex Colors.'),\ #('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\ ] if not Draw.PupBlock('Export...', pup_block): return is_editmode = Blender.Window.EditMode() if is_editmode: Blender.Window.EditMode(0, '', 0) Window.WaitCursor(1) EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val EXPORT_NORMALS = EXPORT_NORMALS.val EXPORT_UV = EXPORT_UV.val EXPORT_COLORS = EXPORT_COLORS.val #EXPORT_EDGES = EXPORT_EDGES.val mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn) if not mesh: Blender.Draw.PupMenu( 'Error%t|Could not get mesh data from active object') return mesh.transform(ob.matrixWorld) faceUV = mesh.faceUV vertexUV = mesh.vertexUV vertexColors = mesh.vertexColors if (not faceUV) and (not vertexUV): EXPORT_UV = False if not vertexColors: EXPORT_COLORS = False if not EXPORT_UV: faceUV = vertexUV = False if not EXPORT_COLORS: vertexColors = False # incase color = uvcoord = uvcoord_key = normal = normal_key = None verts = [] # list of dictionaries # vdict = {} # (index, normal, uv) -> new index vdict = [{} for i in xrange(len(mesh.verts))] vert_count = 0 for i, f in enumerate(mesh.faces): smooth = f.smooth if not smooth: normal = tuple(f.no) normal_key = rvec3d(normal) if faceUV: uv = f.uv if vertexColors: col = f.col for j, v in enumerate(f): if smooth: normal = tuple(v.no) normal_key = rvec3d(normal) if faceUV: uvcoord = uv[j][0], 1.0 - uv[j][1] uvcoord_key = rvec2d(uvcoord) elif vertexUV: uvcoord = v.uvco[0], 1.0 - v.uvco[1] uvcoord_key = rvec2d(uvcoord) if vertexColors: color = col[j].r, col[j].g, col[j].b key = normal_key, uvcoord_key, color vdict_local = vdict[v.index] if (not vdict_local) or (not vdict_local.has_key(key)): vdict_local[key] = vert_count verts.append((tuple(v.co), normal, uvcoord, color)) vert_count += 1 file.write('ply\n') file.write('format ascii 1.0\n') file.write( 'comment Created by Blender3D %s - www.blender.org, source file: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1])) file.write('element vertex %d\n' % len(verts)) file.write('property float x\n') file.write('property float y\n') file.write('property float z\n') if EXPORT_NORMALS: file.write('property float nx\n') file.write('property float ny\n') file.write('property float nz\n') if EXPORT_UV: file.write('property float s\n') file.write('property float t\n') if EXPORT_COLORS: file.write('property uchar red\n') file.write('property uchar green\n') file.write('property uchar blue\n') file.write('element face %d\n' % len(mesh.faces)) file.write('property list uchar uint vertex_indices\n') file.write('end_header\n') for i, v in enumerate(verts): file.write('%.6f %.6f %.6f ' % v[0]) # co if EXPORT_NORMALS: file.write('%.6f %.6f %.6f ' % v[1]) # no if EXPORT_UV: file.write('%.6f %.6f ' % v[2]) # uv if EXPORT_COLORS: file.write('%u %u %u' % v[3]) # col file.write('\n') for (i, f) in enumerate(mesh.faces): file.write('%d ' % len(f)) smooth = f.smooth if not smooth: no = rvec3d(f.no) if faceUV: uv = f.uv if vertexColors: col = f.col for j, v in enumerate(f): if f.smooth: normal = rvec3d(v.no) else: normal = no if faceUV: uvcoord = rvec2d((uv[j][0], 1.0 - uv[j][1])) elif vertexUV: uvcoord = rvec2d((v.uvco[0], 1.0 - v.uvco[1])) if vertexColors: color = col[j].r, col[j].g, col[j].b file.write('%d ' % vdict[v.index][normal, uvcoord, color]) file.write('\n') file.close() if is_editmode: Blender.Window.EditMode(1, '', 0)
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # ***** END GPL LICENCE BLOCK ***** # -------------------------------------------------------------------------- from Blender import Draw, Geometry, Mathutils, Window import bpy GLOBALS = {} GLOBALS['GROUND_SOURCE'] = [Draw.Create(1), Draw.Create(0)] GLOBALS['GROUND_GROUP_NAME'] = Draw.Create('terrain') GLOBALS['DROP_AXIS'] = [Draw.Create(1), Draw.Create(0)] # on what axis will we drop? GLOBALS['DROP_OVERLAP_CHECK'] = Draw.Create(1) # is the terrain a single skin? GLOBALS['EVENT'] = 2 GLOBALS['MOUSE'] = None def collect_terrain_triangles(obs_terrain): terrain_tris = [] me = bpy.data.meshes.new() for ob in obs_terrain: # this matrix takes the object and drop matrix into account ob_mat = ob.matrixWorld # * drop_matrix
from Blender import Window import bpy from Blender.Mathutils import * import blender2obj from Blender import Types from Blender import Scene from Blender.Scene import Render basePath = 'base.obj' pairsPath = 'base.sym' centersPath = 'base.sym.centers' windowEditMode = Blender.Window.EditMode() GUIswitch = 1 objToCOnvertPath = None morphFactor = Draw.Create(1.0) regulFactor = Draw.Create(0.005) saveOnlySelectedVerts = Draw.Create(0) rotationMode = Draw.Create(0) fitVert1 = Draw.Create("head_vertices.dat") fitVert2 = Draw.Create("verts_to_fit.verts") fitVert3 = Draw.Create("head2_vertices.dat") poseMode = False loadedTraslTarget = "" loadedRotTarget = "" loadedPoseTarget = "" targetBuffer = [] #Loaded target Data message = "" targetVertexList = None targetVertexLookup = None
def write_ui(filename): if not filename.lower().endswith('.eolarm'): filename += '.eolarm' if not BPyMessages.Warning_SaveOver(filename): return EXPORT_ARMATURE = Draw.Create(1) # removed too many options are bad! # Get USER Options pup_block = [\ ('Context...'),\ ('Armature', EXPORT_ARMATURE, 'Export Armature'),\ ] if not Draw.PupBlock('Export...', pup_block): return Window.EditMode(0) Window.WaitCursor(1) 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() 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') # Export an animation? scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. for frame in scene_frames: Blender.Set('curframe', frame) export_objects = scn.objects.context 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) Blender.Set('curframe', orig_frame) # Restore old active scene. orig_scene.makeCurrent() Window.WaitCursor(0)
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 file_callback(filename): if not filename.lower().endswith('.ctm'): filename += '.ctm' # Get object mesh from the selected object scn = bpy.data.scenes.active ob = scn.objects.active if not ob: Blender.Draw.PupMenu('Error%t|Select 1 active object') return mesh = BPyMesh.getMeshFromObject(ob, None, False, False, scn) if not mesh: Blender.Draw.PupMenu( 'Error%t|Could not get mesh data from active object') return # Check which mesh properties are present... hasVertexUV = mesh.vertexUV or mesh.faceUV hasVertexColors = mesh.vertexColors # Show a GUI for the export settings pupBlock = [] EXPORT_APPLY_MODIFIERS = Draw.Create(1) pupBlock.append(('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.')) EXPORT_NORMALS = Draw.Create(1) pupBlock.append(('Normals', EXPORT_NORMALS, 'Export vertex normal data.')) if hasVertexUV: EXPORT_UV = Draw.Create(1) pupBlock.append(('UVs', EXPORT_UV, 'Export texface UV coords.')) if hasVertexColors: EXPORT_COLORS = Draw.Create(1) pupBlock.append(('Colors', EXPORT_COLORS, 'Export vertex Colors.')) EXPORT_MG2 = Draw.Create(0) pupBlock.append( ('Fixed Point', EXPORT_MG2, 'Use limited precision algorithm (MG2 method = better compression).')) if not Draw.PupBlock('Export...', pupBlock): return # Adjust export settings according to GUI selections EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val EXPORT_NORMALS = EXPORT_NORMALS.val if hasVertexUV: EXPORT_UV = EXPORT_UV.val else: EXPORT_UV = False if hasVertexColors: EXPORT_COLORS = EXPORT_COLORS.val else: EXPORT_COLORS = False EXPORT_MG2 = EXPORT_MG2.val # If the user wants to export MG2, then show another GUI... if EXPORT_MG2: pupBlock = [] EXPORT_VPREC = Draw.Create(0.01) pupBlock.append(('Vertex', EXPORT_VPREC, 0.0001, 1.0, 'Relative vertex precision (fixed point).')) if EXPORT_NORMALS: EXPORT_NPREC = Draw.Create(1.0 / 256.0) pupBlock.append(('Normal', EXPORT_NPREC, 0.0001, 1.0, 'Normal precision (fixed point).')) if EXPORT_UV: EXPORT_UVPREC = Draw.Create(1.0 / 1024.0) pupBlock.append(('UV', EXPORT_UVPREC, 0.0001, 1.0, 'UV precision (fixed point).')) if EXPORT_COLORS: EXPORT_CPREC = Draw.Create(1.0 / 256.0) pupBlock.append(('Color', EXPORT_CPREC, 0.0001, 1.0, 'Color precision (fixed point).')) if not Draw.PupBlock('Fixed point precision...', pupBlock): return # Adjust export settings according to GUI selections if EXPORT_MG2: EXPORT_VPREC = EXPORT_VPREC.val else: EXPORT_VPREC = 0.1 if EXPORT_MG2 and EXPORT_NORMALS: EXPORT_NPREC = EXPORT_NPREC.val else: EXPORT_NPREC = 0.1 if EXPORT_MG2 and EXPORT_UV: EXPORT_UVPREC = EXPORT_UVPREC.val else: EXPORT_UVPREC = 0.1 if EXPORT_MG2 and EXPORT_COLORS: EXPORT_CPREC = EXPORT_CPREC.val else: EXPORT_CPREC = 0.1 is_editmode = Blender.Window.EditMode() if is_editmode: Blender.Window.EditMode(0, '', 0) Window.WaitCursor(1) try: # Get the mesh, again, if we wanted modifiers (from GUI selection) if EXPORT_APPLY_MODIFIERS: mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn) if not mesh: Blender.Draw.PupMenu( 'Error%t|Could not get mesh data from active object') return mesh.transform(ob.matrixWorld, True) # Count triangles (quads count as two triangles) triangleCount = 0 for f in mesh.faces: if len(f.v) == 4: triangleCount += 2 else: triangleCount += 1 # Extract indices from the Blender mesh (quads are split into two triangles) pindices = cast((c_int * 3 * triangleCount)(), POINTER(c_int)) i = 0 for f in mesh.faces: pindices[i] = c_int(f.v[0].index) pindices[i + 1] = c_int(f.v[1].index) pindices[i + 2] = c_int(f.v[2].index) i += 3 if len(f.v) == 4: pindices[i] = c_int(f.v[0].index) pindices[i + 1] = c_int(f.v[2].index) pindices[i + 2] = c_int(f.v[3].index) i += 3 # Extract vertex array from the Blender mesh vertexCount = len(mesh.verts) pvertices = cast((c_float * 3 * vertexCount)(), POINTER(c_float)) i = 0 for v in mesh.verts: pvertices[i] = c_float(v.co.x) pvertices[i + 1] = c_float(v.co.y) pvertices[i + 2] = c_float(v.co.z) i += 3 # Extract normals if EXPORT_NORMALS: pnormals = cast((c_float * 3 * vertexCount)(), POINTER(c_float)) i = 0 for v in mesh.verts: pnormals[i] = c_float(v.no.x) pnormals[i + 1] = c_float(v.no.y) pnormals[i + 2] = c_float(v.no.z) i += 3 else: pnormals = POINTER(c_float)() # Extract UVs if EXPORT_UV: ptexCoords = cast((c_float * 2 * vertexCount)(), POINTER(c_float)) if mesh.faceUV: for f in mesh.faces: for j, v in enumerate(f.v): k = v.index if k < vertexCount: uv = f.uv[j] ptexCoords[k * 2] = uv[0] ptexCoords[k * 2 + 1] = uv[1] else: i = 0 for v in mesh.verts: ptexCoords[i] = c_float(v.uvco[0]) ptexCoords[i + 1] = c_float(v.uvco[1]) i += 2 else: ptexCoords = POINTER(c_float)() # Extract colors if EXPORT_COLORS: pcolors = cast((c_float * 4 * vertexCount)(), POINTER(c_float)) for f in mesh.faces: for j, v in enumerate(f.v): k = v.index if k < vertexCount: col = f.col[j] pcolors[k * 4] = col.r / 255.0 pcolors[k * 4 + 1] = col.g / 255.0 pcolors[k * 4 + 2] = col.b / 255.0 pcolors[k * 4 + 3] = 1.0 else: pcolors = POINTER(c_float)() # Load the OpenCTM shared library if os.name == 'nt': libHDL = WinDLL('openctm.dll') else: libName = find_library('openctm') if not libName: Blender.Draw.PupMenu( 'Could not find the OpenCTM shared library') return libHDL = CDLL(libName) if not libHDL: Blender.Draw.PupMenu('Could not open the OpenCTM shared library') return # Get all the functions from the shared library that we need ctmNewContext = libHDL.ctmNewContext ctmNewContext.argtypes = [c_int] ctmNewContext.restype = c_void_p ctmFreeContext = libHDL.ctmFreeContext ctmFreeContext.argtypes = [c_void_p] ctmGetError = libHDL.ctmGetError ctmGetError.argtypes = [c_void_p] ctmGetError.restype = c_int ctmErrorString = libHDL.ctmErrorString ctmErrorString.argtypes = [c_int] ctmErrorString.restype = c_char_p ctmFileComment = libHDL.ctmFileComment ctmFileComment.argtypes = [c_void_p, c_char_p] ctmDefineMesh = libHDL.ctmDefineMesh ctmDefineMesh.argtypes = [ c_void_p, POINTER(c_float), c_int, POINTER(c_int), c_int, POINTER(c_float) ] ctmSave = libHDL.ctmSave ctmSave.argtypes = [c_void_p, c_char_p] ctmAddUVMap = libHDL.ctmAddUVMap ctmAddUVMap.argtypes = [c_void_p, POINTER(c_float), c_char_p, c_char_p] ctmAddUVMap.restype = c_int ctmAddAttribMap = libHDL.ctmAddAttribMap ctmAddAttribMap.argtypes = [c_void_p, POINTER(c_float), c_char_p] ctmAddAttribMap.restype = c_int ctmCompressionMethod = libHDL.ctmCompressionMethod ctmCompressionMethod.argtypes = [c_void_p, c_int] ctmVertexPrecisionRel = libHDL.ctmVertexPrecisionRel ctmVertexPrecisionRel.argtypes = [c_void_p, c_float] ctmNormalPrecision = libHDL.ctmNormalPrecision ctmNormalPrecision.argtypes = [c_void_p, c_float] ctmUVCoordPrecision = libHDL.ctmUVCoordPrecision ctmUVCoordPrecision.argtypes = [c_void_p, c_int, c_float] ctmAttribPrecision = libHDL.ctmAttribPrecision ctmAttribPrecision.argtypes = [c_void_p, c_int, c_float] # Create an OpenCTM context ctm = ctmNewContext(0x0102) # CTM_EXPORT try: # Set the file comment ctmFileComment( ctm, c_char_p('%s - created by Blender %s (www.blender.org)' % (ob.getName(), Blender.Get('version')))) # Define the mesh ctmDefineMesh(ctm, pvertices, c_int(vertexCount), pindices, c_int(triangleCount), pnormals) # Add UV coordinates? if EXPORT_UV: tm = ctmAddUVMap(ctm, ptexCoords, c_char_p(), c_char_p()) if EXPORT_MG2: ctmUVCoordPrecision(ctm, tm, EXPORT_UVPREC) # Add colors? if EXPORT_COLORS: cm = ctmAddAttribMap(ctm, pcolors, c_char_p('Color')) if EXPORT_MG2: ctmAttribPrecision(ctm, cm, EXPORT_CPREC) # Set compression method if EXPORT_MG2: ctmCompressionMethod(ctm, 0x0203) # CTM_METHOD_MG2 ctmVertexPrecisionRel(ctm, EXPORT_VPREC) if EXPORT_NORMALS: ctmNormalPrecision(ctm, EXPORT_NPREC) else: ctmCompressionMethod(ctm, 0x0202) # CTM_METHOD_MG1 # Save the file ctmSave(ctm, c_char_p(filename)) # Check for errors e = ctmGetError(ctm) if e != 0: s = ctmErrorString(e) Blender.Draw.PupMenu('Error%t|Could not save the file: ' + s) finally: # Free the OpenCTM context ctmFreeContext(ctm) finally: Window.WaitCursor(0) if is_editmode: Blender.Window.EditMode(1, '', 0)
CAMString = "" OUTPUTString = "" MESHString = os.path.join(mesh_folder,"Male.obj") no_action, ASFBUTTON, AMCBUTTON, AMC2BUTTON,\ AMC3BUTTON, AMC4BUTTON, AMC5BUTTON,\ MESHMENU, OUTERJOINTSBUTTON, STITCHBUTTON,\ CameraAutomaticButton, CameraManualButton,\ CamSelectButton, CameraNumberButton, CameraImportButton,\ CameraExportButton, CameraLatitudeButton, CameraOntopButton,\ CameraRadiusButton, CameraOntopLatitudeButton,\ OutputButton, RenderButton, SimulationButton,\ origFpsButton, outputFpsButton = range(25) Camera_Setup_Selection = {'Automatic setup': [Draw.Create(1),CameraAutomaticButton,'Automatic setup'], 'Pre-saved setup': [Draw.Create(0),CameraManualButton,'Pre-saved setup']} ASF_button = Draw.Create(0) AMC_button = Draw.Create(0) AMC2_button = Draw.Create(0) AMC3_button = Draw.Create(0) AMC4_button = Draw.Create(0) AMC5_button = Draw.Create(0) MESH_menu = Draw.Create(1) OUTERJOINTS_toggle = Draw.Create(0) num_motions_button = Draw.Create(1) motion_transition_button = Draw.Create(120)
elif evt == Draw.RIGHTCTRLKEY: r_ctrl_key_pressed = val elif evt == Draw.RETKEY and val and (l_ctrl_key_pressed or r_ctrl_key_pressed): begin_export() l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def button_events(evt): if evt == 0: Draw.Exit() elif evt == 1: begin_export() elif evt == 0x11: Blender.Window.FileSelector(set_gmdc_filename, 'Select', Blender.sys.makename(ext='.gmdc')) #------------------------------------------------------------------------------- # set default values for GUI elements and run event loop str_gmdc_filename = Draw.Create("") str_resource_name = Draw.Create("") btn_name_suffix = Draw.Create(1) btn_export_rigging = Draw.Create(0) btn_export_tangents = Draw.Create(0) btn_export_bmesh = Draw.Create(0) btn_save_log = Draw.Create(0) btn_use_obj_props = Draw.Create(0) menu_export_morphs = Draw.Create(0) str_bmesh_name = Draw.Create("b_mesh") Draw.Register(draw_gui, event_handler, button_events)
def write_ui(filename): if not filename.lower().endswith('.eolmesh'): filename += '.eolmesh' if not BPyMessages.Warning_SaveOver(filename): return EXPORT_APPLY_MODIFIERS = Draw.Create(0) EXPORT_ROTX90 = Draw.Create(0) EXPORT_SEL_ONLY = 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.'),\ ('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'),\ ] if not Draw.PupBlock('Export...', pup_block): return Window.EditMode(0) Window.WaitCursor(1) EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val EXPORT_ROTX90 = EXPORT_ROTX90.val EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.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() 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') # Export an animation? scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. for frame in scene_frames: 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_APPLY_MODIFIERS,\ EXPORT_ROTX90) Blender.Set('curframe', orig_frame) # Restore old active scene. orig_scene.makeCurrent() Window.WaitCursor(0)
def deform2rvk(): POSSMOD_list=['EDGESPLIT', 'DECIMATE', 'SUBSURF', 'BOOLEAN', 'BUILD', 'MIRROR', 'ARRAY'] AUTHMOD_list=['LATTICE', 'CURVE', 'WAVE', 'ARMATURE'] MODIFIERS=0 BMOD=[['Possible Modifiers'], ['Allowed Modifiers']] # ================================================================= # at leat 2 objects =============================================== # ================================================================= if len(Object.GetSelected())>1 : RVK1=Object.GetSelected()[0] RVK2=Object.GetSelected()[1] # ============================================================= # must be 2 meshes ============================================ # ============================================================= if RVK1.getType()=='Mesh' and RVK2.getType()=='Mesh': FRAME=Blender.Get('curframe') DATA2=RVK2.getData() if DEBUG: print DATA2.getKey() # ============================================================ # at least the second must have a shape key ================== # ============================================================ if DATA2.getKey(): # ====================================================== # in case of modifiers use ============================= # ====================================================== if RVK1.modifiers: MODIFIERS=1 POSSMOD=[Value(t) for t in POSSMOD_list] AUTHMOD=[Value(t) for t in AUTHMOD_list] if DEBUG: print 'POSSMOD:',POSSMOD,'\nAUTHMOD:', AUTHMOD MODRVK1=RVK1.modifiers block = [] # =================================================== # === Bloc Menu Modifiers ===1 doc ================= # =================================================== m=0 for mod in MODRVK1: if DEBUG: print mod.type if mod.type in POSSMOD: BMOD[0].append([Draw.Create(0),mod.type, m, POSSMOD_list[POSSMOD.index(mod.type)], mod[Modifier.Settings.RENDER]==1, mod[Modifier.Settings.EDITMODE]==1 ]) elif mod.type in AUTHMOD: BMOD[1].append([Draw.Create(1), mod.type, m, AUTHMOD_list[AUTHMOD.index(mod.type)], mod[Modifier.Settings.RENDER]==1, mod[Modifier.Settings.EDITMODE]==1 ]) m+=1 # =================================================== # === Bloc Menu Modifiers ===2 display ============= # =================================================== block.append(BMOD[1][0]) for B in BMOD[1][1:]: block.append((B[3],B[0],"")) block.append(BMOD[0][0]) block.append("not alredy implemented") block.append("in this script.") for B in BMOD[0][1:]: block.append((B[3],B[0],"")) retval = Blender.Draw.PupBlock("MESH 2 RVK", block) # =================================================== # === unset Modifiers ============================= # =================================================== for B in BMOD[0][1:]: if DEBUG: print B[2] MODRVK1[B[2]][Modifier.Settings.RENDER]=0 for B in BMOD[1]: if not B[1]: MODRVK1[B[2]][Modifier.Settings.RENDER]=0 # =================================================== # === update Modifiers ============================= # =================================================== #RVK1.makeDisplayList() # ======================================================= # === get deformed mesh ================================ # ======================================================= RVK1NAME=Object.GetSelected()[0].getName() meshrvk1=NMesh.GetRawFromObject(RVK1NAME) if DEBUG: print len(meshrvk1.verts) # ======================================================= # === get normal mesh for vertex group ================= # ======================================================= DATA1=RVK1.getData() # ======================================================= # === get destination mesh ============================ # ======================================================= DATA2=RVK2.getData() if DEBUG: print len(meshrvk1.verts) if DEBUG: print len(DATA2.verts) # ======================================================== # ===== is there the same number of vertices ============= # ======================================================== if len(meshrvk1.verts)==len(DATA2.verts): name = "Do you want to replace or add vertex groups ? %t| YES %x1| NO ? %x2 " result = Draw.PupMenu(name) if result==1: # ===================================================== # ===== Do we save vertex groups ? =================== # ===================================================== GROUPNAME2=DATA2.getVertGroupNames() if len(GROUPNAME2)!=0: for GROUP2 in GROUPNAME2: DATA2.removeVertGroup(GROUP2) GROUPNAME1=DATA1.getVertGroupNames() if len(GROUPNAME1)!=0: for GROUP1 in GROUPNAME1: DATA2.addVertGroup(GROUP1) DATA2.assignVertsToGroup(GROUP1,DATA1.getVertsFromGroup(GROUP1),1.0,'replace') # ======================================================== # ===== now copy the vertices coords ===================== # ======================================================== for v in meshrvk1.verts: i= meshrvk1.verts.index(v) v1=DATA2.verts[i] for n in [0,1,2]: v1.co[n]=v.co[n] DATA2.update() DATA2.insertKey(FRAME,'relative') DATA2.update() RVK2.makeDisplayList() if MODIFIERS: # =================================================== # === unset Modifiers ============================= # =================================================== for B in BMOD[0][1:]: MODRVK1[B[2]][Modifier.Settings.RENDER]|=B[-2] for B in BMOD[1]: if not B[1]: MODRVK1[B[2]][Modifier.Settings.RENDER]|=B[-2] else: name = "Meshes Objects must the same number of vertices %t| Ok. %x1" result = Draw.PupMenu(name) return else: name = "Second Object must have at least a shape key %t| Ok. %x1" result = Draw.PupMenu(name) return else: name = "Object must be Meshes %t| Ok. %x1" result = Draw.PupMenu(name) return else : name = "At least 2 Meshes as to be selected %t| Ok. %x1" result = Draw.PupMenu(name) return Blender.Redraw()
r_ctrl_key_pressed = val elif evt == Draw.RETKEY and val and (l_ctrl_key_pressed or r_ctrl_key_pressed): begin_import() l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def button_events(evt): if evt == 0: Draw.Exit() elif evt == 1: begin_import() elif evt == 0x11: Blender.Window.FileSelector(set_gmdc_filename, 'Select') elif evt == 0x21: Blender.Window.FileSelector(set_cres_filename, 'Select') #------------------------------------------------------------------------------- # set default values for gui elements and run event loop str_gmdc_filename = Draw.Create("") str_cres_filename = Draw.Create("") btn_import_bmesh = Draw.Create(0) btn_remove_doubles = Draw.Create(1) btn_all_bones = Draw.Create(0) btn_save_log = Draw.Create(0) Draw.Register(draw_gui, event_handler, button_events)
#triangulate: go into edit mode, select all faces and press ctrl+t from Blender import Scene, Mesh, Window, Get, sys, Image, Draw import BPyMessages import bpy import math from math import * from Blender.BGL import * EVENT_NOEVENT = 1 EVENT_DRAW = 2 EVENT_EXIT = 3 EVENT_EXPORT = 4 EVENT_BROWSEFILE = 5 as_package_name = Draw.Create("") as_output_string = "" as_filename = "" fileButton = Draw.Create("") engine_menu = Draw.Create(1) export_all = None def export_papervision(me, class_name): as_output_string = "package " + as_package_name.val + " {\n" as_output_string += "\timport org.papervision3d.core.*;\n" as_output_string += "\timport org.papervision3d.materials.*;\n" as_output_string += "\timport org.papervision3d.core.proto.*;\n" as_output_string += "\timport org.papervision3d.core.geom.*;\n\n" as_output_string += "\tpublic class " + class_name + " extends Mesh3D {\n" as_output_string += "\t\tprivate var ve:Array;\n"
from Blender import BGL from Blender.Window import Theme # globals: START_SCREEN = 0 SCRIPT_SCREEN = 1 SCREEN = START_SCREEN # gui buttons: len_gmenus = len(GROUP_MENUS) BUT_GMENU = range(len_gmenus) for i in range(len_gmenus): BUT_GMENU[i] = Draw.Create(0) # events: BEVT_LINK = None # range(len(SCRIPT_INFO.links)) BEVT_EMAIL = None # range(len(SCRIPT_INFO.emails)) BEVT_GMENU = range(100, len_gmenus + 100) BEVT_VIEWSOURCE = 1 BEVT_EXIT = 2 BEVT_BACK = 3 # gui callbacks: def gui(): # drawing the screen global SCREEN, START_SCREEN, SCRIPT_SCREEN