change blender python interface for classes not to ise __idname__ rather bl_idname...
[blender-staging.git] / release / scripts / io / export_x3d.py
1
2 __author__ = ("Bart", "Campbell Barton")
3 __email__ = ["Bart, bart:neeneenee*de"]
4 __url__ = ["Author's (Bart) homepage, http://www.neeneenee.de/vrml"]
5 __version__ = "2006/01/17"
6 __bpydoc__ = """\
7 This script exports to X3D format.
8
9 Usage:
10
11 Run this script from "File->Export" menu.  A pop-up will ask whether you
12 want to export only selected or all relevant objects.
13
14 Known issues:<br>
15         Doesn't handle multiple materials (don't use material indices);<br>
16         Doesn't handle multiple UV textures on a single mesh (create a mesh for each texture);<br>
17         Can't get the texture array associated with material * not the UV ones;
18 """
19
20
21 # $Id$
22 #
23 #------------------------------------------------------------------------
24 # X3D exporter for blender 2.36 or above
25 #
26 # ***** BEGIN GPL LICENSE BLOCK *****
27 #
28 # This program is free software; you can redistribute it and/or
29 # modify it under the terms of the GNU General Public License
30 # as published by the Free Software Foundation; either version 2
31 # of the License, or (at your option) any later version.
32 #
33 # This program is distributed in the hope that it will be useful,
34 # but WITHOUT ANY WARRANTY; without even the implied warranty of
35 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36 # GNU General Public License for more details.
37 #
38 # You should have received a copy of the GNU General Public License
39 # along with this program; if not, write to the Free Software Foundation,
40 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
41 #
42 # ***** END GPL LICENCE BLOCK *****
43 #
44
45 ####################################
46 # Library dependancies
47 ####################################
48
49 import math
50 import os
51
52 import bpy
53 import Mathutils
54
55 from export_3ds import create_derived_objects, free_derived_objects
56
57 # import Blender
58 # from Blender import Object, Lamp, Draw, Image, Text, sys, Mesh
59 # from Blender.Scene import Render
60 # import BPyObject
61 # import BPyMesh
62
63
64 DEG2RAD=0.017453292519943295
65 MATWORLD= Mathutils.RotationMatrix(-90, 4, 'x')
66
67 ####################################
68 # Global Variables
69 ####################################
70
71 filename = ""
72 # filename = Blender.Get('filename')
73 _safeOverwrite = True
74
75 extension = ''
76
77 ##########################################################
78 # Functions for writing output file
79 ##########################################################
80
81 class x3d_class:
82
83         def __init__(self, filename):
84                 #--- public you can change these ---
85                 self.writingcolor = 0
86                 self.writingtexture = 0
87                 self.writingcoords = 0
88                 self.proto = 1
89                 self.matonly = 0
90                 self.share = 0
91                 self.billnode = 0
92                 self.halonode = 0
93                 self.collnode = 0
94                 self.tilenode = 0
95                 self.verbose=2   # level of verbosity in console 0-none, 1-some, 2-most
96                 self.cp=3                 # decimals for material color values   0.000 - 1.000
97                 self.vp=3                 # decimals for vertex coordinate values  0.000 - n.000
98                 self.tp=3                 # decimals for texture coordinate values 0.000 - 1.000
99                 self.it=3
100                 
101                 #--- class private don't touch ---
102                 self.texNames={}   # dictionary of textureNames
103                 self.matNames={}   # dictionary of materiaNames
104                 self.meshNames={}   # dictionary of meshNames
105                 self.indentLevel=0 # keeps track of current indenting
106                 self.filename=filename
107                 self.file = None
108                 if filename.lower().endswith('.x3dz'):
109                         try:
110                                 import gzip
111                                 self.file = gzip.open(filename, "w")                            
112                         except:
113                                 print("failed to import compression modules, exporting uncompressed")
114                                 self.filename = filename[:-1] # remove trailing z
115                 
116                 if self.file == None:
117                         self.file = open(self.filename, "w")
118
119                 self.bNav=0
120                 self.nodeID=0
121                 self.namesReserved=[ "Anchor","Appearance","Arc2D","ArcClose2D","AudioClip","Background","Billboard",
122                                                          "BooleanFilter","BooleanSequencer","BooleanToggle","BooleanTrigger","Box","Circle2D",
123                                                          "Collision","Color","ColorInterpolator","ColorRGBA","component","Cone","connect",
124                                                          "Contour2D","ContourPolyline2D","Coordinate","CoordinateDouble","CoordinateInterpolator",
125                                                          "CoordinateInterpolator2D","Cylinder","CylinderSensor","DirectionalLight","Disk2D",
126                                                          "ElevationGrid","EspduTransform","EXPORT","ExternProtoDeclare","Extrusion","field",
127                                                          "fieldValue","FillProperties","Fog","FontStyle","GeoCoordinate","GeoElevationGrid",
128                                                          "GeoLocationLocation","GeoLOD","GeoMetadata","GeoOrigin","GeoPositionInterpolator",
129                                                          "GeoTouchSensor","GeoViewpoint","Group","HAnimDisplacer","HAnimHumanoid","HAnimJoint",
130                                                          "HAnimSegment","HAnimSite","head","ImageTexture","IMPORT","IndexedFaceSet",
131                                                          "IndexedLineSet","IndexedTriangleFanSet","IndexedTriangleSet","IndexedTriangleStripSet",
132                                                          "Inline","IntegerSequencer","IntegerTrigger","IS","KeySensor","LineProperties","LineSet",
133                                                          "LoadSensor","LOD","Material","meta","MetadataDouble","MetadataFloat","MetadataInteger",
134                                                          "MetadataSet","MetadataString","MovieTexture","MultiTexture","MultiTextureCoordinate",
135                                                          "MultiTextureTransform","NavigationInfo","Normal","NormalInterpolator","NurbsCurve",
136                                                          "NurbsCurve2D","NurbsOrientationInterpolator","NurbsPatchSurface",
137                                                          "NurbsPositionInterpolator","NurbsSet","NurbsSurfaceInterpolator","NurbsSweptSurface",
138                                                          "NurbsSwungSurface","NurbsTextureCoordinate","NurbsTrimmedSurface","OrientationInterpolator",
139                                                          "PixelTexture","PlaneSensor","PointLight","PointSet","Polyline2D","Polypoint2D",
140                                                          "PositionInterpolator","PositionInterpolator2D","ProtoBody","ProtoDeclare","ProtoInstance",
141                                                          "ProtoInterface","ProximitySensor","ReceiverPdu","Rectangle2D","ROUTE","ScalarInterpolator",
142                                                          "Scene","Script","Shape","SignalPdu","Sound","Sphere","SphereSensor","SpotLight","StaticGroup",
143                                                          "StringSensor","Switch","Text","TextureBackground","TextureCoordinate","TextureCoordinateGenerator",
144                                                          "TextureTransform","TimeSensor","TimeTrigger","TouchSensor","Transform","TransmitterPdu",
145                                                          "TriangleFanSet","TriangleSet","TriangleSet2D","TriangleStripSet","Viewpoint","VisibilitySensor",
146                                                          "WorldInfo","X3D","XvlShell","VertexShader","FragmentShader","MultiShaderAppearance","ShaderAppearance" ]
147                 self.namesStandard=[ "Empty","Empty.000","Empty.001","Empty.002","Empty.003","Empty.004","Empty.005",
148                                                          "Empty.006","Empty.007","Empty.008","Empty.009","Empty.010","Empty.011","Empty.012",
149                                                          "Scene.001","Scene.002","Scene.003","Scene.004","Scene.005","Scene.06","Scene.013",
150                                                          "Scene.006","Scene.007","Scene.008","Scene.009","Scene.010","Scene.011","Scene.012",
151                                                          "World","World.000","World.001","World.002","World.003","World.004","World.005" ]
152                 self.namesFog=[ "","LINEAR","EXPONENTIAL","" ]
153
154 ##########################################################
155 # Writing nodes routines
156 ##########################################################
157
158         def writeHeader(self):
159                 #bfile = sys.expandpath( Blender.Get('filename') ).replace('<', '&lt').replace('>', '&gt')
160                 bfile = self.filename.replace('<', '&lt').replace('>', '&gt') # use outfile name
161                 self.file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
162                 self.file.write("<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.0//EN\" \"http://www.web3d.org/specifications/x3d-3.0.dtd\">\n")
163                 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")
164                 self.file.write("<head>\n")
165                 self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % os.path.basename(bfile))
166                 # self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % sys.basename(bfile))
167                 self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % '2.5')
168                 # self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % Blender.Get('version'))
169                 self.file.write("\t<meta name=\"translator\" content=\"X3D exporter v1.55 (2006/01/17)\" />\n")
170                 self.file.write("</head>\n")
171                 self.file.write("<Scene>\n")
172         
173         # This functionality is poorly defined, disabling for now - campbell
174         '''
175         def writeInline(self):
176                 inlines = Blender.Scene.Get()
177                 allinlines = len(inlines)
178                 if scene != inlines[0]:
179                         return
180                 else:
181                         for i in xrange(allinlines):
182                                 nameinline=inlines[i].name
183                                 if (nameinline not in self.namesStandard) and (i > 0):
184                                         self.file.write("<Inline DEF=\"%s\" " % (self.cleanStr(nameinline)))
185                                         nameinline = nameinline+".x3d"
186                                         self.file.write("url=\"%s\" />" % nameinline)
187                                         self.file.write("\n\n")
188
189         
190         def writeScript(self):
191                 textEditor = Blender.Text.Get() 
192                 alltext = len(textEditor)
193                 for i in xrange(alltext):
194                         nametext = textEditor[i].name
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         
211         def writeViewpoint(self, ob, mat, scene):
212                 context = scene.render_data
213                 # context = scene.render
214                 ratio = float(context.resolution_x)/float(context.resolution_y)
215                 # ratio = float(context.imageSizeY())/float(context.imageSizeX())
216                 lens = (360* (math.atan(ratio *16 / ob.data.lens) / math.pi))*(math.pi/180)
217                 # lens = (360* (math.atan(ratio *16 / ob.data.getLens()) / math.pi))*(math.pi/180)
218                 lens = min(lens, math.pi) 
219                 
220                 # get the camera location, subtract 90 degress from X to orient like X3D does
221                 # mat = ob.matrixWorld - mat is now passed!
222                 
223                 loc = self.rotatePointForVRML(mat.translationPart())
224                 rot = mat.toEuler()
225                 rot = (((rot[0]-90)), rot[1], rot[2])
226                 # rot = (((rot[0]-90)*DEG2RAD), rot[1]*DEG2RAD, rot[2]*DEG2RAD)
227                 nRot = self.rotatePointForVRML( rot )
228                 # convert to Quaternion and to Angle Axis
229                 Q  = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
230                 Q1 = self.multiplyQuaternions(Q[0], Q[1])
231                 Qf = self.multiplyQuaternions(Q1, Q[2])
232                 angleAxis = self.quaternionToAngleAxis(Qf)
233                 self.file.write("<Viewpoint DEF=\"%s\" " % (self.cleanStr(ob.name)))
234                 self.file.write("description=\"%s\" " % (ob.name))
235                 self.file.write("centerOfRotation=\"0 0 0\" ")
236                 self.file.write("position=\"%3.2f %3.2f %3.2f\" " % (loc[0], loc[1], loc[2]))
237                 self.file.write("orientation=\"%3.2f %3.2f %3.2f %3.2f\" " % (angleAxis[0], angleAxis[1], -angleAxis[2], angleAxis[3]))
238                 self.file.write("fieldOfView=\"%.3f\" />\n\n" % (lens))
239
240         def writeFog(self, world):
241                 if world:
242                         mtype = world.mist.falloff
243                         # mtype = world.getMistype()
244                         mparam = world.mist
245                         # mparam = world.getMist()
246                         grd = world.horizon_color
247                         # grd = world.getHor()
248                         grd0, grd1, grd2 = grd[0], grd[1], grd[2]
249                 else:
250                         return
251                 if (mtype == 'LINEAR' or mtype == 'INVERSE_QUADRATIC'):
252                         mtype = 1 if mtype == 'LINEAR' else 2
253                 # if (mtype == 1 or mtype == 2):
254                         self.file.write("<Fog fogType=\"%s\" " % self.namesFog[mtype])                                          
255                         self.file.write("color=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
256                         self.file.write("visibilityRange=\"%s\" />\n\n" % round(mparam[2],self.cp))
257                 else:
258                         return
259         
260         def writeNavigationInfo(self, scene):
261                 self.file.write('<NavigationInfo headlight="FALSE" visibilityLimit="0.0" type=\'"EXAMINE","ANY"\' avatarSize="0.25, 1.75, 0.75" />\n')
262         
263         def writeSpotLight(self, ob, mtx, lamp, world):
264                 safeName = self.cleanStr(ob.name)
265                 if world:
266                         ambi = world.ambient_color
267                         # ambi = world.amb
268                         ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
269                 else:
270                         ambi = 0
271                         ambientIntensity = 0
272
273                 # compute cutoff and beamwidth
274                 intensity=min(lamp.energy/1.75,1.0)
275                 beamWidth=((lamp.spot_size*math.pi)/180.0)*.37;
276                 # beamWidth=((lamp.spotSize*math.pi)/180.0)*.37;
277                 cutOffAngle=beamWidth*1.3
278
279                 dx,dy,dz=self.computeDirection(mtx)
280                 # note -dx seems to equal om[3][0]
281                 # note -dz seems to equal om[3][1]
282                 # note  dy seems to equal om[3][2]
283
284                 #location=(ob.matrixWorld*MATWORLD).translationPart() # now passed
285                 location=(mtx*MATWORLD).translationPart()
286                 
287                 radius = lamp.distance*math.cos(beamWidth)
288                 # radius = lamp.dist*math.cos(beamWidth)
289                 self.file.write("<SpotLight DEF=\"%s\" " % safeName)
290                 self.file.write("radius=\"%s\" " % (round(radius,self.cp)))
291                 self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
292                 self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
293                 self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
294                 # 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)))
295                 self.file.write("beamWidth=\"%s\" " % (round(beamWidth,self.cp)))
296                 self.file.write("cutOffAngle=\"%s\" " % (round(cutOffAngle,self.cp)))
297                 self.file.write("direction=\"%s %s %s\" " % (round(dx,3),round(dy,3),round(dz,3)))
298                 self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
299                 
300                 
301         def writeDirectionalLight(self, ob, mtx, lamp, world):
302                 safeName = self.cleanStr(ob.name)
303                 if world:
304                         ambi = world.ambient_color
305                         # ambi = world.amb
306                         ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
307                 else:
308                         ambi = 0
309                         ambientIntensity = 0
310
311                 intensity=min(lamp.energy/1.75,1.0) 
312                 (dx,dy,dz)=self.computeDirection(mtx)
313                 self.file.write("<DirectionalLight DEF=\"%s\" " % safeName)
314                 self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
315                 self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
316                 # 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)))
317                 self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
318                 self.file.write("direction=\"%s %s %s\" />\n\n" % (round(dx,4),round(dy,4),round(dz,4)))
319
320         def writePointLight(self, ob, mtx, lamp, world):
321                 safeName = self.cleanStr(ob.name)
322                 if world:
323                         ambi = world.ambient_color
324                         # ambi = world.amb
325                         ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
326                 else:
327                         ambi = 0
328                         ambientIntensity = 0
329                 
330                 # location=(ob.matrixWorld*MATWORLD).translationPart() # now passed
331                 location= (mtx*MATWORLD).translationPart()
332                 
333                 self.file.write("<PointLight DEF=\"%s\" " % safeName)
334                 self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
335                 self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
336                 # 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)))
337                 self.file.write("intensity=\"%s\" " % (round( min(lamp.energy/1.75,1.0) ,self.cp)))
338                 self.file.write("radius=\"%s\" " % lamp.distance )
339                 # self.file.write("radius=\"%s\" " % lamp.dist )
340                 self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
341         '''
342         def writeNode(self, ob, mtx):
343                 obname=str(ob.name)
344                 if obname in self.namesStandard:
345                         return
346                 else:
347                         dx,dy,dz = self.computeDirection(mtx)
348                         # location=(ob.matrixWorld*MATWORLD).translationPart()
349                         location=(mtx*MATWORLD).translationPart()
350                         self.writeIndented("<%s\n" % obname,1)
351                         self.writeIndented("direction=\"%s %s %s\"\n" % (round(dx,3),round(dy,3),round(dz,3)))
352                         self.writeIndented("location=\"%s %s %s\"\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
353                         self.writeIndented("/>\n",-1)
354                         self.writeIndented("\n")
355         '''
356         def secureName(self, name):
357                 name = name + str(self.nodeID)
358                 self.nodeID=self.nodeID+1
359                 if len(name) <= 3:
360                         newname = "_" + str(self.nodeID)
361                         return "%s" % (newname)
362                 else:
363                         for bad in ['"','#',"'",',','.','[','\\',']','{','}']:
364                                 name=name.replace(bad,'_')
365                         if name in self.namesReserved:
366                                 newname = name[0:3] + "_" + str(self.nodeID)
367                                 return "%s" % (newname)
368                         elif name[0].isdigit():
369                                 newname = "_" + name + str(self.nodeID)
370                                 return "%s" % (newname)
371                         else:
372                                 newname = name
373                                 return "%s" % (newname)
374
375         def writeIndexedFaceSet(self, ob, mesh, mtx, world, EXPORT_TRI = False):
376                 imageMap={}   # set of used images
377                 sided={}          # 'one':cnt , 'two':cnt
378                 vColors={}      # 'multi':1
379                 meshName = self.cleanStr(ob.name)
380                 
381                 meshME = self.cleanStr(ob.data.name) # We dont care if its the mesh name or not
382                 # meshME = self.cleanStr(ob.getData(mesh=1).name) # We dont care if its the mesh name or not
383                 if len(mesh.faces) == 0: return
384                 mode = []
385                 # mode = 0
386                 if mesh.active_uv_texture:
387                 # if mesh.faceUV:
388                         for face in mesh.active_uv_texture.data:
389                         # for face in mesh.faces:
390                                 if face.halo and 'HALO' not in mode:
391                                         mode += ['HALO']
392                                 if face.billboard and 'BILLBOARD' not in mode:
393                                         mode += ['BILLBOARD']
394                                 if face.object_color and 'OBJECT_COLOR' not in mode:
395                                         mode += ['OBJECT_COLOR']
396                                 if face.collision and 'COLLISION' not in mode:
397                                         mode += ['COLLISION']
398                                 # mode |= face.mode 
399                 
400                 if 'HALO' in mode and self.halonode == 0:
401                 # if mode & Mesh.FaceModes.HALO and self.halonode == 0:
402                         self.writeIndented("<Billboard axisOfRotation=\"0 0 0\">\n",1)
403                         self.halonode = 1
404                 elif 'BILLBOARD' in mode and self.billnode == 0:
405                 # elif mode & Mesh.FaceModes.BILLBOARD and self.billnode == 0:
406                         self.writeIndented("<Billboard axisOfRotation=\"0 1 0\">\n",1)
407                         self.billnode = 1
408                 elif 'OBJECT_COLOR' in mode and self.matonly == 0:
409                 # elif mode & Mesh.FaceModes.OBCOL and self.matonly == 0:
410                         self.matonly = 1
411                 # TF_TILES is marked as deprecated in DNA_meshdata_types.h
412                 # elif mode & Mesh.FaceModes.TILES and self.tilenode == 0:
413                 #       self.tilenode = 1
414                 elif 'COLLISION' not in mode and self.collnode == 0:
415                 # elif not mode & Mesh.FaceModes.DYNAMIC and self.collnode == 0:
416                         self.writeIndented("<Collision enabled=\"false\">\n",1)
417                         self.collnode = 1
418                 
419                 nIFSCnt=self.countIFSSetsNeeded(mesh, imageMap, sided, vColors)
420                 
421                 if nIFSCnt > 1:
422                         self.writeIndented("<Group DEF=\"%s%s\">\n" % ("G_", meshName),1)
423                 
424                 if 'two' in sided and sided['two'] > 0:
425                         bTwoSided=1
426                 else:
427                         bTwoSided=0
428
429                 # mtx = ob.matrixWorld * MATWORLD # mtx is now passed
430                 mtx = mtx * MATWORLD
431                 
432                 loc= mtx.translationPart()
433                 sca= mtx.scalePart()
434                 quat = mtx.toQuat()
435                 rot= quat.axis
436
437                 self.writeIndented('<Transform DEF="%s" translation="%.6f %.6f %.6f" scale="%.6f %.6f %.6f" rotation="%.6f %.6f %.6f %.6f">\n' % \
438                                                    (meshName, loc[0], loc[1], loc[2], sca[0], sca[1], sca[2], rot[0], rot[1], rot[2], quat.angle) )
439                 # self.writeIndented('<Transform DEF="%s" translation="%.6f %.6f %.6f" scale="%.6f %.6f %.6f" rotation="%.6f %.6f %.6f %.6f">\n' % \
440                 #   (meshName, loc[0], loc[1], loc[2], sca[0], sca[1], sca[2], rot[0], rot[1], rot[2], quat.angle*DEG2RAD) )
441
442                 self.writeIndented("<Shape>\n",1)
443                 maters=mesh.materials
444                 hasImageTexture=0
445                 issmooth=0
446
447                 if len(maters) > 0 or mesh.active_uv_texture:
448                 # if len(maters) > 0 or mesh.faceUV:
449                         self.writeIndented("<Appearance>\n", 1)
450                         # right now this script can only handle a single material per mesh.
451                         if len(maters) >= 1:
452                                 mat=maters[0]
453                                 # matFlags = mat.getMode()
454                                 if not mat.face_texture:
455                                 # if not matFlags & Blender.Material.Modes['TEXFACE']:
456                                         self.writeMaterial(mat, self.cleanStr(mat.name,''), world)
457                                         # self.writeMaterial(mat, self.cleanStr(maters[0].name,''), world)
458                                         if len(maters) > 1:
459                                                 print("Warning: mesh named %s has multiple materials" % meshName)
460                                                 print("Warning: only one material per object handled")
461                         
462                                 #-- textures
463                                 face = None
464                                 if mesh.active_uv_texture:
465                                 # if mesh.faceUV:
466                                         for face in mesh.active_uv_texture.data:
467                                         # for face in mesh.faces:
468                                                 if face.image:
469                                                 # if (hasImageTexture == 0) and (face.image):
470                                                         self.writeImageTexture(face.image)
471                                                         # hasImageTexture=1  # keep track of face texture
472                                                         break
473                                 if self.tilenode == 1 and face and face.image:
474                                 # if self.tilenode == 1:
475                                         self.writeIndented("<TextureTransform   scale=\"%s %s\" />\n" % (face.image.xrep, face.image.yrep))
476                                         self.tilenode = 0
477                                 self.writeIndented("</Appearance>\n", -1)
478
479                 #-- IndexedFaceSet or IndexedLineSet
480
481                 # user selected BOUNDS=1, SOLID=3, SHARED=4, or TEXTURE=5
482                 ifStyle="IndexedFaceSet"
483                 # look up mesh name, use it if available
484                 if meshME in self.meshNames:
485                         self.writeIndented("<%s USE=\"ME_%s\">" % (ifStyle, meshME), 1)
486                         self.meshNames[meshME]+=1
487                 else:
488                         if int(mesh.users) > 1:
489                                 self.writeIndented("<%s DEF=\"ME_%s\" " % (ifStyle, meshME), 1)
490                                 self.meshNames[meshME]=1
491                         else:
492                                 self.writeIndented("<%s " % ifStyle, 1)
493                         
494                         if bTwoSided == 1:
495                                 self.file.write("solid=\"false\" ")
496                         else:
497                                 self.file.write("solid=\"true\" ")
498
499                         for face in mesh.faces:
500                                 if face.smooth:
501                                          issmooth=1
502                                          break
503                         if issmooth==1:
504                                 creaseAngle=(mesh.autosmooth_angle)*(math.pi/180.0)
505                                 # creaseAngle=(mesh.degr)*(math.pi/180.0)
506                                 self.file.write("creaseAngle=\"%s\" " % (round(creaseAngle,self.cp)))
507
508                         #--- output textureCoordinates if UV texture used
509                         if mesh.active_uv_texture:
510                         # if mesh.faceUV:
511                                 if self.matonly == 1 and self.share == 1:
512                                         self.writeFaceColors(mesh)
513                                 elif hasImageTexture == 1:
514                                         self.writeTextureCoordinates(mesh)
515                         #--- output coordinates
516                         self.writeCoordinates(ob, mesh, meshName, EXPORT_TRI)
517
518                         self.writingcoords = 1
519                         self.writingtexture = 1
520                         self.writingcolor = 1
521                         self.writeCoordinates(ob, mesh, meshName, EXPORT_TRI)
522                         
523                         #--- output textureCoordinates if UV texture used
524                         if mesh.active_uv_texture:
525                         # if mesh.faceUV:
526                                 if hasImageTexture == 1:
527                                         self.writeTextureCoordinates(mesh)
528                                 elif self.matonly == 1 and self.share == 1:
529                                         self.writeFaceColors(mesh)
530                         #--- output vertexColors
531                 self.matonly = 0
532                 self.share = 0
533                 
534                 self.writingcoords = 0
535                 self.writingtexture = 0
536                 self.writingcolor = 0
537                 #--- output closing braces
538                 self.writeIndented("</%s>\n" % ifStyle, -1)
539                 self.writeIndented("</Shape>\n", -1)
540                 self.writeIndented("</Transform>\n", -1)
541
542                 if self.halonode == 1:
543                         self.writeIndented("</Billboard>\n", -1)
544                         self.halonode = 0
545
546                 if self.billnode == 1:
547                         self.writeIndented("</Billboard>\n", -1)
548                         self.billnode = 0
549
550                 if self.collnode == 1:
551                         self.writeIndented("</Collision>\n", -1)
552                         self.collnode = 0
553
554                 if nIFSCnt > 1:
555                         self.writeIndented("</Group>\n", -1)
556
557                 self.file.write("\n")
558
559         def writeCoordinates(self, ob, mesh, meshName, EXPORT_TRI = False):
560                 # create vertex list and pre rotate -90 degrees X for VRML
561                 
562                 if self.writingcoords == 0:
563                         self.file.write('coordIndex="')
564                         for face in mesh.faces:
565                                 fv = face.verts
566                                 # fv = face.v
567                                 
568                                 if len(fv)==3:
569                                 # if len(face)==3:
570                                         self.file.write("%i %i %i -1, " % (fv[0], fv[1], fv[2]))
571                                         # self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
572                                 else:
573                                         if EXPORT_TRI:
574                                                 self.file.write("%i %i %i -1, " % (fv[0], fv[1], fv[2]))
575                                                 # self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
576                                                 self.file.write("%i %i %i -1, " % (fv[0], fv[2], fv[3]))
577                                                 # self.file.write("%i %i %i -1, " % (fv[0].index, fv[2].index, fv[3].index))
578                                         else:
579                                                 self.file.write("%i %i %i %i -1, " % (fv[0], fv[1], fv[2], fv[3]))
580                                                 # self.file.write("%i %i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index, fv[3].index))
581                         
582                         self.file.write("\">\n")
583                 else:
584                         #-- vertices
585                         # mesh.transform(ob.matrixWorld)
586                         self.writeIndented("<Coordinate DEF=\"%s%s\" \n" % ("coord_",meshName), 1)
587                         self.file.write("\t\t\t\tpoint=\"")
588                         for v in mesh.verts:
589                                 self.file.write("%.6f %.6f %.6f, " % tuple(v.co))
590                         self.file.write("\" />")
591                         self.writeIndented("\n", -1)
592
593         def writeTextureCoordinates(self, mesh):
594                 texCoordList=[] 
595                 texIndexList=[]
596                 j=0
597
598                 for face in mesh.active_uv_texture.data:
599                 # for face in mesh.faces:
600                         uvs = face.uv
601                         # uvs = [face.uv1, face.uv2, face.uv3, face.uv4] if face.verts[3] else [face.uv1, face.uv2, face.uv3]
602
603                         for uv in uvs:
604                         # for uv in face.uv:
605                                 texIndexList.append(j)
606                                 texCoordList.append(uv)
607                                 j=j+1
608                         texIndexList.append(-1)
609                 if self.writingtexture == 0:
610                         self.file.write("\n\t\t\ttexCoordIndex=\"")
611                         texIndxStr=""
612                         for i in range(len(texIndexList)):
613                                 texIndxStr = texIndxStr + "%d, " % texIndexList[i]
614                                 if texIndexList[i]==-1:
615                                         self.file.write(texIndxStr)
616                                         texIndxStr=""
617                         self.file.write("\"\n\t\t\t")
618                 else:
619                         self.writeIndented("<TextureCoordinate point=\"", 1)
620                         for i in range(len(texCoordList)):
621                                 self.file.write("%s %s, " % (round(texCoordList[i][0],self.tp), round(texCoordList[i][1],self.tp)))
622                         self.file.write("\" />")
623                         self.writeIndented("\n", -1)
624
625         def writeFaceColors(self, mesh):
626                 if self.writingcolor == 0:
627                         self.file.write("colorPerVertex=\"false\" ")
628                 elif mesh.active_vertex_color:
629                 # else:
630                         self.writeIndented("<Color color=\"", 1)
631                         for face in mesh.active_vertex_color.data:
632                                 c = face.color1
633                                 if self.verbose > 2:
634                                         print("Debug: face.col r=%d g=%d b=%d" % (c[0], c[1], c[2]))
635                                         # print("Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b))
636                                 aColor = self.rgbToFS(c)
637                                 self.file.write("%s, " % aColor)
638
639                         # for face in mesh.faces:
640                         #       if face.col:
641                         #               c=face.col[0]
642                         #               if self.verbose > 2:
643                         #                       print("Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b))
644                         #               aColor = self.rgbToFS(c)
645                         #               self.file.write("%s, " % aColor)
646                         self.file.write("\" />")
647                         self.writeIndented("\n",-1)
648         
649         def writeMaterial(self, mat, matName, world):
650                 # look up material name, use it if available
651                 if matName in self.matNames:
652                         self.writeIndented("<Material USE=\"MA_%s\" />\n" % matName)
653                         self.matNames[matName]+=1
654                         return;
655
656                 self.matNames[matName]=1
657
658                 ambient = mat.ambient/3
659                 # ambient = mat.amb/3
660                 diffuseR, diffuseG, diffuseB = tuple(mat.diffuse_color)
661                 # diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
662                 if world:
663                         ambi = world.ambient_color
664                         # ambi = world.getAmb()
665                         ambi0, ambi1, ambi2 = (ambi[0]*mat.ambient)*2, (ambi[1]*mat.ambient)*2, (ambi[2]*mat.ambient)*2
666                         # ambi0, ambi1, ambi2 = (ambi[0]*mat.amb)*2, (ambi[1]*mat.amb)*2, (ambi[2]*mat.amb)*2
667                 else:
668                         ambi0, ambi1, ambi2 = 0, 0, 0
669                 emisR, emisG, emisB = (diffuseR*mat.emit+ambi0)/2, (diffuseG*mat.emit+ambi1)/2, (diffuseB*mat.emit+ambi2)/2
670
671                 shininess = mat.specular_hardness/512.0
672                 # shininess = mat.hard/512.0
673                 specR = (mat.specular_color[0]+0.001)/(1.25/(mat.specular_intensity+0.001))
674                 # specR = (mat.specCol[0]+0.001)/(1.25/(mat.spec+0.001))
675                 specG = (mat.specular_color[1]+0.001)/(1.25/(mat.specular_intensity+0.001))
676                 # specG = (mat.specCol[1]+0.001)/(1.25/(mat.spec+0.001))
677                 specB = (mat.specular_color[2]+0.001)/(1.25/(mat.specular_intensity+0.001))
678                 # specB = (mat.specCol[2]+0.001)/(1.25/(mat.spec+0.001))
679                 transp = 1-mat.alpha
680                 # matFlags = mat.getMode()
681                 if mat.shadeless:
682                 # if matFlags & Blender.Material.Modes['SHADELESS']:
683                   ambient = 1
684                   shine = 1
685                   specR = emitR = diffuseR
686                   specG = emitG = diffuseG
687                   specB = emitB = diffuseB
688                 self.writeIndented("<Material DEF=\"MA_%s\" " % matName, 1)
689                 self.file.write("diffuseColor=\"%s %s %s\" " % (round(diffuseR,self.cp), round(diffuseG,self.cp), round(diffuseB,self.cp)))
690                 self.file.write("specularColor=\"%s %s %s\" " % (round(specR,self.cp), round(specG,self.cp), round(specB,self.cp)))
691                 self.file.write("emissiveColor=\"%s %s %s\" \n" % (round(emisR,self.cp), round(emisG,self.cp), round(emisB,self.cp)))
692                 self.writeIndented("ambientIntensity=\"%s\" " % (round(ambient,self.cp)))
693                 self.file.write("shininess=\"%s\" " % (round(shininess,self.cp)))
694                 self.file.write("transparency=\"%s\" />" % (round(transp,self.cp)))
695                 self.writeIndented("\n",-1)
696
697         def writeImageTexture(self, image):
698                 name = image.name
699                 filename = image.filename.split('/')[-1].split('\\')[-1]
700                 if name in self.texNames:
701                         self.writeIndented("<ImageTexture USE=\"%s\" />\n" % self.cleanStr(name))
702                         self.texNames[name] += 1
703                         return
704                 else:
705                         self.writeIndented("<ImageTexture DEF=\"%s\" " % self.cleanStr(name), 1)
706                         self.file.write("url=\"%s\" />" % name)
707                         self.writeIndented("\n",-1)
708                         self.texNames[name] = 1
709
710         def writeBackground(self, world, alltextures):
711                 if world:       worldname = world.name
712                 else:           return
713                 blending = (world.blend_sky, world.paper_sky, world.real_sky)
714                 # blending = world.getSkytype() 
715                 grd = world.horizon_color
716                 # grd = world.getHor()
717                 grd0, grd1, grd2 = grd[0], grd[1], grd[2]
718                 sky = world.zenith_color
719                 # sky = world.getZen()
720                 sky0, sky1, sky2 = sky[0], sky[1], sky[2]
721                 mix0, mix1, mix2 = grd[0]+sky[0], grd[1]+sky[1], grd[2]+sky[2]
722                 mix0, mix1, mix2 = mix0/2, mix1/2, mix2/2
723                 self.file.write("<Background ")
724                 if worldname not in self.namesStandard:
725                         self.file.write("DEF=\"%s\" " % self.secureName(worldname))
726                 # No Skytype - just Hor color
727                 if blending == (0, 0, 0):
728                 # if blending == 0:
729                         self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
730                         self.file.write("skyColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
731                 # Blend Gradient
732                 elif blending == (1, 0, 0):
733                 # elif blending == 1:
734                         self.file.write("groundColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
735                         self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
736                         self.file.write("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
737                         self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
738                 # Blend+Real Gradient Inverse
739                 elif blending == (1, 0, 1):
740                 # elif blending == 3:
741                         self.file.write("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
742                         self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
743                         self.file.write("skyColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
744                         self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
745                 # Paper - just Zen Color
746                 elif blending == (0, 0, 1):
747                 # elif blending == 4:
748                         self.file.write("groundColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
749                         self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
750                 # Blend+Real+Paper - komplex gradient
751                 elif blending == (1, 1, 1):
752                 # elif blending == 7:
753                         self.writeIndented("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
754                         self.writeIndented("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
755                         self.writeIndented("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
756                         self.writeIndented("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
757                 # Any Other two colors
758                 else:
759                         self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
760                         self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
761
762                 alltexture = len(alltextures)
763
764                 for i in range(alltexture):
765                         tex = alltextures[i]
766
767                         if tex.type != 'IMAGE' or tex.image == None:
768                                 continue
769
770                         namemat = tex.name
771                         # namemat = alltextures[i].name
772
773                         pic = tex.image
774
775                         # using .expandpath just in case, os.path may not expect //
776                         basename = os.path.basename(pic.get_abs_filename())
777
778                         pic = alltextures[i].image
779                         # pic = alltextures[i].getImage()
780                         if (namemat == "back") and (pic != None):
781                                 self.file.write("\n\tbackUrl=\"%s\" " % basename)
782                                 # self.file.write("\n\tbackUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
783                         elif (namemat == "bottom") and (pic != None):
784                                 self.writeIndented("bottomUrl=\"%s\" " % basename)
785                                 # self.writeIndented("bottomUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
786                         elif (namemat == "front") and (pic != None):
787                                 self.writeIndented("frontUrl=\"%s\" " % basename)
788                                 # self.writeIndented("frontUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
789                         elif (namemat == "left") and (pic != None):
790                                 self.writeIndented("leftUrl=\"%s\" " % basename)
791                                 # self.writeIndented("leftUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
792                         elif (namemat == "right") and (pic != None):
793                                 self.writeIndented("rightUrl=\"%s\" " % basename)
794                                 # self.writeIndented("rightUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
795                         elif (namemat == "top") and (pic != None):
796                                 self.writeIndented("topUrl=\"%s\" " % basename)
797                                 # self.writeIndented("topUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
798                 self.writeIndented("/>\n\n")
799
800 ##########################################################
801 # export routine
802 ##########################################################
803
804         def export(self, scene, world, alltextures,\
805                         EXPORT_APPLY_MODIFIERS = False,\
806                         EXPORT_TRI=                             False,\
807                 ):
808                 
809                 print("Info: starting X3D export to " + self.filename + "...")
810                 self.writeHeader()
811                 # self.writeScript()
812                 self.writeNavigationInfo(scene)
813                 self.writeBackground(world, alltextures)
814                 self.writeFog(world)
815                 self.proto = 0
816                 
817                 
818                 # # COPIED FROM OBJ EXPORTER
819                 # if EXPORT_APPLY_MODIFIERS:
820                 #       temp_mesh_name = '~tmp-mesh'
821                 
822                 #       # Get the container mesh. - used for applying modifiers and non mesh objects.
823                 #       containerMesh = meshName = tempMesh = None
824                 #       for meshName in Blender.NMesh.GetNames():
825                 #               if meshName.startswith(temp_mesh_name):
826                 #                       tempMesh = Mesh.Get(meshName)
827                 #                       if not tempMesh.users:
828                 #                               containerMesh = tempMesh
829                 #       if not containerMesh:
830                 #               containerMesh = Mesh.New(temp_mesh_name)
831                 # -------------------------- 
832                 
833                 
834                 for ob_main in [o for o in scene.objects if o.is_visible()]:
835                 # for ob_main in scene.objects.context:
836
837                         free, derived = create_derived_objects(ob_main)
838
839                         if derived == None: continue
840
841                         for ob, ob_mat in derived:
842                         # for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
843                                 objType=ob.type
844                                 objName=ob.name
845                                 self.matonly = 0
846                                 if objType == "CAMERA":
847                                 # if objType == "Camera":
848                                         self.writeViewpoint(ob, ob_mat, scene)
849                                 elif objType in ("MESH", "CURVE", "SURF", "TEXT") :
850                                 # elif objType in ("Mesh", "Curve", "Surf", "Text") :                           
851                                         if EXPORT_APPLY_MODIFIERS or objType != 'MESH':
852                                         # if  EXPORT_APPLY_MODIFIERS or objType != 'Mesh':
853                                                 me = ob.create_mesh(EXPORT_APPLY_MODIFIERS, 'PREVIEW')
854                                                 # me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scene)
855                                         else:
856                                                 me = ob.data
857                                                 # me = ob.getData(mesh=1)
858                                         
859                                         self.writeIndexedFaceSet(ob, me, ob_mat, world, EXPORT_TRI = EXPORT_TRI)
860
861                                         # free mesh created with create_mesh()
862                                         if me != ob.data:
863                                                 bpy.data.remove_mesh(me)
864
865                                 elif objType == "LAMP":
866                                 # elif objType == "Lamp":
867                                         data= ob.data
868                                         datatype=data.type
869                                         if datatype == 'POINT':
870                                         # if datatype == Lamp.Types.Lamp:
871                                                 self.writePointLight(ob, ob_mat, data, world)
872                                         elif datatype == 'SPOT':
873                                         # elif datatype == Lamp.Types.Spot:
874                                                 self.writeSpotLight(ob, ob_mat, data, world)
875                                         elif datatype == 'SUN':
876                                         # elif datatype == Lamp.Types.Sun:
877                                                 self.writeDirectionalLight(ob, ob_mat, data, world)
878                                         else:
879                                                 self.writeDirectionalLight(ob, ob_mat, data, world)
880                                 # do you think x3d could document what to do with dummy objects?
881                                 #elif objType == "Empty" and objName != "Empty":
882                                 #       self.writeNode(ob, ob_mat)
883                                 else:
884                                         #print "Info: Ignoring [%s], object type [%s] not handle yet" % (object.name,object.getType)
885                                         pass
886                                 
887                         if free:
888                                 free_derived_objects(ob_main)
889                         
890                 self.file.write("\n</Scene>\n</X3D>")
891                 
892                 # if EXPORT_APPLY_MODIFIERS:
893                 #       if containerMesh:
894                 #               containerMesh.verts = None
895                 
896                 self.cleanup()
897                 
898 ##########################################################
899 # Utility methods
900 ##########################################################
901
902         def cleanup(self):
903                 self.file.close()
904                 self.texNames={}
905                 self.matNames={}
906                 self.indentLevel=0
907                 print("Info: finished X3D export to %s\n" % self.filename)
908
909         def cleanStr(self, name, prefix='rsvd_'):
910                 """cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
911
912                 newName=name[:]
913                 if len(newName) == 0:
914                         self.nNodeID+=1
915                         return "%s%d" % (prefix, self.nNodeID)
916                 
917                 if newName in self.namesReserved:
918                         newName='%s%s' % (prefix,newName)
919                 
920                 if newName[0].isdigit():
921                         newName='%s%s' % ('_',newName)
922
923                 for bad in [' ','"','#',"'",',','.','[','\\',']','{','}']:
924                         newName=newName.replace(bad,'_')
925                 return newName
926
927         def countIFSSetsNeeded(self, mesh, imageMap, sided, vColors):
928                 """
929                 countIFFSetsNeeded() - should look at a blender mesh to determine
930                 how many VRML IndexFaceSets or IndexLineSets are needed.  A
931                 new mesh created under the following conditions:
932                 
933                  o - split by UV Textures / one per mesh
934                  o - split by face, one sided and two sided
935                  o - split by smooth and flat faces
936                  o - split when faces only have 2 vertices * needs to be an IndexLineSet
937                 """
938                 
939                 imageNameMap={}
940                 faceMap={}
941                 nFaceIndx=0
942                 
943                 if mesh.active_uv_texture:
944                 # if mesh.faceUV:
945                         for face in mesh.active_uv_texture.data:
946                         # for face in mesh.faces:
947                                 sidename='';
948                                 if face.twoside:
949                                 # if  face.mode & Mesh.FaceModes.TWOSIDE:
950                                         sidename='two'
951                                 else:
952                                         sidename='one'
953                                 
954                                 if sidename in sided:
955                                         sided[sidename]+=1
956                                 else:
957                                         sided[sidename]=1
958                                 
959                                 image = face.image
960                                 if image:
961                                         faceName="%s_%s" % (face.image.name, sidename);
962                                         try:
963                                                 imageMap[faceName].append(face)
964                                         except:
965                                                 imageMap[faceName]=[face.image.name,sidename,face]
966
967                         if self.verbose > 2:
968                                 for faceName in imageMap.keys():
969                                         ifs=imageMap[faceName]
970                                         print("Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
971                                                   (faceName, ifs[0], ifs[1], len(ifs)-2))
972
973                 return len(imageMap)
974         
975         def faceToString(self,face):
976
977                 print("Debug: face.flag=0x%x (bitflags)" % face.flag)
978                 if face.sel:
979                         print("Debug: face.sel=true")
980
981                 print("Debug: face.mode=0x%x (bitflags)" % face.mode)
982                 if face.mode & Mesh.FaceModes.TWOSIDE:
983                         print("Debug: face.mode twosided")
984
985                 print("Debug: face.transp=0x%x (enum)" % face.transp)
986                 if face.transp == Mesh.FaceTranspModes.SOLID:
987                         print("Debug: face.transp.SOLID")
988
989                 if face.image:
990                         print("Debug: face.image=%s" % face.image.name)
991                 print("Debug: face.materialIndex=%d" % face.materialIndex) 
992
993         # XXX not used
994         # def getVertexColorByIndx(self, mesh, indx):
995         #       c = None
996         #       for face in mesh.faces:
997         #               j=0
998         #               for vertex in face.v:
999         #                       if vertex.index == indx:
1000         #                               c=face.col[j]
1001         #                               break
1002         #                       j=j+1
1003         #               if c: break
1004         #       return c
1005
1006         def meshToString(self,mesh):
1007                 # print("Debug: mesh.hasVertexUV=%d" % mesh.vertexColors)
1008                 print("Debug: mesh.faceUV=%d" % (len(mesh.uv_textures) > 0))
1009                 # print("Debug: mesh.faceUV=%d" % mesh.faceUV)
1010                 print("Debug: mesh.hasVertexColours=%d" % (len(mesh.vertex_colors) > 0))
1011                 # print("Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours())
1012                 print("Debug: mesh.verts=%d" % len(mesh.verts))
1013                 print("Debug: mesh.faces=%d" % len(mesh.faces))
1014                 print("Debug: mesh.materials=%d" % len(mesh.materials))
1015
1016         def rgbToFS(self, c):
1017                 s="%s %s %s" % (round(c[0]/255.0,self.cp),
1018                                                 round(c[1]/255.0,self.cp),
1019                                                 round(c[2]/255.0,self.cp))
1020
1021                 # s="%s %s %s" % (
1022                 #       round(c.r/255.0,self.cp),
1023                 #       round(c.g/255.0,self.cp),
1024                 #       round(c.b/255.0,self.cp))
1025                 return s
1026
1027         def computeDirection(self, mtx):
1028                 x,y,z=(0,-1.0,0) # point down
1029                 
1030                 ax,ay,az = (mtx*MATWORLD).toEuler()
1031                 
1032                 # ax *= DEG2RAD
1033                 # ay *= DEG2RAD
1034                 # az *= DEG2RAD
1035
1036                 # rot X
1037                 x1=x
1038                 y1=y*math.cos(ax)-z*math.sin(ax)
1039                 z1=y*math.sin(ax)+z*math.cos(ax)
1040
1041                 # rot Y
1042                 x2=x1*math.cos(ay)+z1*math.sin(ay)
1043                 y2=y1
1044                 z2=z1*math.cos(ay)-x1*math.sin(ay)
1045
1046                 # rot Z
1047                 x3=x2*math.cos(az)-y2*math.sin(az)
1048                 y3=x2*math.sin(az)+y2*math.cos(az)
1049                 z3=z2
1050
1051                 return [x3,y3,z3]
1052                 
1053
1054         # swap Y and Z to handle axis difference between Blender and VRML
1055         #------------------------------------------------------------------------
1056         def rotatePointForVRML(self, v):
1057                 x = v[0]
1058                 y = v[2]
1059                 z = -v[1]
1060                 
1061                 vrmlPoint=[x, y, z]
1062                 return vrmlPoint
1063
1064         # For writing well formed VRML code
1065         #------------------------------------------------------------------------
1066         def writeIndented(self, s, inc=0):
1067                 if inc < 1:
1068                         self.indentLevel = self.indentLevel + inc
1069
1070                 spaces=""
1071                 for x in range(self.indentLevel):
1072                         spaces = spaces + "\t"
1073                 self.file.write(spaces + s)
1074
1075                 if inc > 0:
1076                         self.indentLevel = self.indentLevel + inc
1077
1078         # Converts a Euler to three new Quaternions
1079         # Angles of Euler are passed in as radians
1080         #------------------------------------------------------------------------
1081         def eulerToQuaternions(self, x, y, z):
1082                 Qx = [math.cos(x/2), math.sin(x/2), 0, 0]
1083                 Qy = [math.cos(y/2), 0, math.sin(y/2), 0]
1084                 Qz = [math.cos(z/2), 0, 0, math.sin(z/2)]
1085                 
1086                 quaternionVec=[Qx,Qy,Qz]
1087                 return quaternionVec
1088         
1089         # Multiply two Quaternions together to get a new Quaternion
1090         #------------------------------------------------------------------------
1091         def multiplyQuaternions(self, Q1, Q2):
1092                 result = [((Q1[0] * Q2[0]) - (Q1[1] * Q2[1]) - (Q1[2] * Q2[2]) - (Q1[3] * Q2[3])),
1093                                   ((Q1[0] * Q2[1]) + (Q1[1] * Q2[0]) + (Q1[2] * Q2[3]) - (Q1[3] * Q2[2])),
1094                                   ((Q1[0] * Q2[2]) + (Q1[2] * Q2[0]) + (Q1[3] * Q2[1]) - (Q1[1] * Q2[3])),
1095                                   ((Q1[0] * Q2[3]) + (Q1[3] * Q2[0]) + (Q1[1] * Q2[2]) - (Q1[2] * Q2[1]))]
1096                 
1097                 return result
1098         
1099         # Convert a Quaternion to an Angle Axis (ax, ay, az, angle)
1100         # angle is in radians
1101         #------------------------------------------------------------------------
1102         def quaternionToAngleAxis(self, Qf):
1103                 scale = math.pow(Qf[1],2) + math.pow(Qf[2],2) + math.pow(Qf[3],2)
1104                 ax = Qf[1]
1105                 ay = Qf[2]
1106                 az = Qf[3]
1107
1108                 if scale > .0001:
1109                         ax/=scale
1110                         ay/=scale
1111                         az/=scale
1112                 
1113                 angle = 2 * math.acos(Qf[0])
1114                 
1115                 result = [ax, ay, az, angle]
1116                 return result
1117
1118 ##########################################################
1119 # Callbacks, needed before Main
1120 ##########################################################
1121
1122 def x3d_export(filename,
1123                            context,
1124                            EXPORT_APPLY_MODIFIERS=False,
1125                            EXPORT_TRI=False,
1126                            EXPORT_GZIP=False):
1127         
1128         if EXPORT_GZIP:
1129                 if not filename.lower().endswith('.x3dz'):
1130                         filename = '.'.join(filename.split('.')[:-1]) + '.x3dz'
1131         else:
1132                 if not filename.lower().endswith('.x3d'):
1133                         filename = '.'.join(filename.split('.')[:-1]) + '.x3d'
1134         
1135         
1136         scene = context.scene
1137         # scene = Blender.Scene.GetCurrent()
1138         world = scene.world
1139
1140         # XXX these are global textures while .Get() returned only scene's?
1141         alltextures = bpy.data.textures
1142         # alltextures = Blender.Texture.Get()
1143
1144         wrlexport=x3d_class(filename)
1145         wrlexport.export(\
1146                 scene,\
1147                 world,\
1148                 alltextures,\
1149                 \
1150                 EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS,\
1151                 EXPORT_TRI = EXPORT_TRI,\
1152                 )
1153
1154
1155 def x3d_export_ui(filename):
1156         if not filename.endswith(extension):
1157                 filename += extension
1158         #if _safeOverwrite and sys.exists(filename):
1159         #       result = Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0")
1160         #if(result != 1):
1161         #       return
1162         
1163         # Get user options
1164         EXPORT_APPLY_MODIFIERS = Draw.Create(1)
1165         EXPORT_TRI = Draw.Create(0)
1166         EXPORT_GZIP = Draw.Create( filename.lower().endswith('.x3dz') )
1167         
1168         # Get USER Options
1169         pup_block = [\
1170         ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object.'),\
1171         ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\
1172         ('Compress', EXPORT_GZIP, 'GZip the resulting file, requires a full python install'),\
1173         ]
1174
1175         if not Draw.PupBlock('Export...', pup_block):
1176                 return
1177
1178         Blender.Window.EditMode(0)
1179         Blender.Window.WaitCursor(1)
1180         
1181         x3d_export(filename,\
1182                 EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val,\
1183                 EXPORT_TRI = EXPORT_TRI.val,\
1184                 EXPORT_GZIP = EXPORT_GZIP.val\
1185         )
1186         
1187         Blender.Window.WaitCursor(0)
1188
1189
1190
1191 #########################################################
1192 # main routine
1193 #########################################################
1194
1195
1196 # if __name__ == '__main__':
1197 #       Blender.Window.FileSelector(x3d_export_ui,"Export X3D", Blender.Get('filename').replace('.blend', '.x3d'))
1198
1199 class EXPORT_OT_x3d(bpy.types.Operator):
1200         '''Export selection to Extensible 3D file (.x3d)'''
1201         bl_idname = "export.x3d"
1202         bl_label = 'Export X3D'
1203         
1204         # List of operator properties, the attributes will be assigned
1205         # to the class instance from the operator settings before calling.
1206
1207         bl_props = [
1208                 bpy.props.StringProperty(attr="path", name="File Path", description="File path used for exporting the X3D file", maxlen= 1024, default= ""),
1209
1210                 bpy.props.BoolProperty(attr="apply_modifiers", name="Apply Modifiers", description="Use transformed mesh data from each object.", default=True),
1211                 bpy.props.BoolProperty(attr="triangulate", name="Triangulate", description="Triangulate quads.", default=False),
1212                 bpy.props.BoolProperty(attr="compress", name="Compress", description="GZip the resulting file, requires a full python install.", default=False),
1213         ]
1214         
1215         def execute(self, context):
1216                 x3d_export(self.path, context, self.apply_modifiers, self.triangulate, self.compress)
1217                 return ('FINISHED',)
1218         
1219         def invoke(self, context, event):
1220                 wm = context.manager
1221                 wm.add_fileselect(self.__operator__)
1222                 return ('RUNNING_MODAL',)
1223
1224 bpy.ops.add(EXPORT_OT_x3d)
1225
1226 import dynamic_menu
1227 menu_func = lambda self, context: self.layout.itemO("export.x3d", text="X3D Extensible 3D (.x3d)...")
1228 menu_item = dynamic_menu.add(bpy.types.INFO_MT_file_export, menu_func)
1229
1230 # NOTES
1231 # - blender version is hardcoded