dont use tface hide or select anymore, since maintaining 2 sets of hide/select data...
[blender.git] / release / scripts / x3d_export.py
1 #!BPY
2 """ Registration info for Blender menus:
3 Name: 'X3D Extensible 3D (.x3d)...'
4 Blender: 235
5 Group: 'Export'
6 Submenu: 'All Objects...' all
7 Submenu: 'All Objects compressed...' comp
8 Submenu: 'Selected Objects...' selected
9 Tooltip: 'Export to Extensible 3D file (.x3d)'
10 """
11
12 __author__ = ("Bart")
13 __email__ = ["Bart, bart:neeneenee*de"]
14 __url__ = ["Author's (Bart) homepage, http://www.neeneenee.de/vrml"]
15 __version__ = "2006/01/17"
16 __bpydoc__ = """\
17 This script exports to X3D format.
18
19 Usage:
20
21 Run this script from "File->Export" menu.  A pop-up will ask whether you
22 want to export only selected or all relevant objects.
23
24 Known issues:<br>
25     Doesn't handle multiple materials (don't use material indices);<br>
26     Doesn't handle multiple UV textures on a single mesh (create a mesh
27 for each texture);<br>
28     Can't get the texture array associated with material * not the UV ones;
29 """
30
31
32 # $Id$
33 #
34 #------------------------------------------------------------------------
35 # X3D exporter for blender 2.36 or above
36 #
37 # ***** BEGIN GPL LICENSE BLOCK *****
38 #
39 # This program is free software; you can redistribute it and/or
40 # modify it under the terms of the GNU General Public License
41 # as published by the Free Software Foundation; either version 2
42 # of the License, or (at your option) any later version.
43 #
44 # This program is distributed in the hope that it will be useful,
45 # but WITHOUT ANY WARRANTY; without even the implied warranty of
46 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
47 # GNU General Public License for more details.
48 #
49 # You should have received a copy of the GNU General Public License
50 # along with this program; if not, write to the Free Software Foundation,
51 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
52 #
53 # ***** END GPL LICENCE BLOCK *****
54 #
55
56 ####################################
57 # Library dependancies
58 ####################################
59
60 import Blender
61 from Blender import Object, NMesh, Lamp, Draw, Image, Text, sys
62 from Blender.Scene import Render
63 import math
64
65 ####################################
66 # Global Variables
67 ####################################
68
69 scene = Blender.Scene.GetCurrent()
70 world = Blender.World.GetCurrent() 
71 worldmat = Blender.Texture.Get()
72 filename = Blender.Get('filename')
73 _safeOverwrite = True
74 ARG=''
75 extension = ''
76
77 class DrawTypes:
78     """Object DrawTypes enum values
79     BOUNDS - draw only the bounding box of the object
80     WIRE - draw object as a wire frame
81     SOLID - draw object with flat shading
82     SHADED - draw object with OpenGL shading
83 """
84     BOUNDBOX  = 1
85     WIRE      = 2
86     SOLID     = 3
87     SHADED    = 4
88     TEXTURE   = 5
89
90 if not hasattr(Blender.Object,'DrawTypes'):
91     Blender.Object.DrawTypes = DrawTypes()
92
93 ##########################################################
94 # Functions for writing output file
95 ##########################################################
96
97 class VRML2Export:
98
99     def __init__(self, filename):
100         #--- public you can change these ---
101         self.writingcolor = 0
102         self.writingtexture = 0
103         self.writingcoords = 0
104         self.wire = 0
105         self.proto = 1
106         self.matonly = 0
107         self.share = 0
108         self.billnode = 0
109         self.halonode = 0
110         self.collnode = 0
111         self.tilenode = 0
112         self.verbose=2     # level of verbosity in console 0-none, 1-some, 2-most
113         self.cp=3          # decimals for material color values     0.000 - 1.000
114         self.vp=3          # decimals for vertex coordinate values  0.000 - n.000
115         self.tp=3          # decimals for texture coordinate values 0.000 - 1.000
116         self.it=3
117         
118         #--- class private don't touch ---
119         self.texNames={}   # dictionary of textureNames
120         self.matNames={}   # dictionary of materiaNames
121         self.meshNames={}   # dictionary of meshNames
122         self.indentLevel=0 # keeps track of current indenting
123         self.filename=filename
124         self.file = open(filename, "w")
125         self.bNav=0
126         self.nodeID=0
127         self.namesReserved=[ "Anchor","Appearance","Arc2D","ArcClose2D","AudioClip","Background","Billboard",
128                              "BooleanFilter","BooleanSequencer","BooleanToggle","BooleanTrigger","Box","Circle2D",
129                              "Collision","Color","ColorInterpolator","ColorRGBA","component","Cone","connect",
130                              "Contour2D","ContourPolyline2D","Coordinate","CoordinateDouble","CoordinateInterpolator",
131                              "CoordinateInterpolator2D","Cylinder","CylinderSensor","DirectionalLight","Disk2D",
132                              "ElevationGrid","EspduTransform","EXPORT","ExternProtoDeclare","Extrusion","field",
133                              "fieldValue","FillProperties","Fog","FontStyle","GeoCoordinate","GeoElevationGrid",
134                              "GeoLocationLocation","GeoLOD","GeoMetadata","GeoOrigin","GeoPositionInterpolator",
135                              "GeoTouchSensor","GeoViewpoint","Group","HAnimDisplacer","HAnimHumanoid","HAnimJoint",
136                              "HAnimSegment","HAnimSite","head","ImageTexture","IMPORT","IndexedFaceSet",
137                              "IndexedLineSet","IndexedTriangleFanSet","IndexedTriangleSet","IndexedTriangleStripSet",
138                              "Inline","IntegerSequencer","IntegerTrigger","IS","KeySensor","LineProperties","LineSet",
139                              "LoadSensor","LOD","Material","meta","MetadataDouble","MetadataFloat","MetadataInteger",
140                              "MetadataSet","MetadataString","MovieTexture","MultiTexture","MultiTextureCoordinate",
141                              "MultiTextureTransform","NavigationInfo","Normal","NormalInterpolator","NurbsCurve",
142                              "NurbsCurve2D","NurbsOrientationInterpolator","NurbsPatchSurface",
143                              "NurbsPositionInterpolator","NurbsSet","NurbsSurfaceInterpolator","NurbsSweptSurface",
144                              "NurbsSwungSurface","NurbsTextureCoordinate","NurbsTrimmedSurface","OrientationInterpolator",
145                              "PixelTexture","PlaneSensor","PointLight","PointSet","Polyline2D","Polypoint2D",
146                              "PositionInterpolator","PositionInterpolator2D","ProtoBody","ProtoDeclare","ProtoInstance",
147                              "ProtoInterface","ProximitySensor","ReceiverPdu","Rectangle2D","ROUTE","ScalarInterpolator",
148                              "Scene","Script","Shape","SignalPdu","Sound","Sphere","SphereSensor","SpotLight","StaticGroup",
149                              "StringSensor","Switch","Text","TextureBackground","TextureCoordinate","TextureCoordinateGenerator",
150                              "TextureTransform","TimeSensor","TimeTrigger","TouchSensor","Transform","TransmitterPdu",
151                              "TriangleFanSet","TriangleSet","TriangleSet2D","TriangleStripSet","Viewpoint","VisibilitySensor",
152                              "WorldInfo","X3D","XvlShell","VertexShader","FragmentShader","MultiShaderAppearance","ShaderAppearance" ]
153         self.namesStandard=[ "Empty","Empty.000","Empty.001","Empty.002","Empty.003","Empty.004","Empty.005",
154                              "Empty.006","Empty.007","Empty.008","Empty.009","Empty.010","Empty.011","Empty.012",
155                              "Scene.001","Scene.002","Scene.003","Scene.004","Scene.005","Scene.06","Scene.013",
156                              "Scene.006","Scene.007","Scene.008","Scene.009","Scene.010","Scene.011","Scene.012",
157                              "World","World.000","World.001","World.002","World.003","World.004","World.005" ]
158         self.namesFog=[ "","LINEAR","EXPONENTIAL","" ]
159
160 ##########################################################
161 # Writing nodes routines
162 ##########################################################
163
164     def writeHeader(self):
165         bfile = sys.expandpath(Blender.Get('filename'))
166         self.file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
167         self.file.write("<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.0//EN\" \"http://www.web3d.org/specifications/x3d-3.0.dtd\">\n")
168         self.file.write("<X3D version=\"3.0\" profile=\"Immersive\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema-instance\" xsd:noNamespaceSchemaLocation=\"http://www.web3d.org/specifications/x3d-3.0.xsd\">\n")
169         self.file.write("<head>\n")
170         self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % sys.basename(bfile))
171         self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % Blender.Get('version'))
172         self.file.write("\t<meta name=\"translator\" content=\"X3D exporter v1.55 (2006/01/17)\" />\n")
173         self.file.write("</head>\n")
174         self.file.write("<Scene>\n")
175
176     def writeInline(self):
177         inlines = Blender.Scene.Get()
178         allinlines = len(inlines)
179         if scene != inlines[0]:
180             return
181         else:
182             for i in xrange(allinlines):
183                 nameinline=inlines[i].name
184                 if (nameinline not in self.namesStandard) and (i > 0):
185                     self.file.write("<Inline DEF=\"%s\" " % (self.cleanStr(nameinline)))
186                     nameinline = nameinline+".x3d"
187                     self.file.write("url=\"%s\" />" % nameinline)
188                     self.file.write("\n\n")
189
190     def writeScript(self):
191         textEditor = Blender.Text.Get() 
192         alltext = len(textEditor)
193         for i in xrange(alltext):
194             nametext = textEditor[i].getName()
195             nlines = textEditor[i].getNLines()
196             if (self.proto == 1):
197                 if (nametext == "proto" or nametext == "proto.js" or nametext == "proto.txt") and (nlines != None):
198                     nalllines = len(textEditor[i].asLines())
199                     alllines = textEditor[i].asLines()
200                     for j in xrange(nalllines):
201                         self.writeIndented(alllines[j] + "\n")
202             elif (self.proto == 0):
203                 if (nametext == "route" or nametext == "route.js" or nametext == "route.txt") and (nlines != None):
204                     nalllines = len(textEditor[i].asLines())
205                     alllines = textEditor[i].asLines()
206                     for j in xrange(nalllines):
207                         self.writeIndented(alllines[j] + "\n")
208         self.writeIndented("\n")
209
210     def writeViewpoint(self, thisObj):
211         context = scene.getRenderingContext()
212         ratio = float(context.imageSizeY())/float(context.imageSizeX())
213         lens = (360* (math.atan(ratio *16 / thisObj.data.getLens()) / math.pi))*(math.pi/180)
214         lens = min(lens, math.pi) 
215         # get the camera location, subtract 90 degress from X to orient like X3D does
216         loc = self.rotatePointForVRML(thisObj.loc)
217         rot = [thisObj.RotX - 1.57, thisObj.RotY, thisObj.RotZ]
218         nRot = self.rotatePointForVRML(rot)
219         # convert to Quaternion and to Angle Axis
220         Q  = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
221         Q1 = self.multiplyQuaternions(Q[0], Q[1])
222         Qf = self.multiplyQuaternions(Q1, Q[2])
223         angleAxis = self.quaternionToAngleAxis(Qf)
224         self.file.write("<Viewpoint DEF=\"%s\" " % (self.cleanStr(thisObj.name)))
225         self.file.write("description=\"%s\" " % (thisObj.name))
226         self.file.write("centerOfRotation=\"0 0 0\" ")
227         self.file.write("position=\"%3.2f %3.2f %3.2f\" " % (loc[0], loc[1], loc[2]))
228         self.file.write("orientation=\"%3.2f %3.2f %3.2f %3.2f\" " % (angleAxis[0], angleAxis[1], -angleAxis[2], angleAxis[3]))
229         self.file.write("fieldOfView=\"%.3f\" />\n\n" % (lens))
230
231     def writeFog(self):
232         if world:
233             mtype = world.getMistype()
234             mparam = world.getMist()
235             grd = world.getHor()
236             grd0, grd1, grd2 = grd[0], grd[1], grd[2]
237         else:
238             return
239         if (mtype == 1 or mtype == 2):
240             self.file.write("<Fog fogType=\"%s\" " % self.namesFog[mtype])                                              
241             self.file.write("color=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
242             self.file.write("visibilityRange=\"%s\" />\n\n" % round(mparam[2],self.cp))
243         else:
244             return
245
246     def writeNavigationInfo(self, scene):
247         allObj = []
248         allObj = list(scene.objects)
249         headlight = "TRUE"
250         vislimit = 0.0
251         for thisObj in allObj:
252             objType=thisObj.type
253             if objType == "Camera":
254                 vislimit = thisObj.data.clipEnd
255             elif objType == "Lamp":
256                 headlight = "FALSE"
257         self.file.write("<NavigationInfo headlight=\"%s\" " % headlight)
258         self.file.write("visibilityLimit=\"%s\" " % (round(vislimit,self.cp)))
259         self.file.write("type=\"EXAMINE, ANY\" avatarSize=\"0.25, 1.75, 0.75\" />\n\n")
260
261     def writeSpotLight(self, ob, lamp):
262         safeName = self.cleanStr(ob.name)
263         if world:
264             ambi = world.amb
265             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
266         else:
267             ambi = 0
268             ambientIntensity = 0
269
270         # compute cutoff and beamwidth
271         intensity=min(lamp.energy/1.75,1.0)
272         beamWidth=((lamp.spotSize*math.pi)/180.0)*.37;
273         cutOffAngle=beamWidth*1.3
274
275         dx,dy,dz=self.computeDirection(ob)
276         # note -dx seems to equal om[3][0]
277         # note -dz seems to equal om[3][1]
278         # note  dy seems to equal om[3][2]
279
280         location=ob.getLocation('worldspace')
281         radius = lamp.dist*math.cos(beamWidth)
282         self.file.write("<SpotLight DEF=\"%s\" " % safeName)
283         self.file.write("radius=\"%s\" " % (round(radius,self.cp)))
284         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
285         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
286         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
287         self.file.write("beamWidth=\"%s\" " % (round(beamWidth,self.cp)))
288         self.file.write("cutOffAngle=\"%s\" " % (round(cutOffAngle,self.cp)))
289         self.file.write("direction=\"%s %s %s\" " % (round(dx,3),round(dy,3),round(dz,3)))
290         self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
291         
292     def writeDirectionalLight(self, ob, lamp):
293         safeName = self.cleanStr(ob.name)
294         if world:
295             ambi = world.amb
296             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
297         else:
298             ambi = 0
299             ambientIntensity = 0
300
301         intensity=min(lamp.energy/1.75,1.0) 
302         (dx,dy,dz)=self.computeDirection(ob)
303         self.file.write("<DirectionalLight DEF=\"%s\" " % safeName)
304         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
305         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
306         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
307         self.file.write("direction=\"%s %s %s\" />\n\n" % (round(dx,4),round(dy,4),round(dz,4)))
308
309     def writePointLight(self, ob, lamp):
310         safeName = self.cleanStr(ob.name)
311         if world:
312             ambi = world.amb
313             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
314         else:
315             ambi = 0
316             ambientIntensity = 0
317         
318         location=ob.getLocation('worldspace')
319         intensity=min(lamp.energy/1.75,1.0) 
320         radius = lamp.dist
321         self.file.write("<PointLight DEF=\"%s\" " % safeName)
322         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
323         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
324         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
325         self.file.write("radius=\"%s\" " % radius )
326         self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
327
328     def writeNode(self, thisObj):
329         obname=str(thisObj.getName())
330         if obname in self.namesStandard:
331             return
332         else:
333             dx,dy,dz = self.computeDirection(thisObj)
334             location = thisObj.getLocation('worldspace')
335             self.writeIndented("<%s\n" % obname,1)
336             self.writeIndented("# direction %s %s %s\n" % (round(dx,3),round(dy,3),round(dz,3)))
337             self.writeIndented("# location %s %s %s\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
338             self.writeIndented("/>\n",-1)
339             self.writeIndented("\n")
340
341     def secureName(self, name):
342         name = name + str(self.nodeID)
343         self.nodeID=self.nodeID+1
344         if len(name) <= 3:
345             newname = "_" + str(self.nodeID)
346             return "%s" % (newname)
347         else:
348             for bad in ['"','#',"'",',','.','[','\\',']','{','}']:
349                 name=name.replace(bad,'_')
350             if name in self.namesReserved:
351                 newname = name[0:3] + "_" + str(self.nodeID)
352                 return "%s" % (newname)
353             elif name[0].isdigit():
354                 newname = "_" + name + str(self.nodeID)
355                 return "%s" % (newname)
356             else:
357                 newname = name
358                 return "%s" % (newname)
359
360     def writeIndexedFaceSet(self, ob, normals = 0):
361         imageMap={}   # set of used images
362         sided={}      # 'one':cnt , 'two':cnt
363         vColors={}    # 'multi':1
364         meshName = self.cleanStr(ob.name)
365         mesh=ob.data
366         meshME = self.cleanStr(mesh.name)
367         if len(mesh.faces) == 0: return
368         for face in mesh.faces:
369             if face.mode & Blender.NMesh.FaceModes['HALO'] and self.halonode == 0:
370                 self.writeIndented("<Billboard axisOfRotation=\"0 0 0\">\n",1)
371                 self.halonode = 1
372             elif face.mode & Blender.NMesh.FaceModes['BILLBOARD'] and self.billnode == 0:
373                 self.writeIndented("<Billboard axisOfRotation=\"0 1 0\">\n",1)
374                 self.billnode = 1
375             elif face.mode & Blender.NMesh.FaceModes['OBCOL'] and self.matonly == 0:
376                 self.matonly = 1
377             elif face.mode & Blender.NMesh.FaceModes['SHAREDCOL'] and self.share == 0:
378                 self.share = 1
379             elif face.mode & Blender.NMesh.FaceModes['TILES'] and self.tilenode == 0:
380                 self.tilenode = 1
381             elif not face.mode & Blender.NMesh.FaceModes['DYNAMIC'] and self.collnode == 0:
382                 self.writeIndented("<Collision enabled=\"false\">\n",1)
383                 self.collnode = 1
384
385         nIFSCnt=self.countIFSSetsNeeded(mesh, imageMap, sided, vColors)
386         
387         if nIFSCnt > 1:
388             self.writeIndented("<Group DEF=\"%s%s\">\n" % ("G_", meshName),1)
389         
390         if sided.has_key('two') and sided['two'] > 0:
391             bTwoSided=1
392         else:
393             bTwoSided=0
394         
395         location= ob.getLocation('worldspace')
396         self.writeIndented("<Transform DEF=\"%s\" translation=\"%s %s %s\">\n" % (meshName, round(location[0],3), round(location[1],3), round(location[2],3)),1)
397         self.writeIndented("<Shape>\n",1)
398             
399         maters=mesh.materials
400         hasImageTexture=0
401         issmooth=0
402
403         if len(maters) > 0 or mesh.hasFaceUV():
404           self.writeIndented("<Appearance>\n", 1)
405           # right now this script can only handle a single material per mesh.
406           if len(maters) >= 1:
407             mat=Blender.Material.Get(maters[0].name)
408             matFlags = mat.getMode()
409             if not matFlags & Blender.Material.Modes['TEXFACE']:
410               self.writeMaterial(mat, self.cleanStr(maters[0].name,''))
411               if len(maters) > 1:
412                 print "Warning: mesh named %s has multiple materials" % meshName
413                 print "Warning: only one material per object handled"
414         
415             #-- textures
416             if mesh.hasFaceUV():
417                 for face in mesh.faces:
418                     if (hasImageTexture == 0) and (face.image):
419                         self.writeImageTexture(face.image)
420                         hasImageTexture=1  # keep track of face texture
421             if self.tilenode == 1:
422                 self.writeIndented("<TextureTransform   scale=\"%s %s\" />\n" % (face.image.xrep, face.image.yrep))
423                 self.tilenode = 0
424             self.writeIndented("</Appearance>\n", -1)
425
426         #-- IndexedFaceSet or IndexedLineSet
427
428         # check if object is wireframe only
429         if ob.drawType == Blender.Object.DrawTypes.WIRE:
430             # user selected WIRE=2 on the Drawtype=Wire on (F9) Edit page
431             ifStyle="IndexedLineSet"
432             self.wire = 1
433         else:
434             # user selected BOUNDS=1, SOLID=3, SHARED=4, or TEXTURE=5
435             ifStyle="IndexedFaceSet"
436         # look up mesh name, use it if available
437         if self.meshNames.has_key(meshME):
438             self.writeIndented("<%s USE=\"ME_%s\">" % (ifStyle, meshME), 1)
439             self.meshNames[meshME]+=1
440         else:
441             if int(mesh.users) > 1:
442                 self.writeIndented("<%s DEF=\"ME_%s\" " % (ifStyle, meshME), 1)
443                 self.meshNames[meshME]=1
444             else:
445                 self.writeIndented("<%s " % ifStyle, 1)
446             if ob.drawType != Blender.Object.DrawTypes.WIRE:
447                 if bTwoSided == 1:
448                     self.file.write("solid=\"false\" ")
449                 else:
450                     self.file.write("solid=\"true\" ")
451
452             for face in mesh.faces:
453                 if face.smooth:
454                      issmooth=1
455             if issmooth==1 and self.wire == 0:
456                 creaseAngle=(mesh.getMaxSmoothAngle())*(math.pi/180.0)
457                 self.file.write("creaseAngle=\"%s\" " % (round(creaseAngle,self.cp)))
458
459             #--- output vertexColors
460             if self.share == 1 and self.matonly == 0:
461                 self.writeVertexColors(mesh)
462             if ob.drawType != Blender.Object.DrawTypes.WIRE:
463                 #--- output textureCoordinates if UV texture used
464                 if mesh.hasFaceUV():
465                     if self.matonly == 1 and self.share == 1:
466                         self.writeFaceColors(mesh)
467                     elif hasImageTexture == 1:
468                         self.writeTextureCoordinates(mesh)
469             #--- output coordinates
470             self.writeCoordinates(ob, mesh, meshName)
471
472             self.writingcoords = 1
473             self.writingtexture = 1
474             self.writingcolor = 1
475             self.writeCoordinates(ob, mesh, meshName)
476        
477             if ob.drawType != Blender.Object.DrawTypes.WIRE:
478                 #--- output textureCoordinates if UV texture used
479                 if mesh.hasFaceUV():
480                     if hasImageTexture == 1:
481                         self.writeTextureCoordinates(mesh)
482                     elif self.matonly == 1 and self.share == 1:
483                         self.writeFaceColors(mesh)
484             #--- output vertexColors
485             if self.share == 1 and self.matonly == 0:
486                 self.writeVertexColors(mesh)
487         self.matonly = 0
488         self.share = 0
489         self.wire = 0
490         self.writingcoords = 0
491         self.writingtexture = 0
492         self.writingcolor = 0
493         #--- output closing braces
494         self.writeIndented("</%s>\n" % ifStyle, -1)
495         self.writeIndented("</Shape>\n", -1)
496         self.writeIndented("</Transform>\n", -1)
497
498         if self.halonode == 1:
499             self.writeIndented("</Billboard>\n", -1)
500             self.halonode = 0
501
502         if self.billnode == 1:
503             self.writeIndented("</Billboard>\n", -1)
504             self.billnode = 0
505
506         if self.collnode == 1:
507             self.writeIndented("</Collision>\n", -1)
508             self.collnode = 0
509
510         if nIFSCnt > 1:
511             self.writeIndented("</Group>\n", -1)
512
513         self.file.write("\n")
514
515     def writeCoordinates(self, ob, mesh, meshName):
516         meshVertexList = mesh.verts
517
518         # create vertex list and pre rotate -90 degrees X for VRML
519         location= ob.getLocation('worldspace')
520         if self.writingcoords == 0:
521             self.file.write('coordIndex="')
522             for face in mesh.faces:
523                 for i in xrange(len(face)):
524                     indx=face[i].index
525                     self.file.write("%s " % indx)
526                 self.file.write("-1, ")
527             self.file.write("\">\n")
528         else:
529             #-- vertices
530             mesh.transform(ob.matrixWorld)
531             self.writeIndented("<Coordinate DEF=\"%s%s\" \n" % ("coord_",meshName), 1)
532             self.file.write("\t\t\t\tpoint=\"")
533             for v in meshVertexList:
534                 self.file.write("%.6f %.6f %.6f, " % tuple(v.co))
535             self.file.write("\" />")
536             self.writeIndented("\n", -1)
537
538     def writeTextureCoordinates(self, mesh):
539         texCoordList=[] 
540         texIndexList=[]
541         j=0
542
543         for face in mesh.faces:
544             for i in xrange(len(face)):
545                 texIndexList.append(j)
546                 texCoordList.append(face.uv[i])
547                 j=j+1
548             texIndexList.append(-1)
549         if self.writingtexture == 0:
550             self.file.write("\n\t\t\ttexCoordIndex=\"")
551             texIndxStr=""
552             for i in xrange(len(texIndexList)):
553                 texIndxStr = texIndxStr + "%d, " % texIndexList[i]
554                 if texIndexList[i]==-1:
555                     self.file.write(texIndxStr)
556                     texIndxStr=""
557             self.file.write("\"\n\t\t\t")
558         else:
559             self.writeIndented("<TextureCoordinate point=\"", 1)
560             for i in xrange(len(texCoordList)):
561                 self.file.write("%s %s, " % (round(texCoordList[i][0],self.tp), round(texCoordList[i][1],self.tp)))
562             self.file.write("\" />")
563             self.writeIndented("\n", -1)
564
565     def writeFaceColors(self, mesh):
566         if self.writingcolor == 0:
567             self.file.write("colorPerVertex=\"false\" ")
568         else:
569             self.writeIndented("<Color color=\"", 1)
570             for face in mesh.faces:
571                 if face.col:
572                     c=face.col[0]
573                     if self.verbose > 2:
574                         print "Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b)
575                     aColor = self.rgbToFS(c)
576                     self.file.write("%s, " % aColor)
577             self.file.write("\" />")
578             self.writeIndented("\n",-1)
579
580     def writeVertexColors(self, mesh):
581         if self.writingcolor == 0:
582             self.file.write("colorPerVertex=\"false\" ")
583         else:
584             self.writeIndented("<Color color=\"", 1)
585             for i in xrange(len(mesh.verts)):
586                 c=self.getVertexColorByIndx(mesh,i)
587                 if self.verbose > 2:
588                     print "Debug: vertex[%d].col r=%d g=%d b=%d" % (i, c.r, c.g, c.b)
589
590                 aColor = self.rgbToFS(c)
591                 self.file.write("%s, " % aColor)
592             self.file.write("\" />")
593             self.writeIndented("\n",-1)
594
595     def writeMaterial(self, mat, matName):
596         # look up material name, use it if available
597         if self.matNames.has_key(matName):
598             self.writeIndented("<Material USE=\"MA_%s\" />\n" % matName)
599             self.matNames[matName]+=1
600             return;
601
602         self.matNames[matName]=1
603
604         ambient = mat.amb/3
605         diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
606         if world:
607             ambi = world.getAmb()
608             ambi0, ambi1, ambi2 = (ambi[0]*mat.amb)*2, (ambi[1]*mat.amb)*2, (ambi[2]*mat.amb)*2
609         else:
610             ambi0, ambi1, ambi2 = 0, 0, 0
611         emisR, emisG, emisB = (diffuseR*mat.emit+ambi0)/2, (diffuseG*mat.emit+ambi1)/2, (diffuseB*mat.emit+ambi2)/2
612
613         shininess = mat.hard/512.0
614         specR = (mat.specCol[0]+0.001)/(1.25/(mat.getSpec()+0.001))
615         specG = (mat.specCol[1]+0.001)/(1.25/(mat.getSpec()+0.001))
616         specB = (mat.specCol[2]+0.001)/(1.25/(mat.getSpec()+0.001))
617         transp = 1-mat.alpha
618         matFlags = mat.getMode()
619         if matFlags & Blender.Material.Modes['SHADELESS']:
620           ambient = 1
621           shine = 1
622           specR = emitR = diffuseR
623           specG = emitG = diffuseG
624           specB = emitB = diffuseB
625         self.writeIndented("<Material DEF=\"MA_%s\" " % matName, 1)
626         self.file.write("diffuseColor=\"%s %s %s\" " % (round(diffuseR,self.cp), round(diffuseG,self.cp), round(diffuseB,self.cp)))
627         self.file.write("specularColor=\"%s %s %s\" " % (round(specR,self.cp), round(specG,self.cp), round(specB,self.cp)))
628         self.file.write("emissiveColor=\"%s %s %s\" \n" % (round(emisR,self.cp), round(emisG,self.cp), round(emisB,self.cp)))
629         self.writeIndented("ambientIntensity=\"%s\" " % (round(ambient,self.cp)))
630         self.file.write("shininess=\"%s\" " % (round(shininess,self.cp)))
631         self.file.write("transparency=\"%s\" />" % (round(transp,self.cp)))
632         self.writeIndented("\n",-1)
633
634     def writeImageTexture(self, image):
635         name = image.name
636         filename = image.filename.split('/')[-1].split('\\')[-1]
637         if self.texNames.has_key(name):
638             self.writeIndented("<ImageTexture USE=\"%s\" />\n" % self.cleanStr(name))
639             self.texNames[name] += 1
640             return
641         else:
642             self.writeIndented("<ImageTexture DEF=\"%s\" " % self.cleanStr(name), 1)
643             self.file.write("url=\"%s\" />" % name)
644             self.writeIndented("\n",-1)
645             self.texNames[name] = 1
646
647     def writeBackground(self):
648         if world:       worldname = world.name
649         else:           return
650         blending = world.getSkytype()   
651         grd = world.getHor()
652         grd0, grd1, grd2 = grd[0], grd[1], grd[2]
653         sky = world.getZen()
654         sky0, sky1, sky2 = sky[0], sky[1], sky[2]
655         mix0, mix1, mix2 = grd[0]+sky[0], grd[1]+sky[1], grd[2]+sky[2]
656         mix0, mix1, mix2 = mix0/2, mix1/2, mix2/2
657         self.file.write("<Background ")
658         if worldname not in self.namesStandard:
659             self.file.write("DEF=\"%s\" " % self.secureName(worldname))
660         # No Skytype - just Hor color
661         if blending == 0:
662             self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
663             self.file.write("skyColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
664         # Blend Gradient
665         elif blending == 1:
666             self.file.write("groundColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
667             self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
668             self.file.write("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
669             self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
670         # Blend+Real Gradient Inverse
671         elif blending == 3:
672             self.file.write("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
673             self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
674             self.file.write("skyColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
675             self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
676         # Paper - just Zen Color
677         elif blending == 4:
678             self.file.write("groundColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
679             self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
680         # Blend+Real+Paper - komplex gradient
681         elif blending == 7:
682             self.writeIndented("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
683             self.writeIndented("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
684             self.writeIndented("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
685             self.writeIndented("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
686         # Any Other two colors
687         else:
688             self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
689             self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
690         alltexture = len(worldmat)
691         for i in xrange(alltexture):
692             namemat = worldmat[i].getName()
693             pic = worldmat[i].getImage()        
694             if (namemat == "back") and (pic != None):
695                 self.file.write("\n\tbackUrl=\"%s\" " % str(pic.getName()))
696             elif (namemat == "bottom") and (pic != None):
697                 self.writeIndented("bottomUrl=\"%s\" " % str(pic.getName()))
698             elif (namemat == "front") and (pic != None):
699                 self.writeIndented("frontUrl=\"%s\" " % str(pic.getName()))
700             elif (namemat == "left") and (pic != None):
701                 self.writeIndented("leftUrl=\"%s\" " % str(pic.getName()))
702             elif (namemat == "right") and (pic != None):
703                 self.writeIndented("rightUrl=\"%s\" " % str(pic.getName()))
704             elif (namemat == "top") and (pic != None):
705                 self.writeIndented("topUrl=\"%s\" " % str(pic.getName()))
706         self.writeIndented("/>\n\n")
707
708 ##########################################################
709 # export routine
710 ##########################################################
711
712     def export(self, scene, world, worldmat):
713         print "Info: starting X3D export to " + self.filename + "..."
714         self.writeHeader()
715         self.writeScript()
716         self.writeNavigationInfo(scene)
717         self.writeBackground()
718         self.writeFog()
719         self.proto = 0
720         allObj = []
721         if ARG == 'selected':
722             allObj = list(scene.objects.context)
723         else:
724             allObj = list(scene.objects)
725             self.writeInline()
726         for thisObj in allObj:
727             try:
728                 objType=thisObj.type
729                 objName=thisObj.name
730                 self.matonly = 0
731                 if objType == "Camera":
732                     self.writeViewpoint(thisObj)
733                 elif objType == "Mesh":
734                     self.writeIndexedFaceSet(thisObj, normals = 0)
735                 elif objType == "Lamp":
736                     lmpName= thisObj.data
737                     lmpType=lmpName.getType()
738                     if lmpType == Lamp.Types.Lamp:
739                         self.writePointLight(thisObj, lmpName)
740                     elif lmpType == Lamp.Types.Spot:
741                         self.writeSpotLight(thisObj, lmpName)
742                     elif lmpType == Lamp.Types.Sun:
743                         self.writeDirectionalLight(thisObj, lmpName)
744                     else:
745                         self.writeDirectionalLight(thisObj, lmpName)
746                 elif objType == "Empty" and objName != "Empty":
747                     self.writeNode(thisObj)
748                 else:
749                     #print "Info: Ignoring [%s], object type [%s] not handle yet" % (object.name,object.getType())
750                     print ""
751             except AttributeError:
752                 print "Error: Unable to get type info for %s" % thisObj.getName()
753         if ARG != 'selected':
754             self.writeScript()
755         self.file.write("\n</Scene>\n</X3D>")
756         self.cleanup()
757         
758 ##########################################################
759 # Utility methods
760 ##########################################################
761
762     def cleanup(self):
763         self.file.close()
764         self.texNames={}
765         self.matNames={}
766         self.indentLevel=0
767         print "Info: finished X3D export to %s\n" % self.filename
768
769     def cleanStr(self, name, prefix='rsvd_'):
770         """cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
771
772         newName=name[:]
773         if len(newName) == 0:
774             self.nNodeID+=1
775             return "%s%d" % (prefix, self.nNodeID)
776         
777         if newName in self.namesReserved:
778             newName='%s%s' % (prefix,newName)
779         
780         if newName[0].isdigit():
781             newName='%s%s' % ('_',newName)
782
783         for bad in [' ','"','#',"'",',','.','[','\\',']','{','}']:
784             newName=newName.replace(bad,'_')
785         return newName
786
787     def countIFSSetsNeeded(self, mesh, imageMap, sided, vColors):
788         """
789         countIFFSetsNeeded() - should look at a blender mesh to determine
790         how many VRML IndexFaceSets or IndexLineSets are needed.  A
791         new mesh created under the following conditions:
792         
793          o - split by UV Textures / one per mesh
794          o - split by face, one sided and two sided
795          o - split by smooth and flat faces
796          o - split when faces only have 2 vertices * needs to be an IndexLineSet
797         """
798         
799         imageNameMap={}
800         faceMap={}
801         nFaceIndx=0
802         
803         for face in mesh.faces:
804             sidename='';
805             if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
806                 sidename='two'
807             else:
808                 sidename='one'
809             
810             if sided.has_key(sidename):
811                 sided[sidename]+=1
812             else:
813                 sided[sidename]=1
814
815             if face.image:
816                 faceName="%s_%s" % (face.image.name, sidename);
817
818                 try:
819                     imageMap[faceName].append(face)
820                 except:
821                     imageMap[faceName]=[face.image.name,sidename,face]
822
823         if self.verbose > 2:
824             for faceName in imageMap.iterkeys():
825                 ifs=imageMap[faceName]
826                 print "Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
827                       (faceName, ifs[0], ifs[1], len(ifs)-2)
828
829         return len(imageMap)
830     
831     def faceToString(self,face):
832
833         print "Debug: face.flag=0x%x (bitflags)" % face.flag
834         if face.sel:
835             print "Debug: face.sel=true"
836
837         print "Debug: face.mode=0x%x (bitflags)" % face.mode
838         if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
839             print "Debug: face.mode twosided"
840
841         print "Debug: face.transp=0x%x (enum)" % face.transp
842         if face.transp == NMesh.FaceTranspModes.SOLID:
843             print "Debug: face.transp.SOLID"
844
845         if face.image:
846             print "Debug: face.image=%s" % face.image.name
847         print "Debug: face.materialIndex=%d" % face.materialIndex 
848
849     def getVertexColorByIndx(self, mesh, indx):
850         c = None
851         for face in mesh.faces:
852             j=0
853             for vertex in face.v:
854                 if vertex.index == indx:
855                     c=face.col[j]
856                     break
857                 j=j+1
858             if c: break
859         return c
860
861     def meshToString(self,mesh):
862         print "Debug: mesh.hasVertexUV=%d" % mesh.hasVertexUV()
863         print "Debug: mesh.hasFaceUV=%d" % mesh.hasFaceUV()
864         print "Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours()
865         print "Debug: mesh.verts=%d" % len(mesh.verts)
866         print "Debug: mesh.faces=%d" % len(mesh.faces)
867         print "Debug: mesh.materials=%d" % len(mesh.materials)
868
869     def rgbToFS(self, c):
870         s="%s %s %s" % (
871             round(c.r/255.0,self.cp),
872             round(c.g/255.0,self.cp),
873             round(c.b/255.0,self.cp))
874         return s
875
876     def computeDirection(self, ob):
877         x,y,z=(0,-1.0,0) # point down
878         ax,ay,az = (ob.RotX,ob.RotZ,ob.RotY)
879
880         # rot X
881         x1=x
882         y1=y*math.cos(ax)-z*math.sin(ax)
883         z1=y*math.sin(ax)+z*math.cos(ax)
884
885         # rot Y
886         x2=x1*math.cos(ay)+z1*math.sin(ay)
887         y2=y1
888         z2=z1*math.cos(ay)-x1*math.sin(ay)
889
890         # rot Z
891         x3=x2*math.cos(az)-y2*math.sin(az)
892         y3=x2*math.sin(az)+y2*math.cos(az)
893         z3=z2
894
895         return [x3,y3,z3]
896         
897
898     # swap Y and Z to handle axis difference between Blender and VRML
899     #------------------------------------------------------------------------
900     def rotatePointForVRML(self, v):
901         x = v[0]
902         y = v[2]
903         z = -v[1]
904         
905         vrmlPoint=[x, y, z]
906         return vrmlPoint
907
908     # For writing well formed VRML code
909     #------------------------------------------------------------------------
910     def writeIndented(self, s, inc=0):
911         if inc < 1:
912             self.indentLevel = self.indentLevel + inc
913
914         spaces=""
915         for x in xrange(self.indentLevel):
916             spaces = spaces + "\t"
917         self.file.write(spaces + s)
918
919         if inc > 0:
920             self.indentLevel = self.indentLevel + inc
921
922     # Converts a Euler to three new Quaternions
923     # Angles of Euler are passed in as radians
924     #------------------------------------------------------------------------
925     def eulerToQuaternions(self, x, y, z):
926         Qx = [math.cos(x/2), math.sin(x/2), 0, 0]
927         Qy = [math.cos(y/2), 0, math.sin(y/2), 0]
928         Qz = [math.cos(z/2), 0, 0, math.sin(z/2)]
929         
930         quaternionVec=[Qx,Qy,Qz]
931         return quaternionVec
932     
933     # Multiply two Quaternions together to get a new Quaternion
934     #------------------------------------------------------------------------
935     def multiplyQuaternions(self, Q1, Q2):
936         result = [((Q1[0] * Q2[0]) - (Q1[1] * Q2[1]) - (Q1[2] * Q2[2]) - (Q1[3] * Q2[3])),
937                   ((Q1[0] * Q2[1]) + (Q1[1] * Q2[0]) + (Q1[2] * Q2[3]) - (Q1[3] * Q2[2])),
938                   ((Q1[0] * Q2[2]) + (Q1[2] * Q2[0]) + (Q1[3] * Q2[1]) - (Q1[1] * Q2[3])),
939                   ((Q1[0] * Q2[3]) + (Q1[3] * Q2[0]) + (Q1[1] * Q2[2]) - (Q1[2] * Q2[1]))]
940         
941         return result
942     
943     # Convert a Quaternion to an Angle Axis (ax, ay, az, angle)
944     # angle is in radians
945     #------------------------------------------------------------------------
946     def quaternionToAngleAxis(self, Qf):
947         scale = math.pow(Qf[1],2) + math.pow(Qf[2],2) + math.pow(Qf[3],2)
948         ax = Qf[1]
949         ay = Qf[2]
950         az = Qf[3]
951
952         if scale > .0001:
953             ax/=scale
954             ay/=scale
955             az/=scale
956         
957         angle = 2 * math.acos(Qf[0])
958         
959         result = [ax, ay, az, angle]
960         return result
961
962 ##########################################################
963 # Callbacks, needed before Main
964 ##########################################################
965
966 def select_file(filename):
967   if not filename.endswith(extension):
968     filename += extension
969   if _safeOverwrite and sys.exists(filename):
970     result = Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0")
971     if(result != 1):
972       return
973
974   wrlexport=VRML2Export(filename)
975   wrlexport.export(scene, world, worldmat)
976
977 def createWRLPath():
978   filename = Blender.Get('filename')
979   print filename
980   
981   if filename.find('.') != -1:
982     filename = filename.split('.')[0]
983     filename += extension
984     print filename
985
986   return filename
987
988 #########################################################
989 # main routine
990 #########################################################
991
992 try:
993     ARG = __script__['arg'] # user selected argument
994 except:
995     print "older version"
996
997 if Blender.Get('version') < 235:
998   print "Warning: X3D export failed, wrong blender version!"
999   print " You aren't running blender version 2.35 or greater"
1000   print " download a newer version from http://blender3d.org/"
1001 else:
1002   if ARG == 'comp':
1003     from gzip import *
1004     extension=".x3dz"
1005   else:
1006     extension=".x3d"
1007   Blender.Window.FileSelector(select_file,"Export X3D",createWRLPath())
1008