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