home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2005 November / WNnov2005.iso / Windows / Equipement / Blender / blender-2.37a-windows.exe / $_5_ / .blender / scripts / wrl2export.py < prev    next >
Text File  |  2005-06-13  |  40KB  |  1,015 lines

  1. #!BPY
  2. """ Registration info for Blender menus:
  3. Name: 'VRML 97 (old version)...'
  4. Blender: 232
  5. Group: 'Export'
  6. Submenu: 'All Objects...' all
  7. Submenu: 'Selected Objects...' selected
  8. Tooltip: 'Old version of VRML2 exporter, please try the newer one'
  9. """
  10.  
  11. __author__ = ("Rick Kimball", "Ken Miller", "Steve Matthews")
  12. __url__ = ["blender", "elysiun",
  13. "Author's (Rick) homepage, http://kimballsoftware.com/blender",
  14. "Show your VRML world at vrmlworld.net, http://vrmlworld.net"]
  15. __version__ = "2004/01/19"
  16.  
  17. __bpydoc__ = """\
  18. This script exports to VRML 2.0 format.
  19.  
  20. Usage:
  21.  
  22. Run this script from "File->Export" menu.  A pop-up will ask whether you
  23. want to export only selected or all relevant objects.
  24.  
  25. Known issues:<br>
  26.     Doesn't handle multiple materials (don't use material indices);<br>
  27.     Doesn't handle multiple UV textures on a single mesh (create a mesh
  28. for each texture);<br>
  29.     Material colors need work;<br>
  30.     Spotlight softness needs work;<br>
  31.     Can't get the texture array associated with material * not the UV ones;<br>
  32.     Can't set smoothing, crease angle and mesh smoothing * setting not
  33.     accessible.
  34. """
  35.  
  36.  
  37. # $Id: wrl2export.py,v 1.5 2005/06/12 23:40:46 ianwill Exp $
  38. #
  39. #------------------------------------------------------------------------
  40. # VRML2 exporter for blender 2.28a or above
  41. #
  42. # Source: http://blender.kimballsoftware.com/
  43. #
  44. # Authors: Rick Kimball with much inspiration
  45. #         from the forum at www.elysiun.com
  46. #         and irc://irc.freenode.net/blenderchat
  47. #         Ken Miller and Steve Matthews (Added Camera Support)
  48. #
  49. # ***** BEGIN GPL LICENSE BLOCK *****
  50. #
  51. # Copyright (C) 2003,2004: Rick Kimball rick@vrmlworld.net
  52. #
  53. # This program is free software; you can redistribute it and/or
  54. # modify it under the terms of the GNU General Public License
  55. # as published by the Free Software Foundation; either version 2
  56. # of the License, or (at your option) any later version.
  57. #
  58. # This program is distributed in the hope that it will be useful,
  59. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  60. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  61. # GNU General Public License for more details.
  62. #
  63. # You should have received a copy of the GNU General Public License
  64. # along with this program; if not, write to the Free Software Foundation,
  65. # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  66. #
  67. # ***** END GPL LICENCE BLOCK *****
  68. #
  69. # To use script:
  70. # 1.) load this file in the text window.
  71. #     (press SHIFT+F11, Open New via Datablock button)
  72. # 2.) make sure your mouse is over the text edit window and
  73. #     run this script. (press ALT+P)
  74. # Or:
  75. #   copy to the scripts directory and it will appear in the
  76. #   export list. (Needs 2.32 or higher)
  77. #
  78. # Notes:
  79. #  a.) output filename is same as current blender file with .wrl extension
  80. #  b.) error messages go to the Blender DOS console window
  81. #
  82. # The latest version of this python export script:
  83. #   http://blender.kimballsoftware.com/
  84. #
  85. # If you like this script, try using http://vrmlworld.net/
  86. # to show off your VRML world.
  87. #
  88. # 2004-01-19 by Rick Kimball <rick@vrmlworld.net>
  89. #  o added sub menus and file selector dialog
  90. #
  91. # 2004-01-17 by Rick Kimball <rick@vrmlworld.net>
  92. #  o add meta comments so script will appear in export menu list
  93. #
  94. # 2003-11-01 by Rick Kimball <rick@vrmlworld.net>
  95. #  o fixed issues related to Lamp object and 2.28a API.
  96. #
  97. # 2003-07-19 by Rick Kimball <rick@vrmlworld.net>
  98. #  o made compatible with new Python API in 2.28
  99. #
  100. # 2003-01-16 by Ken Miller - with math help from Steve Matthews :)
  101. #   o Added support for exporting cameras out of Blender
  102. #   o Sets the name of the camera as the object name
  103. #   o sets the description of the camera as the object name,
  104. #     which should be modified to something meaningful
  105. #   o sets the position and orientation
  106. #
  107. # 2003-01-19 Rick Kimball <rick@vrmlworld.net>
  108. #   o Added Support For PointLight, SpotLight and DirectionalLight using Lamps
  109. #   o Creates multi singlesided or doublesided IFS
  110. #   o Creates IndexedLineSets if DrawTypes is WIRE instead of Shaded
  111. #
  112. # 2003-02-03 Rick Kimball <rick@vrmlworld.net>
  113. #   o attempts to catch exceptions for empty objects
  114. #
  115. # 2003-02-04 Rick Kimball <rick@vrmlworld.net>
  116. #   o fixed file overwrite problem when blender filename is all uppercase
  117. #
  118. # 2003-02-08 Rick Kimball <rick@vrmlworld.net>
  119. #   o cleanStr() creates valid VRML DEF names even if object.name
  120. #     is zero length or uses VRML reserved names or characters
  121. #
  122. #------------------------------------------------------------------------
  123. # Known Issue:
  124. #  o doesn't handle multiple materials (don't use material indices)
  125. #  o doesn't handle multiple UV textures on a single mesh. (create a mesh for each texture)
  126. #  o material colors need work
  127. #  o spotlight softness needs work
  128. #  o can't get the texture array associated with material * not the UV ones
  129. #  o can't set smoothing, crease angle and mesh smoothing * setting not accesible
  130. #
  131. # Still Todo:
  132. #
  133. #  - Support for material indexes
  134. #  - Automatically Split IFS when multiple UV textures found * warning only now
  135. #  - Automatically Split IFS when combination of single vs double sided
  136. #  - Automatically Split IFS when face with only 2 vertices is found should be an ILS
  137. #  - Export common coordinate map for split IFS
  138. #  - Intelligent color array vs color index
  139. #  - Support more blender objects: World
  140. #  - Figure out how to output Animation
  141. #  - Add GUI to control the following:
  142. #    o All/Layer/Object output radio button
  143. #    o Color per vertex toggle yes/no
  144. #    o Complex/Simple VRML output radio button
  145. #    o Compressed/Uncompressed output radio button
  146. #    o Decimal precision dropdown 1,2,3,4,5,6
  147. #    o IFS/Elevation Grid output radio button
  148. #    o Normals output toggle yes/no
  149. #    o Proto output toggle yes/no
  150. #    o Verbose console progress
  151.  
  152. import Blender
  153. from Blender import NMesh, Lamp
  154. import math
  155.  
  156.  
  157. #-- module constants
  158. radD=math.pi/180.0
  159. rad90=90.0*radD      # for rotation
  160. rad30=30.0*radD      # default crease angle
  161. ARG=''
  162.  
  163. #------------------------------------------------------------------------
  164. #-- utility functions and classes --
  165. #------------------------------------------------------------------------
  166. def rad2deg(v):
  167.     return round(v*180.0/math.pi,4)
  168.  
  169. def deg2rad(v):
  170.     return (v*math.pi)/180.0;
  171.  
  172. class DrawTypes:
  173.     """Object DrawTypes enum values
  174.     BOUNDS - draw only the bounding box of the object
  175.     WIRE - draw object as a wire frame
  176.     SOLID - draw object with flat shading
  177.     SHADED - draw object with OpenGL shading
  178. """
  179.     BOUNDBOX  = 1
  180.     WIRE      = 2
  181.     SOLID     = 3
  182.     SHADED    = 4
  183.     TEXTURE   = 5
  184.  
  185. #------------------------------------------------------
  186. # the Blender.Object class seems to be missing this...
  187. #------------------------------------------------------
  188. if not hasattr(Blender.Object,'DrawTypes'):
  189.     Blender.Object.DrawTypes = DrawTypes()
  190.  
  191. #------------------------------------------------------------------------
  192. #-- VRML2Export --
  193. #------------------------------------------------------------------------
  194. class VRML2Export:
  195.     #------------------------------------------------------------------------
  196.     def __init__(self, filename):
  197.         #--- public you can change these ---
  198.         self.verbose=1     # level of verbosity in console 0-none, 1-some, 2-most
  199.         self.cp=3          # decimals for material color values     0.000 - 1.000
  200.         self.vp=3          # decimals for vertex coordinate values  0.000 - n.000
  201.         self.tp=3          # decimals for texture coordinate values 0.000 - 1.000
  202.         self.ambientIntensity=.2
  203.         self.defCreaseAngle=rad30
  204.         self.smooth=0
  205.         
  206.         #--- class private don't touch ---
  207.         self.texNames={}   # dictionary of textureNames
  208.         self.matNames={}   # dictionary of materiaNames
  209.         self.indentLevel=0 # keeps track of current indenting
  210.         self.filename=filename
  211.         self.file = open(filename, "w")
  212.         self.bNav=0
  213.         self.nNodeID=0
  214.         self.VRMLReserved=[ "Anchor","Appearance","Anchor","AudioClip","Background",
  215.                             "Billboard", "Box", "Collision", "Color", "ColorInterpolator",
  216.                             "Cone", "Coordinate", "CoordinateInterpolator", "Cylinder",
  217.                             "CylinderSensor", "DirectionalLight", "ElevationGrid",
  218.                             "Extrustion", "Fog", "FontStyle", "Group", "ImageTexture",
  219.                             "IndexedFaceSet", "IndexedLineSet", "Inline", "LOD",
  220.                             "Material", "MovieTexture", "NavigationInfo", "Normal",
  221.                             "NormalInterpolator","OrientationInterpolator", "PixelTexture",
  222.                             "PlaneSensor", "PointLight", "PointSet", "PositionInterpolator",
  223.                             "ProxmimitySensor", "ScalarInterpolator", "Script", "Shape",
  224.                             "Sound", "Sphere", "SphereSensor", "SpotLight", "Switch",
  225.                             "Text", "TextureCoordinate", "TextureTransform", "TimeSensor",
  226.                             "TouchSensor", "Transform", "Viewpoint", "VisibilitySensor",
  227.                             "WorldInfo"
  228.                             ]
  229.  
  230.     #------------------------------------------------------------------------
  231.     # writeHeader, export file, cleanup
  232.     #------------------------------------------------------------------------
  233.     def writeHeader(self):
  234.         self.file.write("#VRML V2.0 utf8\n")
  235.         self.file.write("# modeled using blender3d http://blender.org/$\n")
  236.         self.file.write("# exported using wrl2export.py version $Revision: 1.5 $\n")
  237.         self.file.write("# get latest exporter at http://kimballsoftware.com/blender/\n\n")
  238.     
  239.     def export(self, scene):
  240.         print "Info: starting VRML2 export to " + self.filename + "..."
  241.     
  242.         self.writeHeader()
  243.         theObjects = []
  244.         if ARG == 'selected':
  245.             theObjects = Blender.Object.GetSelected()
  246.         else:
  247.             theObjects = scene.getChildren()
  248.             
  249.         for object in theObjects:
  250.             try:
  251.                 objType=object.getType()
  252.  
  253.                 if objType == "Mesh":
  254.                     self.writeIndexedFaceSet(object, normals = 0)
  255.                 elif objType == "Camera":
  256.                     self.writeCameraInfo(object)
  257.                 elif objType == "Lamp":
  258.                     # if there is a lamp then we probably want to turn off the headlight
  259.                     if self.bNav == 0:
  260.                         self.writeNavigationInfo()
  261.                         self.bNav=1
  262.                     #endif
  263.                 
  264.                     lamp=Lamp.Get(object.data.getName())
  265.                     try:
  266.                         lampType=lamp.getType()
  267.  
  268.                         if lampType == Lamp.Types.Lamp:
  269.                             self.writePointLight(object, lamp)
  270.                         elif lampType == Lamp.Types.Spot:
  271.                             self.writeSpotLight(object, lamp)
  272.                         elif lampType == Lamp.Types.Sun:
  273.                             self.writeDirectionalLight(object, lamp)
  274.                         else:
  275.                             self.writeDirectionalLight(object, lamp)
  276.                         #endif
  277.                     except AttributeError:
  278.                         print "Error: Unable to get type info for %s" % object.name
  279.                 else:
  280.                     print "Info: Ignoring [%s], object type [%s] not handle yet" % \
  281.                           (object.name,object.getType())
  282.                 #endif
  283.             except ValueError:
  284.                 print "Error: object named %s has problem with accessing an attribute" % object.name
  285.             #end try
  286.         #endfor
  287.         self.cleanup()
  288.  
  289.     def cleanup(self):
  290.         self.file.close()
  291.         self.texNames={}
  292.         self.matNames={}
  293.         self.indentLevel=0
  294.         print "Info: finished VRML2 export to %s\n" % self.filename
  295.  
  296.     #------------------------------------------------------------------------
  297.     # Writes out camera info as a viewpoint
  298.     # Handles orientation, position
  299.     # Use camera object name to set description
  300.     #------------------------------------------------------------------------
  301.     def writeCameraInfo(self, object):
  302.         if self.verbose > 0:
  303.             print "Info: exporting camera named="+object.name
  304.         #endif
  305.         
  306.         self.writeIndented("DEF %s Viewpoint {\n" % (self.cleanStr(object.name)), 1)
  307.         
  308.         self.writeIndented("description \"%s\" \n" % (object.name))
  309.         
  310.         # get the camera location, subtract 90 degress from X to orient like VRML does
  311.         loc = self.rotatePointForVRML(object.loc)
  312.         rot = [object.RotX - 1.57, object.RotY, object.RotZ]
  313.         nRot = self.rotatePointForVRML(rot)
  314.         
  315.         # convert to Quaternion and to Angle Axis
  316.         Q  = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
  317.         Q1 = self.multiplyQuaternions(Q[0], Q[1])
  318.         Qf = self.multiplyQuaternions(Q1, Q[2])
  319.         angleAxis = self.quaternionToAngleAxis(Qf)
  320.         
  321.         # write orientation statement
  322.         self.writeIndented("orientation %3.2f %3.2f %3.2f %3.2f\n" %
  323.                            (angleAxis[0], angleAxis[1], -angleAxis[2], angleAxis[3]))
  324.         
  325.         # write position statement
  326.         self.writeIndented("position %3.2f %3.2f %3.2f\n" %
  327.                            (loc[0], loc[1], loc[2]))
  328.         
  329.         self.writeIndented("} # Viewpoint\n", -1)
  330.         
  331.         self.writeIndented("\n")
  332.  
  333.     #------------------------------------------------------------------------
  334.     def writeIndexedFaceSet(self, object, normals = 0):
  335.         if self.verbose > 0:
  336.             print "Info: exporting mesh named=["+object.name+"]"
  337.         #endif
  338.  
  339.         imageMap={}   # set of used images
  340.         sided={}      # 'one':cnt , 'two':cnt
  341.         vColors={}    # 'multi':1
  342.  
  343.         mesh=object.getData()
  344.  
  345.         nIFSCnt=self.countIFSSetsNeeded(mesh, imageMap, sided, vColors)
  346.  
  347.         meshName = self.cleanStr(object.name)
  348.         
  349.         if nIFSCnt > 1:
  350.             self.writeIndented("DEF %s%s Group {\n" % ("G_", meshName),1)
  351.             self.writeIndented("children [\n",1)
  352.         #endif
  353.         
  354.         if self.verbose > 0:
  355.             print "Debug: [%s] has %d UV Textures" % (object.name, nIFSCnt)
  356.         #endif
  357.  
  358.         if sided.has_key('two') and sided['two'] > 0:
  359.             bTwoSided=1
  360.         else:
  361.             bTwoSided=0
  362.  
  363.         self.writeIndented("DEF %s Shape {\n" % meshName,1)
  364.     
  365.         # show script debugging info
  366.         if self.verbose > 1:
  367.             self.meshToString(mesh)
  368.             print "Debug: mesh.faces["
  369.             for face in mesh.faces:
  370.                 self.faceToString(face)
  371.             #endfor
  372.             print "Debug: ]"
  373.         #endif
  374.         
  375.         maters=mesh.materials
  376.         hasImageTexture=0
  377.  
  378.         if len(maters) > 0 or mesh.hasFaceUV():
  379.             self.writeIndented("appearance Appearance {\n", 1)
  380.             
  381.             # right now this script can only handle a single material per mesh.
  382.             if len(maters) >= 1:
  383.                 mat=Blender.Material.Get(maters[0].name)
  384.                 self.writeMaterial(mat, self.cleanStr(maters[0].name,'mat_'))
  385.                 if len(maters) > 1:
  386.                     print "Warning: mesh named %s has multiple materials" % meshName
  387.                     print "Warning: only one material per object handled"
  388.                 #endif
  389.             else:
  390.                 self.writeIndented("material NULL\n")
  391.             #endif
  392.         
  393.             #-- textures
  394.             if mesh.hasFaceUV():
  395.                 for face in mesh.faces:
  396.                     if (hasImageTexture == 0) and (face.image):
  397.                         self.writeImageTexture(face.image.name)
  398.                         hasImageTexture=1  # keep track of face texture
  399.                     #endif
  400.                 #endfor
  401.             #endif
  402.  
  403.             self.writeIndented("} # Appearance\n", -1)
  404.         #endif
  405.  
  406.         #-------------------------------------------------------------------
  407.         #--
  408.         #-- IndexedFaceSet or IndexedLineSet
  409.         #
  410.  
  411.         # check if object is wireframe only
  412.         if object.drawType == Blender.Object.DrawTypes.WIRE:
  413.             # user selected WIRE=2 on the Drawtype=Wire on (F9) Edit page
  414.             ifStyle="IndexedLineSet"
  415.         else:
  416.             # user selected BOUNDS=1, SOLID=3, SHARED=4, or TEXTURE=5
  417.             ifStyle="IndexedFaceSet"
  418.         #endif
  419.         
  420.         self.writeIndented("geometry %s {\n" % ifStyle, 1)
  421.         if object.drawType != Blender.Object.DrawTypes.WIRE:
  422.             if bTwoSided == 1:
  423.                 self.writeIndented("solid FALSE # two sided\n")
  424.             else:
  425.                 self.writeIndented("solid TRUE # one sided\n")
  426.             #endif
  427.         #endif
  428.         
  429.         #---
  430.         #--- output coordinates
  431.         self.writeCoordinates(object, mesh, meshName)
  432.         
  433.         if object.drawType != Blender.Object.DrawTypes.WIRE:
  434.             #---
  435.             #--- output textureCoordinates if UV texture used
  436.             if mesh.hasFaceUV():
  437.                 if hasImageTexture == 1:
  438.                     self.writeTextureCoordinates(mesh)
  439.                     if vColors.has_key('multi'):
  440.                         self.writeVertexColors(mesh) # experiment
  441.                     #endif
  442.                 else:
  443.                     self.writeFaceColors(mesh)
  444.                 #endif hasImageTexture
  445.             #endif hasFaceUV
  446.  
  447.             # TBD: figure out how to get this properly
  448.             if self.smooth:
  449.                 creaseAngle=self.defCreaseAngle;
  450.                 self.writeIndented("creaseAngle %s\n" % creaseAngle)
  451.             else:
  452.                 self.writeIndented("creaseAngle 0.0 # in radians\n")
  453.             #endif mesh.smooth
  454.         #endif WIRE
  455.  
  456.         #--- output vertexColors
  457.         if mesh.hasVertexColours() and vColors.has_key('multi'):
  458.             self.writeVertexColors(mesh)
  459.         #endif
  460.  
  461.         #--- output closing braces
  462.         self.writeIndented("} # %s\n" % ifStyle, -1)
  463.         self.writeIndented("} # Shape\n", -1)
  464.  
  465.         if nIFSCnt > 1:
  466.             self.writeIndented("] # children\n", -1)
  467.             self.writeIndented("} # Group\n", -1)
  468.         #endif
  469.  
  470.         self.writeIndented("\n")
  471.  
  472.     #------------------------------------------------------------------------
  473.     def writeCoordinates(self, object, mesh, meshName):
  474.         #-- vertices
  475.         self.writeIndented("coord DEF %s%s Coordinate {\n" % ("coord_",meshName), 1)
  476.         self.writeIndented("point [\n", 1)
  477.         meshVertexList = mesh.verts
  478.  
  479.         # create vertex list and pre rotate -90 degrees X for VRML
  480.         mm=object.getMatrix()
  481.         for vertex in meshVertexList:
  482.             v=self.rotVertex(mm, vertex);
  483.             self.writeIndented("%s %s %s,\n" %
  484.                                (round(v[0],self.vp),
  485.                                 round(v[1],self.vp),
  486.                                 round(v[2],self.vp) ))
  487.         #endfor
  488.         self.writeIndented("] # point\n", -1)
  489.         self.writeIndented("} # Coordinate\n", -1)
  490.  
  491.         self.writeIndented("coordIndex [\n", 1)
  492.         coordIndexList=[]  
  493.         for face in mesh.faces:
  494.             cordStr=""
  495.             for i in range(len(face)):
  496.                 indx=meshVertexList.index(face[i])
  497.                 cordStr = cordStr + "%s, " % indx
  498.             #endfor
  499.             self.writeIndented(cordStr + "-1,\n")
  500.         #endfor
  501.         self.writeIndented("] # coordIndex\n", -1)
  502.  
  503.     #------------------------------------------------------------------------
  504.     def writeTextureCoordinates(self, mesh):
  505.         texCoordList=[] 
  506.         texIndexList=[]
  507.         j=0
  508.  
  509.         for face in mesh.faces:
  510.             for i in range(len(face)):
  511.                 texIndexList.append(j)
  512.                 texCoordList.append(face.uv[i])
  513.                 j=j+1
  514.             #endfor
  515.             texIndexList.append(-1)
  516.         #endfor
  517.  
  518.         self.writeIndented("texCoord TextureCoordinate {\n", 1)
  519.         self.writeIndented("point [\n", 1)
  520.         for i in range(len(texCoordList)):
  521.             self.writeIndented("%s %s," %
  522.                                (round(texCoordList[i][0],self.tp), 
  523.                                 round(texCoordList[i][1],self.tp))+"\n")
  524.         #endfor
  525.         self.writeIndented("] # point\n", -1)
  526.         self.writeIndented("} # texCoord\n", -1)
  527.  
  528.         self.writeIndented("texCoordIndex [\n", 1)
  529.         texIndxStr=""
  530.         for i in range(len(texIndexList)):
  531.             texIndxStr = texIndxStr + "%d, " % texIndexList[i]
  532.             if texIndexList[i]==-1:
  533.                 self.writeIndented(texIndxStr + "\n")
  534.                 texIndxStr=""
  535.             #endif
  536.         #endfor
  537.         self.writeIndented("] # texCoordIndex\n", -1)
  538.  
  539.     #------------------------------------------------------------------------
  540.     def writeFaceColors(self, mesh):
  541.         self.writeIndented("colorPerVertex FALSE\n")
  542.         self.writeIndented("color Color {\n",1)
  543.         self.writeIndented("color [\n",1)
  544.  
  545.         for face in mesh.faces:
  546.             if face.col:
  547.                 c=face.col[0]
  548.                 if self.verbose > 1:
  549.                     print "Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b)
  550.                 #endif
  551.  
  552.                 aColor = self.rgbToFS(c)
  553.                 self.writeIndented("%s,\n" % aColor)
  554.         #endfor
  555.  
  556.         self.writeIndented("] # color\n",-1)
  557.         self.writeIndented("} # Color\n",-1)
  558.  
  559.     #------------------------------------------------------------------------
  560.     def writeVertexColors(self, mesh):
  561.         self.writeIndented("colorPerVertex TRUE\n")
  562.         self.writeIndented("color Color {\n",1)
  563.         self.writeIndented("color [\n",1)
  564.  
  565.         for i in range(len(mesh.verts)):
  566.             c=self.getVertexColorByIndx(mesh,i)
  567.             if self.verbose > 1:
  568.                 print "Debug: vertex[%d].col r=%d g=%d b=%d" % (i, c.r, c.g, c.b)
  569.             #endif
  570.  
  571.             aColor = self.rgbToFS(c)
  572.             self.writeIndented("%s,\n" % aColor)
  573.         #endfor
  574.  
  575.         self.writeIndented("] # color\n",-1)
  576.         self.writeIndented("} # Color\n",-1)
  577.  
  578.     #------------------------------------------------------------------------
  579.     def writeMaterial(self, mat, matName):
  580.         # look up material name, use it if available
  581.         if self.matNames.has_key(matName):
  582.             self.writeIndented("material USE %s\n" % matName)
  583.             self.matNames[matName]+=1
  584.             return;
  585.         #endif
  586.  
  587.         self.matNames[matName]=1
  588.  
  589.         ambient = mat.amb
  590.         diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
  591.         emisR, emisG, emisB = diffuseR*mat.emit, diffuseG*mat.emit, diffuseB*mat.emit
  592.         shininess = mat.hard/255.0
  593.         specR = mat.specCol[0]
  594.         specG = mat.specCol[1]
  595.         specB = mat.specCol[2]
  596.         transp = 1-mat.alpha
  597.  
  598.         self.writeIndented("material DEF %s Material {\n" % matName, 1)
  599.         self.writeIndented("diffuseColor %s %s %s" %
  600.                            (round(diffuseR,self.cp), round(diffuseG,self.cp), round(diffuseB,self.cp)) +
  601.                            "\n")
  602.         self.writeIndented("ambientIntensity %s" %
  603.                            (round(ambient,self.cp))+
  604.                            "\n")
  605.         self.writeIndented("specularColor %s %s %s" %
  606.                            (round(specR,self.cp), round(specG,self.cp), round(specB,self.cp)) +
  607.                            "\n" )
  608.         self.writeIndented("emissiveColor  %s %s %s" %
  609.                            (round(emisR,self.cp), round(emisG,self.cp), round(emisB,self.cp)) +
  610.                            "\n" )
  611.         self.writeIndented("shininess %s" %
  612.                            (round(shininess,self.cp)) +
  613.                            "\n" )
  614.         self.writeIndented("transparency %s" %
  615.                            (round(transp,self.cp)) +
  616.                            "\n")
  617.         self.writeIndented("} # Material\n",-1)
  618.  
  619.     #------------------------------------------------------------------------
  620.     def writeImageTexture(self, name):
  621.         if self.texNames.has_key(name):
  622.             self.writeIndented("texture USE %s\n" % self.cleanStr(name))
  623.             self.texNames[name] += 1
  624.             return
  625.         else:
  626.             self.writeIndented("texture DEF %s ImageTexture {\n" % self.cleanStr(name), 1)
  627.             self.writeIndented("url \"%s\"\n" % name)
  628.             self.writeIndented("} # ImageTexture \n",-1)
  629.             self.texNames[name] = 1
  630.         #endif
  631.  
  632.     #------------------------------------------------------------------------
  633.     def writeSpotLight(self, object, lamp):
  634.         safeName = self.cleanStr(object.name)
  635.  
  636.         # compute cutoff and beamwidth
  637.         intensity=min(lamp.energy/1.5,1.0) # TBD: figure out the right value
  638.  
  639.         beamWidth=deg2rad(lamp.spotSize)*.5;
  640.         cutOffAngle=beamWidth*.99
  641.  
  642.         (dx,dy,dz)=self.computeDirection(object)
  643.         # note -dx seems to equal om[3][0]
  644.         # note -dz seems to equal om[3][1]
  645.         # note  dy seems to equal om[3][2]
  646.         om = object.getMatrix()
  647.             
  648.         location=self.rotVertex(om, (0,0,0));
  649.         radius = lamp.dist*math.cos(beamWidth)
  650.         self.writeIndented("DEF %s SpotLight {\n" % safeName,1)
  651.         self.writeIndented("radius %s\n" % radius )
  652.         self.writeIndented("intensity %s\n" % intensity )
  653.         self.writeIndented("beamWidth %s # lamp.spotSize %s\n" % (beamWidth, lamp.spotSize) )
  654.         self.writeIndented("cutOffAngle %s # lamp.spotBlend %s\n" % (cutOffAngle, lamp.spotBlend))
  655.         self.writeIndented("direction %s %s %s # lamp.RotX=%s RotY=%s RotZ=%s\n" % \
  656.                            (round(dx,3),round(dy,3),round(dz,3),
  657.                             round(rad2deg(object.RotX),3),
  658.                             round(rad2deg(object.RotY),3),
  659.                             round(rad2deg(object.RotZ),3)))
  660.         self.writeIndented("location %s %s %s\n" % (round(location[0],3),
  661.                                                     round(location[1],3),
  662.                                                     round(location[2],3)))
  663.         self.writeIndented("} # SpotLight\n",-1)
  664.  
  665.         # export a cone that matches the spotlight in verbose mode
  666.         if self.verbose > 1:
  667.             self.writeIndented("#generated visible spotlight cone\n")
  668.             self.writeIndented("Transform { # Spotlight Cone\n",1)
  669.             self.writeIndented("translation %s %s %s\n" % (round(location[0],3),
  670.                                                            round(location[1],3),
  671.                                                            round(location[2],3)))
  672.             rot = [object.RotX, object.RotY, object.RotZ]
  673.             nRot = self.rotatePointForVRML(rot)
  674.             
  675.             # convert to Quaternion and to Angle Axis
  676.             Q  = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
  677.             Q1 = self.multiplyQuaternions(Q[0], Q[1])
  678.             Qf = self.multiplyQuaternions(Q1, Q[2])
  679.             angleAxis = self.quaternionToAngleAxis(Qf)
  680.             
  681.             # write orientation statement
  682.             self.writeIndented("rotation %3.2f %3.2f %3.2f %3.2f\n" %
  683.                                (angleAxis[0], angleAxis[1], -angleAxis[2], angleAxis[3]))
  684.             
  685.             self.writeIndented("children [\n",1)
  686.             
  687.             ch=radius
  688.             br=ch*math.sin(beamWidth)
  689.             self.writeIndented("Transform {\n",1)
  690.             self.writeIndented("translation 0 -%s 0\n" % (ch/2))
  691.             self.writeIndented("children ")
  692.             self.writeIndented("Collision {\n",1)
  693.             self.writeIndented("collide FALSE children Shape {\n",1)
  694.             self.writeIndented("geometry Cone { height %s bottomRadius %s }\n" % (ch, br))
  695.             self.writeIndented("appearance Appearance{\n",1)
  696.             self.writeIndented("material Material { diffuseColor 1 1 1 transparency .8 }\n")
  697.             self.writeIndented("} # Appearance\n",-1)
  698.             self.writeIndented("} # Shape\n",-1)
  699.             self.writeIndented("} # Collision\n",-1)
  700.             self.writeIndented("} # Transform visible cone \n",-1)
  701.             self.writeIndented("] # Spot children\n",-1)
  702.             self.writeIndented("} # SpotLight Cone Transform\n",-1)
  703.         #endif debug cone
  704.         self.writeIndented("\n")
  705.         
  706.     #------------------------------------------------------------------------
  707.     def writeDirectionalLight(self, object, lamp):
  708.         safeName = self.cleanStr(object.name)
  709.  
  710.         intensity=min(lamp.energy/1.5, 1.0) # TBD: figure out the right value
  711.         (dx,dy,dz)=self.computeDirection(object)
  712.  
  713.         self.writeIndented("DEF %s DirectionalLight {\n" % safeName,1)
  714.         self.writeIndented("ambientIntensity %s\n" % self.ambientIntensity )
  715.         self.writeIndented("intensity %s\n" % intensity )
  716.         self.writeIndented("direction %s %s %s\n" % (round(dx,4),round(dy,4),round(dz,4)))
  717.         self.writeIndented("} # DirectionalLight\n",-1)
  718.         self.writeIndented("\n")
  719.  
  720.     #------------------------------------------------------------------------
  721.     def writePointLight(self, object, lamp):
  722.         safeName = self.cleanStr(object.name)
  723.  
  724.         om = object.getMatrix()
  725.         location=self.rotVertex(om, (0,0,0));
  726.         intensity=min(lamp.energy/1.5,1.0) # TBD: figure out the right value
  727.  
  728.         radius = lamp.dist
  729.         self.writeIndented("DEF %s PointLight {\n" % safeName,1)
  730.         self.writeIndented("ambientIntensity %s\n" % self.ambientIntensity )
  731.         self.writeIndented("intensity %s\n" % intensity )
  732.         self.writeIndented("location %s %s %s\n" % (round(location[0],3),
  733.                                                     round(location[1],3),
  734.                                                     round(location[2],3)))
  735.         self.writeIndented("radius %s\n" % radius )
  736.         self.writeIndented("} # PointLight\n",-1)
  737.         self.writeIndented("\n")
  738.  
  739.     #------------------------------------------------------------------------
  740.     def writeNavigationInfo(self):
  741.         self.writeIndented("NavigationInfo {\n",1)
  742.         self.writeIndented("headlight FALSE\n")
  743.         self.writeIndented("avatarSize [0.25, 1.75, 0.75]\n")
  744.         self.writeIndented("} # NavigationInfo\n",-1)
  745.         self.writeIndented("\n")
  746.  
  747.     #------------------------------------------------------------------------
  748.     #--- Utility methods
  749.     #------------------------------------------------------------------------
  750.  
  751.     def cleanStr(self, name, prefix='rsvd_'):
  752.         """cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
  753.  
  754.         newName=name[:]
  755.         if len(newName) == 0:
  756.             self.nNodeID+=1
  757.             return "%s%d" % (prefix, self.nNodeID)
  758.         
  759.         if newName in self.VRMLReserved:
  760.             newName='%s%s' % (prefix,newName)
  761.         #endif
  762.         
  763.         if newName[0] in ['0','1','2','3','4','5','6','7','8','9']:
  764.             newName='%s%s' % ('_',newName)
  765.         #endif
  766.  
  767.         for bad in [' ','"','#',"'",',','.','[','\\',']','{','}']:
  768.             newName=newName.replace(bad,'_')
  769.         return newName
  770.  
  771.     def countIFSSetsNeeded(self, mesh, imageMap, sided, vColors):
  772.         """
  773.         countIFFSetsNeeded() - should look at a blender mesh to determine
  774.         how many VRML IndexFaceSets or IndexLineSets are needed.  A
  775.         new mesh created under the following conditions:
  776.         
  777.          o - split by UV Textures / one per mesh
  778.          o - split by face, one sided and two sided
  779.          o - split by smooth and flat faces
  780.          o - split when faces only have 2 vertices * needs to be an IndexLineSet
  781.         """
  782.         
  783.         imageNameMap={}
  784.         faceMap={}
  785.         nFaceIndx=0
  786.         
  787.         for face in mesh.faces:
  788.             sidename='';
  789.             if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
  790.                 sidename='two'
  791.             else:
  792.                 sidename='one'
  793.             #endif
  794.  
  795.             if not vColors.has_key('multi'):
  796.                 for face in mesh.faces:
  797.                     if face.col:
  798.                         c=face.col[0]
  799.                         if c.r != 255 and c.g != 255 and c.b !=255:
  800.                             vColors['multi']=1
  801.                         #endif
  802.                     #endif
  803.                 #endfor
  804.             #endif
  805.  
  806.             if sided.has_key(sidename):
  807.                 sided[sidename]+=1
  808.             else:
  809.                 sided[sidename]=1
  810.             #endif
  811.  
  812.             if face.image:
  813.                 faceName="%s_%s" % (face.image.name, sidename);
  814.  
  815.                 if imageMap.has_key(faceName):
  816.                     imageMap[faceName].append(face)
  817.                 else:
  818.                     imageMap[faceName]=[face.image.name,sidename,face]
  819.                 #endif
  820.             #endif
  821.         #endfor
  822.  
  823.         if self.verbose > 0:
  824.             for faceName in imageMap.keys():
  825.                 ifs=imageMap[faceName]
  826.                 print "Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
  827.                       (faceName, ifs[0], ifs[1], len(ifs)-2)
  828.             #endif
  829.         #endif
  830.  
  831.         return len(imageMap.keys())
  832.     
  833.     def faceToString(self,face):
  834.         print "Debug: face.flag=0x%x (bitflags)" % face.flag
  835.         if face.flag & NMesh.FaceFlags.SELECT == NMesh.FaceFlags.SELECT:
  836.             print "Debug: face.flag.SELECT=true"
  837.         #endif
  838.  
  839.         print "Debug: face.mode=0x%x (bitflags)" % face.mode
  840.         if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
  841.             print "Debug: face.mode twosided"
  842.         #endif
  843.  
  844.         print "Debug: face.transp=0x%x (enum)" % face.transp
  845.         if face.transp == NMesh.FaceTranspModes.SOLID:
  846.             print "Debug: face.transp.SOLID"
  847.         #
  848.  
  849.         if face.image:
  850.             print "Debug: face.image=%s" % face.image.name
  851.         #endif
  852.         print "Debug: face.materialIndex=%d" % face.materialIndex
  853.  
  854.     def getVertexColorByIndx(self, mesh, indx):
  855.         for face in mesh.faces:
  856.             j=0
  857.             for vertex in face.v:
  858.                 if vertex.index == indx:
  859.                     c=face.col[j]
  860.                 #endif
  861.                 j=j+1
  862.             #endfor
  863.         #endfor
  864.         return c
  865.  
  866.     def meshToString(self,mesh):
  867.         print "Debug: mesh.hasVertexUV=%d" % mesh.hasVertexUV()
  868.         print "Debug: mesh.hasFaceUV=%d" % mesh.hasFaceUV()
  869.         print "Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours()
  870.         print "Debug: mesh.verts=%d" % len(mesh.verts)
  871.         print "Debug: mesh.faces=%d" % len(mesh.faces)
  872.         print "Debug: mesh.materials=%d" % len(mesh.materials)
  873.  
  874.     def rgbToFS(self, c):
  875.         s="%s %s %s" % (
  876.             round(c.r/255.0,self.cp),
  877.             round(c.g/255.0,self.cp),
  878.             round(c.b/255.0,self.cp))
  879.         return s
  880.  
  881.     def computeDirection(self, object):
  882.         x,y,z=(0,-1.0,0) # point down
  883.         ax,ay,az = (object.RotX,object.RotZ,object.RotY)
  884.  
  885.         # rot X
  886.         x1=x
  887.         y1=y*math.cos(ax)-z*math.sin(ax)
  888.         z1=y*math.sin(ax)+z*math.cos(ax)
  889.  
  890.         # rot Y
  891.         x2=x1*math.cos(ay)+z1*math.sin(ay)
  892.         y2=y1
  893.         z2=z1*math.cos(ay)-x1*math.sin(ay)
  894.  
  895.         # rot Z
  896.         x3=x2*math.cos(az)-y2*math.sin(az)
  897.         y3=x2*math.sin(az)+y2*math.cos(az)
  898.         z3=z2
  899.  
  900.         return [x3,y3,z3]
  901.         
  902.  
  903.     # swap Y and Z to handle axis difference between Blender and VRML
  904.     #------------------------------------------------------------------------
  905.     def rotatePointForVRML(self, v):
  906.         x = v[0]
  907.         y = v[2]
  908.         z = -v[1]
  909.         
  910.         vrmlPoint=[x, y, z]
  911.         return vrmlPoint
  912.     
  913.     def rotVertex(self, mm, v):
  914.         lx,ly,lz=v[0],v[1],v[2]
  915.         gx=(mm[0][0]*lx + mm[1][0]*ly + mm[2][0]*lz) + mm[3][0]
  916.         gy=((mm[0][2]*lx + mm[1][2]*ly+ mm[2][2]*lz) + mm[3][2])
  917.         gz=-((mm[0][1]*lx + mm[1][1]*ly + mm[2][1]*lz) + mm[3][1])
  918.         rotatedv=[gx,gy,gz]
  919.         return rotatedv
  920.  
  921.     def writeIndented(self, s, inc=0):
  922.         if inc < 1:
  923.             self.indentLevel = self.indentLevel + inc
  924.         #endif
  925.  
  926.         spaces=""
  927.         for x in xrange(self.indentLevel):
  928.             spaces = spaces + "   "
  929.         #endfor
  930.         self.file.write(spaces + s)
  931.  
  932.         if inc > 0:
  933.             self.indentLevel = self.indentLevel + inc
  934.         #endif
  935.  
  936.     # Converts a Euler to three new Quaternions
  937.     # Angles of Euler are passed in as radians
  938.     #------------------------------------------------------------------------
  939.     def eulerToQuaternions(self, x, y, z):
  940.         Qx = [math.cos(x/2), math.sin(x/2), 0, 0]
  941.         Qy = [math.cos(y/2), 0, math.sin(y/2), 0]
  942.         Qz = [math.cos(z/2), 0, 0, math.sin(z/2)]
  943.         
  944.         quaternionVec=[Qx,Qy,Qz]
  945.         return quaternionVec
  946.     
  947.     # Multiply two Quaternions together to get a new Quaternion
  948.     #------------------------------------------------------------------------
  949.     def multiplyQuaternions(self, Q1, Q2):
  950.         result = [((Q1[0] * Q2[0]) - (Q1[1] * Q2[1]) - (Q1[2] * Q2[2]) - (Q1[3] * Q2[3])),
  951.                   ((Q1[0] * Q2[1]) + (Q1[1] * Q2[0]) + (Q1[2] * Q2[3]) - (Q1[3] * Q2[2])),
  952.                   ((Q1[0] * Q2[2]) + (Q1[2] * Q2[0]) + (Q1[3] * Q2[1]) - (Q1[1] * Q2[3])),
  953.                   ((Q1[0] * Q2[3]) + (Q1[3] * Q2[0]) + (Q1[1] * Q2[2]) - (Q1[2] * Q2[1]))]
  954.         
  955.         return result
  956.     
  957.     # Convert a Quaternion to an Angle Axis (ax, ay, az, angle)
  958.     # angle is in radians
  959.     #------------------------------------------------------------------------
  960.     def quaternionToAngleAxis(self, Qf):
  961.         scale = math.pow(Qf[1],2) + math.pow(Qf[2],2) + math.pow(Qf[3],2)
  962.         ax = Qf[1]
  963.         ay = Qf[2]
  964.         az = Qf[3]
  965.  
  966.         if scale > .0001:
  967.             ax/=scale
  968.             ay/=scale
  969.             az/=scale
  970.         #endif
  971.         
  972.         angle = 2 * math.acos(Qf[0])
  973.         
  974.         result = [ax, ay, az, angle]
  975.         return result
  976.  
  977. def file_callback(filename):
  978.     if filename.find('.wrl', -4) < 0: filename += '.wrl'
  979.     wrlexport=VRML2Export(filename)
  980.     scene = Blender.Scene.getCurrent()
  981.     wrlexport.export(scene)
  982. #enddef
  983.     
  984. #------------------------------------------------------------------------
  985. # main routine
  986. #------------------------------------------------------------------------
  987. print "\nThis is the old version of the vrml 2 (or 97) exporter."
  988. print "It should be removed soon, please try the updated 'VRML 97' version.\n"
  989.  
  990. try:
  991.     ARG = __script__['arg'] # user selected argument
  992. except:
  993.     print "older version"
  994.  
  995. if Blender.Get('version') < 225:
  996.     print "Warning: VRML2 export failed, wrong blender version!"
  997.     print " You aren't running blender version 2.25 or greater"
  998.     print " download a newer version from http://blender.org/"
  999. else:
  1000.     if ARG == 'all' or ARG == 'selected':
  1001.         Blender.Window.FileSelector(file_callback,"Export VRML 2.0")
  1002.     else:
  1003.         baseFileName=Blender.Get('filename')
  1004.         if baseFileName.find('.') != -1:
  1005.             dots=Blender.Get('filename').split('.')[0:-1]
  1006.         else:
  1007.             dots=[baseFileName]
  1008.         #endif
  1009.         dots+=["wrl"]
  1010.         vrmlFile=".".join(dots)
  1011.  
  1012.         file_callback(vrmlFile)
  1013.     #endif
  1014. #endif
  1015.