Exemplo n.º 1
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"
Exemplo n.º 2
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()
Exemplo n.º 3
0
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()
Exemplo n.º 4
0
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
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
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 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()
Exemplo n.º 8
0
 def DeselectAllObjects():
 	for object in Object.GetSelected(): object.select(0)
Exemplo n.º 9
0
        def select_modifier(RVK1, RVK2, DATA2):
            # ======================================================
            # 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 RVK1.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 have the same number of vertices %t|Ok. %x1"
                result = Draw.PupMenu(name)
                return
Exemplo n.º 10
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()
the occupied in the original file, so you may no notice anything till you turn that
layers on.

It can also be used in a single instance (ie: first open the file with object, copy,
open the destination blend, paste)

Save the .blend containing the objects you want to copy first, even if it already has
a filename, only saved objects can be copied (if you had altered something, then save).
"""

import Blender
from Blender import Draw, Text, Library, Object

choice = Draw.PupMenu("Copy object(s) to buffer|Paste object(s) from buffer")
if choice == 1:
    objs = Object.GetSelected()
    if len(objs) == 0:
        Draw.PupMenu("Please select at least 1 object!")
    else:
        txt = open(Blender.Get("datadir") + "/buffer", "w")
        txt.write(Blender.Get("filename") + "\n")
        for item in objs:
            txt.write(item.getName() + "\n")
        txt.close()
elif choice == 2:
    txt = Text.Load(Blender.Get("datadir") + "/buffer")
    buffer = txt.asLines()
    Library.Open(buffer[0])
    buffer.pop(0)
    for item in buffer:
        Library.Load(item, "Object", 0)
Exemplo n.º 12
0
def renderGUI():
    """
	Renders the GUI for the script.
	"""

    global G

    # find the selection set and update some selection
    #  related flags
    haveEmpty = False
    haveCamera = False
    emptyName = ""
    G.selection = Object.GetSelected()
    G.curempty = None
    if G.selection is not None and len(G.selection) > 0:
        mso = G.selection[0]
        msotype = mso.getType()
        if msotype == 'Empty':
            haveEmpty = True
            G.curempty = mso
            emptyName = G.curempty.getName()
        elif msotype == 'Camera':
            haveCamera = True
    emptyHasCoords = G.coordmap.has_key(emptyName)
    removeUnknownsFromCoords()

    # clear any buttons that need to have set states
    G.buttons.add = G.buttons.delete = None

    # clear the window
    c = COLOR_BACKGROUND
    BGL.glClearColor(c[0], c[1], c[2], c[3])
    BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)

    # paint the image in the background
    if G.image is not None:
        #drawImage(G.image, G.imgpos, G.iw, G.ih, G.zoom)
        Draw.Image(G.image, G.imgpos[0], G.imgpos[1], G.zoom, G.zoom)
    # paint 2D vertices in the image
    BGL.glPushAttrib(BGL.GL_POINT_BIT | BGL.GL_CURRENT_BIT)
    BGL.glPointSize(POINT_SIZE)
    x0 = int(G.imgpos[0] / G.zoom)
    y0 = int(G.imgpos[1] / G.zoom)

    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))

    BGL.glBegin(BGL.GL_POINTS)
    map(drawvc, G.coordmap.items())
    BGL.glEnd()
    BGL.glPopAttrib()

    # if we're in add mode then draw some extra stuff
    if G.mode == MODE_ADD:

        xm, ym = map(int, getWMCoords())
        xm -= 10
        ym += 10
        (xw, yw, ww, hw) = getWinRect()

        # draw crosshairs
        c = COLOR_CROSSHAIRS
        BGL.glColor4f(c[0], c[1], c[2], c[3])
        verts = [(xm, 0), (xm, hw), (0, ym), (ww, ym)]
        BGL.glBegin(BGL.GL_LINES)
        map(lambda x: BGL.glVertex2d(x[0], x[1]), verts)
        BGL.glEnd()

        #############################################
        # UNCOMMENT THIS SECTION FOR A COOL MINIMAP
        # EFFECT - NOT VERY USEFUL THOUGH
        #
        ## draw "minimap" background
        #c = COLOR_MINIMAP
        #BGL.glColor4f(c[0], c[1], c[2], c[3])
        #verts = [ (119,10), (221,10), (221,111), (119,111) ]
        #BGL.glBegin(BGL.GL_QUADS)
        #map(lambda x: BGL.glVertex2i(x[0],x[1]), verts)
        #BGL.glEnd()
        #
        ## paint the image into the minimap
        #ix,iy = wc2ic((xm,ym))
        #ix,iy = map(int, [ix, iy])
        #drawImage(G.ibuf, (120,10), G.iw, G.ih, 10.0, (ix-5,iy-5,10,10))
        #
        # END OF MINIMAP SECTION
        #############################################

    # paint the current empty name
    if haveEmpty:
        c = COLOR_TEXT
        BGL.glColor4d(c[0], c[1], c[2], c[3])
        BGL.glRasterPos2i(220, 10)
        Draw.Text(emptyName, 'small')

    # paint the normal GUI buttons
    G.buttons.quit = Draw.PushButton('Quit', BUTTON_QUIT, 5, 5, 100, 20,
                                     'Exits the script.')
    G.buttons.load = Draw.PushButton('Load Image', BUTTON_LOAD, 5, 25, 100, 20,
                                     'Loads an image.')
    G.buttons.zoom = Draw.Number('Zoom', BUTTON_ZOOM, 5, 45, 100, 20, G.zoom,
                                 ZOOM_MIN, ZOOM_MAX, 'Adjusts image zoom.')

    # paint camera-specific stuff
    if haveCamera:
        G.buttons.fullopt = Draw.Toggle('Full Optimization', BUTTON_FULLOPT,
                                        110, 5, 120, 20, G.fullopt,
                                        'Full or partial optimization.')
        G.buttons.coplanar = Draw.Toggle('Coplanar', BUTTON_COPLANAR, 110, 25,
                                         120, 20, G.coplanar,
                                         'Coplanar or non-coplanar target.')
        # Origin offset is not currently working in the Tsai module.
        #  It should be brought back here when it is.
        #G.buttons.ofsz      = Draw.Number('OfsZ', BUTTON_OFSZ, 110, 50, 100, 20, G.ofsz, OFS_MIN, OFS_MAX, 'Z origin offset.')
        #G.buttons.ofsy      = Draw.Number('OfsY', BUTTON_OFSY, 110, 70, 100, 20, G.ofsy, OFS_MIN, OFS_MAX, 'Y origin offset.')
        #G.buttons.ofsx      = Draw.Number('OfsX', BUTTON_OFSX, 110, 90, 100, 20, G.ofsx, OFS_MIN, OFS_MAX, 'X origin offset.')
        G.buttons.calibrate = Draw.PushButton(
            'Calibrate', BUTTON_CALIBRATE, 235, 5, 100, 20,
            'Calibrates the selected camera.')

    # paint empty-specific stuff
    elif haveEmpty and (G.mode == MODE_NORMAL):
        if emptyHasCoords:
            G.buttons.delete = Draw.PushButton(
                'Delete', BUTTON_DELETE, 110, 5, 100, 20,
                'Adds an image calibration coordinate.')
        else:
            G.buttons.add = Draw.PushButton(
                'Add', BUTTON_ADD, 110, 5, 100, 20,
                'Removes an image calibration coordinate.')
Exemplo n.º 13
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)
Exemplo n.º 14
0
def main():
    print '\nStarting BoneWeight Copy...'
    scn = Blender.Scene.GetCurrent()
    contextSel = Object.GetSelected()
    if not contextSel:
        Blender.Draw.PupMenu(
            'Error%t|2 or more mesh objects need to be selected.|aborting.')
        return

    PREF_QUALITY = Blender.Draw.Create(0)
    PREF_NO_XCROSS = Blender.Draw.Create(0)
    PREF_SEL_ONLY = Blender.Draw.Create(0)

    pup_block = [\
    ('Quality:', PREF_QUALITY, 0, 4, 'Generate interpolated verts for a higher quality result.'),\
    ('No X Crossing', PREF_NO_XCROSS, 'Do not snap across the zero X axis'),\
    '',\
    '"Update Selected" copies',\
    'active object weights to',\
    'selected verts on the other',\
    'selected mesh objects.',\
    ('Update Selected', PREF_SEL_ONLY, 'Only copy new weights to selected verts on the target mesh. (use active object as source)'),\
    ]

    if not Blender.Draw.PupBlock("Copy Weights for %i Meshs" % len(contextSel),
                                 pup_block):
        return

    PREF_SEL_ONLY = PREF_SEL_ONLY.val
    PREF_NO_XCROSS = PREF_NO_XCROSS.val
    quality = PREF_QUALITY.val

    act_ob = scn.objects.active
    if PREF_SEL_ONLY and act_ob == None:
        Blender.Draw.PupMenu(
            'Error%t|When dealing with 2 or more meshes with vgroups|There must be an active object|to be used as a source|aborting.'
        )
        return

    sel = []
    from_data = None

    for ob in contextSel:
        if ob.type == 'Mesh':
            me = ob.getData(mesh=1)
            groups = me.getVertGroupNames()

            # If this is the only mesh with a group OR if its one of many, but its active.
            if groups and ((ob == act_ob and PREF_SEL_ONLY) or
                           (not PREF_SEL_ONLY)):
                if from_data:
                    Blender.Draw.PupMenu(
                        'More then 1 mesh has vertex weights, only select 1 mesh with weights. aborting.'
                    )
                    return
                else:
                    # This uses worldspace_verts_idx which gets (idx,co) pairs, then zsorts.
                    if quality:
                        for _ob in contextSel:
                            _ob.sel = 0
                        ob.sel = 1
                        Object.Duplicate(mesh=1)
                        ob = scn.objects.active
                        me = ob.getData(mesh=1)
                        # groups will be the same
                        print '\tGenerating higher %ix quality weights.' % quality
                        subdivMesh(me, quality)
                        scn.unlink(ob)
                    from_data = (ob, me, worldspace_verts_idx(me, ob), groups)

            else:
                data = (ob, me, worldspace_verts(me, ob), groups)
                sel.append(data)

    if not from_data:
        Blender.Draw.PupMenu('Error%t|No mesh with vertex groups found.')
        return

    if not sel:
        Blender.Draw.PupMenu(
            'Error%t|Select 2 or more mesh objects, aborting.')
        if quality: from_data[1].verts = None
        return

    t = Blender.sys.time()
    Window.WaitCursor(1)

    # Now do the copy.
    print '\tCopying from "%s" to %i other mesh(es).' % (from_data[0].name,
                                                         len(sel))
    for data in sel:
        copy_bone_influences(from_data, data, PREF_SEL_ONLY, PREF_NO_XCROSS)

    # We cant unlink the mesh, but at least remove its data.
    if quality:
        from_data[1].verts = None

    print 'Copy Complete in %.6f sec' % (Blender.sys.time() - t)
    Window.DrawProgressBar(1.0, '')
    Window.WaitCursor(0)
Exemplo n.º 15
0
def exportMesh(obj, file, loc, size, quat):
    mesh = NMesh.GetRawFromObject(obj.getName())

    indent(file)
    file.write("<Mesh name=\"%s\" numVertices=\"%d\" numFaces=\"%d\" " %
               (obj.getName(), len(mesh.verts), len(mesh.faces)))
    file.write("x=\"%3.5f\" y=\"%3.5f\" z=\"%3.5f\" " %
               (loc[0], loc[2], -loc[1]))
    file.write("sx=\"%3.5f\" sy=\"%3.5f\" sz=\"%3.5f\" " %
               (size[0], size[1], size[2]))
    file.write("qw=\"%3.5f\" qx=\"%3.5f\" qy=\"%3.5f\" qz=\"%3.5f\"" %
               (quat[0], quat[1], quat[2], quat[3]))
    file.write(">\n")
    setIndent(1)

    for mat in mesh.materials:
        exportMaterial(mat, file)
    if len(mesh.materials) > 0:
        file.write("\n")

    textures = []
    if mesh.hasFaceUV():
        for face in mesh.faces:
            if not face.image:
                continue

            if textures.count(face.image) == 0:
                textures.append(face.image)

    for tex in textures:
        exportTexture(tex, file)
    if len(textures) > 0:
        file.write("\n")

    for vert in mesh.verts:
        indent(file)
        file.write("<Vertex x=\"%3.5f\" y=\"%3.5f\" z=\"%3.5f\" " %
                   (vert.co[0], vert.co[2], -vert.co[1]))
        file.write("nx=\"%3.5f\" ny=\"%3.5f\" nz=\"%3.5f\"/>\n" %
                   (vert.no[0], vert.no[2], -vert.no[1]))

    file.write("\n")

    for face in mesh.faces:
        indent(file)
        file.write("<Face smooth=\"%d\" " % face.smooth)
        file.write("nx=\"%3.5f\" ny=\"%3.5f\" nz=\"%3.5f\" " %
                   (face.normal[0], face.normal[2], -face.normal[1]))

        if face.image:
            file.write("texture=\"%d\" " % (textures.index(face.image)))
        else:
            file.write("texture=\"-1\" ")

        mat = face.materialIndex
        if mat >= len(mesh.materials):
            mat = -1

        file.write("material=\"%d\">\n" % (mat))

        setIndent(1)
        for i in range(3):
            indent(file)
            file.write("<Vertex index=\"%d\" " % face.v[i].index)

            if mesh.hasFaceUV() and face.image:
                file.write("u=\"%1.3f\" v=\"%1.3f\"" %
                           (face.uv[i][0], 1.0 - face.uv[i][1]))

            file.write("/>\n")

        setIndent(-1)

        #		file.write(" vertex1=\"%d\" vertex2=\"%d\" vertex3=\"%d\"/>\n" %(face.v[0].index, face.v[1].index, face.v[2].index))
        indent(file)
        file.write("</Face>\n")

    Object.GetSelected().remove(obj)
    for child in Object.GetSelected():
        if child.parent == obj:
            export(child, file)
            Object.GetSelected().remove(child)

    setIndent(-1)
    indent(file)
    file.write("</Mesh>\n\n")
Exemplo n.º 16
0
import Blender
import math, sys
from Blender import NMesh, Object, Scene
from math import *

PATH = "/home/carlos/"  # La ruta donde se salvara el OREj
nframes = 50

object = Object.GetSelected()
objname = object[0].name
meshname = object[0].data.name
mesh = NMesh.GetRaw(meshname)

filename = PATH + objname + ".orj"
file = open(filename, "w")
std = sys.stdout  # Asociamos stdout al fichero .orj
sys.stdout = file

print "# Objeto OREj:", objname
print "# Vertices Totales:", len(mesh.verts)
print "# Caras Totales:", len(mesh.faces)

# Escribimos toda la lista de vertices (v x y z)
for vertex in mesh.verts:
    x, y, z = vertex.co
    print "v %f %f %f" % (x, y, z)
# Escribimos toda la lista de caras (f v1 v2 v3 ...)
for face in mesh.faces:
    print "f",
    face.v.reverse()  # Invertimos las normales
    for vertex in face.v:
Exemplo n.º 17
0
def save_opengl(filename):

    # Open file
    f = open(filename + ".c", "w")
    header_file = open(filename + ".h", "w")
    bone_file = open(filename + ".bone", "w")

    print "File %s created and opened. Now exporting..." % filename

    # Write all the preprocessors in the header file required to
    # make it work w/ vbo_Utilities.h :
    header_file.write("#ifndef MODEL_H")
    header_file.write("\n#define MODEL_H")

    header_file.write("\n\n#include <GL/gl.h>")
    header_file.write("\n#include <GL/glu.h>")
    header_file.write("\n\n#include \"Transformation.h\"")
    header_file.write("\n\n#include \"vbo_Utilities.h\"")
    header_file.write("\n\n#include \"bone.h\"")

    header_file.write(
        "\n\n// The following is the list of objects that will be exported :")
    # The actual object names and their estern declarations will be written out in the loop below

    f.write("#include \"%s.h\"\n\n" % filename)

    # Which object to export
    # currently all objects (meshes only - see below)
    objects = [ob for ob in Object.GetSelected() if ob.getType() == 'Mesh']

    obj_index = 0
    for obj in objects:
        nmesh = NMesh.GetRawFromObject(obj.name)

        header_file.write("\n\nextern CVBO_Model %s;" % (nmesh.name))

        f.write("\n// Object: %s" % (nmesh.name))
        f.write("\nCVBO_Model %s;" % (nmesh.name))
        f.write("\n\nvoid make_%s_vbo_arrays () {" % (nmesh.name))

        # Get the list of vertices for the object
        vertices = nmesh.verts[:]

        # Get the list of faces for the object
        faces = nmesh.faces[:]
        # initialize a refCount array for the vertices
        refCount_for_vertices = []
        for idx in range(len(vertices)):
            refCount_for_vertices.append(0)

        # Make one pass through all the faces in the object
        # to identify all the vertices that will have to be split
        # into 2 or more vertices if they have different texture coordinates
        # as part of different faces. Example : vertices along uv-unwrapping_seams.
        # Naturally, this has to be done only if the mesh uses face-UV textures

        if nmesh.hasFaceUV():
            for face in faces:
                for idx in range(len(face.v)):
                    vertex_idx = face.v[idx].index
                    if refCount_for_vertices[vertex_idx] == 0:
                        refCount_for_vertices[vertex_idx] = 1
                        vertices[vertex_idx].uvco.x = face.uv[idx][0]
                        vertices[vertex_idx].uvco.y = face.uv[idx][1]
                    elif face.uv[idx][0] != vertices[
                            vertex_idx].uvco.x or face.uv[idx][1] != vertices[
                                vertex_idx].uvco.y:
                        # get a new temp vert of type MyVert
                        newVert = MyVert(0.0, 0.0, 0.0)

                        refCount_for_vertices.append(1)

                        # Copy over relevant stuff to newVert
                        newVert.co = Co(vertices[vertex_idx].co.x,
                                        vertices[vertex_idx].co.y,
                                        vertices[vertex_idx].co.z)

                        newVert.index = vertices[vertex_idx].index
                        newVert.dup_vertex_index = vertices[vertex_idx].index

                        newVert.no = No(vertices[vertex_idx].no.x,
                                        vertices[vertex_idx].no.y,
                                        vertices[vertex_idx].no.z)

                        newVert.uvco = Uvco(vertices[vertex_idx].uvco.x,
                                            vertices[vertex_idx].uvco.y)

                        # Append it to the list
                        vertices.append(newVert)

                        vertex_idx = len(
                            vertices
                        ) - 1  # new vertex_idx, of the newly appended vertex

                        # Now set the diverged uvco and index at the newly appended vertex
                        vertices[vertex_idx].uvco.x = face.uv[idx][0]
                        vertices[vertex_idx].uvco.y = face.uv[idx][1]
                        vertices[vertex_idx].index = vertex_idx

                        # And, set the face's v to point to this newly appended vertex
                        face.v[idx] = vertices[vertex_idx]

        numVerts = len(vertices)
        f.write("\n\tint numVertices = %d;\n" % numVerts)

        # Write out the list of vertices for the object
        f.write("\n\t// List of vertices for object %s" % (nmesh.name))
        f.write("\n\tGLfloat vertices[] = {")
        for vertex in vertices:
            f.write("\n\t\t%f,\t%f,\t%f,\t1.0000," %
                    (vertex.co.x, vertex.co.y, vertex.co.z))
            f.write("\t\t// index : %d" % (vertex.index))
        f.write("\n\t};")
        f.write(
            "\n\t%s.bulk_init_vertices (numVertices, (vec4 *)vertices);\n\n" %
            (nmesh.name))

        # Write out the texture coordinates for the object
        if nmesh.hasFaceUV():
            f.write("\n\t// List of texture_coords for object %s" %
                    (nmesh.name))
            f.write("\n\tGLfloat textures[] = {")
            for vertex in vertices:
                f.write("\n\t\t%f,\t%f," % (vertex.uvco.x, vertex.uvco.y))
                f.write("\t\t// index : %d" % (vertex.index))
            f.write("\n\t};")
            f.write(
                "\n\t%s.bulk_init_textures (numVertices, (vec2 *)textures);\n\n"
                % (nmesh.name))

        # Write out the normals for the object
        f.write("\n\t// List of normals for object %s" % (nmesh.name))
        f.write("\n\tGLfloat normals[] = {")
        for vertex in vertices:
            f.write("\n\t\t%f,\t%f,\t%f," %
                    (vertex.no.x, vertex.no.y, vertex.no.z))
            f.write("\t\t// index : %d" % (vertex.index))
        f.write("\n\t};")
        f.write(
            "\n\t%s.bulk_init_normals (numVertices, (vec3 *)normals);\n\n" %
            (nmesh.name))

        numFaces = 0
        for face in nmesh.faces:
            numFaces = numFaces + 1
            if len(
                    face.v
            ) == 4:  # , because quads will be exported as 2 triangles (see below)
                numFaces = numFaces + 1
        f.write("\n\tint numFaces = %d;\n" % numFaces)

        # Write out the indices to form each face of the object
        f.write("\n\tGLuint indices[] = {")
        for face in nmesh.faces:
            f.write("\n\t\t")
            f.write("%d, " % face.v[0].index)
            f.write("%d, " % face.v[1].index)
            f.write("%d, " % face.v[2].index)
            if len(face.v) == 4:
                f.write("\n\t\t")
                f.write("%d, " % face.v[3].index)
                f.write("%d, " % face.v[0].index)
                f.write("%d, " % face.v[2].index)
        f.write("\n\t};")
        f.write("\n\t%s.bulk_init_indices (numFaces, (GLuint *)indices);\n\n" %
                (nmesh.name))

        #translation
        locx = 0
        locy = 0
        locz = 0
        if obj.LocX > 0.0001 or obj.LocX < -0.0001:
            locx = obj.LocX
        if obj.LocY > 0.0001 or obj.LocY < -0.0001:
            locy = obj.LocY
        if obj.LocZ > 0.0001 or obj.LocZ < -0.0001:
            locz = obj.LocZ

        f.write("\n\t%s.locX = %f;" % (nmesh.name, locx))
        f.write("\n\t%s.locY = %f;" % (nmesh.name, locy))
        f.write("\n\t%s.locZ = %f;" % (nmesh.name, locz))

        f.write("\n\treturn;")
        f.write("\n}")

        # Bone stuff

        mesh = Mesh.Get(obj.name)
        obj.link(mesh)
        f.write("\n\n// Object : %s " % (mesh.name))

        numRealVerts = len(mesh.verts)

        armatures = Armature.Get()  # type: dict
        armature_names = armatures.keys()
        for armature_name in armature_names:
            f.write("\n// Armature %s, being used by %d users" %
                    (armature_name, armatures[armature_name].users))
            if armatures[
                    armature_name].users > 0:  # being used by at least 1 user (helps discard deleted armatures which are (for some reason) still lying around in Blender)
                armature = armatures[armature_name]
                bones = armature.bones  # type: dict
                bone_names = bones.keys()
                for bone_name in bone_names:  # loop over all bones
                    bone = bones[bone_name]
                    f.write("\n\nBone %s;" % bone.name)
                    header_file.write("\nextern Bone %s;" % bone.name)

                    f.write("\n\nvoid init_%s_bone_influences () {" %
                            bone.name)
                    f.write("\n\tInfluence influences[] = {")

                    num_influences = 0
                    for vertex_idx in range(
                            numVerts
                    ):  # loop over all vertices, looking for The bone's influences
                        # bone_file.write("\nindex : %d " % (vertex_idx))
                        if vertex_idx < numRealVerts:
                            for influence in mesh.getVertexInfluences(
                                    vertex_idx):
                                if influence[0] == bone.name:
                                    # bone_file.write("\n %s, %f" % (influence[0], influence[1]))
                                    f.write("\n\t\tInfluence(%d, %f)," %
                                            (vertex_idx, influence[1]))
                                    num_influences = num_influences + 1
                        elif vertex_idx >= numRealVerts:
                            for influence in mesh.getVertexInfluences(
                                    vertices[vertex_idx].dup_vertex_index):
                                if influence[0] == bone.name:
                                    # bone_file.write("\n %s, %f" % (influence[0], influence[1]))
                                    f.write("\n\t\tInfluence(%d, %f)," %
                                            (vertex_idx, influence[1]))
                                    num_influences = num_influences + 1

                    f.write("\n\t};")
                    f.write("\n\n\t%s.bulkInitInfluences (%d, influences);" %
                            (bone.name, num_influences))
                    f.write("\n\t%s.name = \"%s\";" % (bone.name, bone.name))
                    f.write("\n\n\treturn;")
                    f.write("\n};\n")

        obj_index += 1

    header_file.write("\n\nvoid initialize_all_models ();")
    header_file.write("\nvoid ready_all_models_for_render ();")

    f.write("\n\nvoid initialize_all_models () {")
    for obj in objects:
        nmesh = NMesh.GetRawFromObject(obj.name)
        f.write("\n\n\tmake_%s_vbo_arrays ();" % (nmesh.name))
        f.write("\n\t%s.setTexture (\"./cube_texture_test.png\", PNG);" %
                nmesh.name)
        f.write("\n\t%s.setMatColor (0.2, 0.3, 0.4, 1.0);" % nmesh.name)
        # Bone stuff :
        armatures = Armature.Get()  # type: dict
        armature_names = armatures.keys()
        for armature_name in armature_names:
            if armatures[
                    armature_name].users > 0:  # being used by at least 1 user (helps discard deleted armatures which are (for some reason) still lying around in Blender)
                armature = armatures[armature_name]
                bones = armature.bones  # type: dict
                bone_names = bones.keys()
                for bone_name in bone_names:  # loop over all bones
                    bone = bones[bone_name]
                    f.write("\n\tinit_%s_bone_influences ();" % bone.name)
                    f.write("\n\t%s.setVBO (&%s);" % (bone.name, obj.name))
                    f.write("\n\t%s.addBone (&%s);" % (obj.name, bone.name))

    f.write("\n\n\treturn;\n}\n")

    f.write("\n\nvoid ready_all_models_for_render () {")
    for obj in objects:
        nmesh = NMesh.GetRawFromObject(obj.name)
        f.write("\n\t%s.make_ready_for_render ();" % nmesh.name)
    f.write("\n\n\treturn;\n}\n\n")

    header_file.write("\n\n#endif\n\n")

    print "Export complete"

    f.close()
Exemplo n.º 18
0
def save_opengl(filename):

    ## Open file
    f = open(filename, "w")

    print "File %s created and opened. Now exporting..." % filename

    ## Which object to export
    #currently all objects (meshes only - see below)
    objects = [ob for ob in Object.GetSelected() if ob.getType() == 'Mesh']

    index = 0
    for obj in objects:
        nmesh = NMesh.GetRawFromObject(obj.name)

        f.write("\n\n//object: %s_%d\n" % (nmesh.name, index))

        f.write("function load_%d() {\n" % index)
        index += 1

        #used for materials
        f.write("\tvar matColors=[];\n")

        #transformation data

        #first translate, then rotate, then scale
        # because they are applied from "back to front"

        #we also store the current matrix and restore it
        # after the object is rendered (push, pop)
        f.write("\tgl.PushMatrix();\n")

        #translation

        locx = 0
        locy = 0
        locz = 0
        if obj.LocX > 0.0001 or obj.LocX < -0.0001:
            locx = obj.LocX
        if obj.LocY > 0.0001 or obj.LocY < -0.0001:
            locy = obj.LocY
        if obj.LocZ > 0.0001 or obj.LocZ < -0.0001:
            locz = obj.LocZ

        f.write("\tgl.Translated(%.6f, %.6f, %.6f);\n" % (locx, locy, locz))

        #rotation - this seems to be buggy !?
        if obj.RotX > 0.0001 or obj.RotX < -0.0001:
            f.write("  gl.Rotated(%.6f,1,0,0);\n" %
                    (-obj.RotX * 180 * 0.31831))
        if obj.RotY > 0.0001 or obj.RotY < -0.0001:
            f.write("  gl.Rotated(%.6f,0,1,0);\n" %
                    (-obj.RotY * 180 * 0.31831))
        if obj.RotZ > 0.0001 or obj.RotZ < -0.0001:
            f.write("  gl.Rotated(%.6f,0,0,1);\n" %
                    (-obj.RotZ * 180 * 0.31831))

        #scaling
        f.write("\tgl.Scaled(%.6f, %.6f, %.6f);\n" % tuple(obj.size))

        tricount = 0
        lastMaterialIndex = -1
        for face in nmesh.faces:
            vn = 0
            tricount = tricount + 1

            #material - can be changed between glBegin and glEnd
            if nmesh.materials:
                if face.materialIndex != lastMaterialIndex:
                    lastMaterialIndex = face.materialIndex
                    material = nmesh.materials[face.materialIndex]
                    print "exporting face material"

                    #ambient and diffuse
                    f.write("\tmatColors[0] = %.6f;\n" % material.R)
                    f.write("\tmatColors[1] = %.6f;\n" % material.G)
                    f.write("\tmatColors[2] = %.6f;\n" % material.B)
                    f.write("\tmatColors[3] = %.6f;\n" % material.alpha)
                    f.write(
                        "\tgl.Materialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,matColors);\n"
                    )

                    #specular
                    specs = material.getSpecCol()
                    f.write("\tmatColors[0] = %.6f;\n" % specs[0])
                    f.write("\tmatColors[1] = %.6f;\n" % specs[1])
                    f.write("\tmatColors[2] = %.6f;\n" % specs[2])
                    f.write("\tmatColors[3] = %.6f;\n" %
                            material.getSpecTransp())
                    f.write(
                        "\tgl.Materialfv(GL_FRONT_AND_BACK,GL_SPECULAR,matColors);\n"
                    )

            print "Exporting %s triangle(s)" % tricount

            if len(face) == 3: f.write("\tgl.Begin(GL_TRIANGLES);\n")
            elif len(face) == 4: f.write("\tgl.Begin(GL_QUADS);\n")

            for vertex in face.v:
                ## Build glVertex3f
                f.write("\tgl.Normal3f(%.6f, %.6f, %.6f);\n" %
                        tuple(vertex.no))
                f.write("\tgl.Vertex3f(%.6f, %.6f, %.6f);\n" %
                        tuple(vertex.co))
                vn += 1
            #print "glEnd();"
            f.write("\tgl.End();\n")

        f.write("\tgl.PopMatrix();\n")
        f.write("}\n")

    f.write("\n\n")

    #print "void loadModel() {"
    f.write("function loadModel() {\n")

    index = 0

    for obj in objects:
        f.write("\tload_%d();" % index)
        f.write("\t//object: %s\n" % obj.getData())
        index += 1

    f.write("}\n")

    print "Export complete"

    f.close()