Advertisement
danfalck

exportWebGL.py

Jun 13th, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.87 KB | None | 0 0
  1. #***************************************************************************
  2. #*                                                                         *
  3. #*   Copyright (c) 2013                                                    *  
  4. #*   Yorik van Havre <yorik@uncreated.net>                                 *  
  5. #*   modified by Daniel Falck <ddfalck@gmail.com>                          *
  6. #*   This program is free software; you can redistribute it and/or modify  *
  7. #*   it under the terms of the GNU Lesser General Public License (LGPL)    *
  8. #*   as published by the Free Software Foundation; either version 2 of     *
  9. #*   the License, or (at your option) any later version.                   *
  10. #*   for detail see the LICENCE text file.                                 *
  11. #*                                                                         *
  12. #*   This program is distributed in the hope that it will be useful,       *
  13. #*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
  14. #*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
  15. #*   GNU Library General Public License for more details.                  *
  16. #*                                                                         *
  17. #*   You should have received a copy of the GNU Library General Public     *
  18. #*   License along with this program; if not, write to the Free Software   *
  19. #*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
  20. #*   USA                                                                   *
  21. #*                                                                         *
  22. #***************************************************************************
  23.  
  24. "FreeCAD webgl exporter"
  25.  
  26. import FreeCAD,Draft,Part,DraftGeomUtils
  27. if FreeCAD.GuiUp:
  28.     from DraftTools import translate
  29.  
  30. if FreeCAD.GuiUp:
  31.     import FreeCADGui
  32. else:
  33.     FreeCADGui = None
  34.  
  35. tab = "                "
  36. addWireframe = False
  37.  
  38. if open.__module__ == '__builtin__':
  39.     pythonopen = open
  40.    
  41.    
  42. def getHTML(objectsList):
  43.     "returns the complete HTML code of a viewer for the given objects"
  44.    
  45.     # get objects data
  46.     objectsData = ''
  47.     for obj in objectsList:
  48.         objectsData += getObjectData(obj)
  49.     template = getTemplate()
  50.     template = template.replace("$CameraData",getCameraData())
  51.     template = template.replace("$ObjectsData",objectsData)
  52.     return template
  53.    
  54. def getCameraData():
  55.     "returns the position and direction of the camera as three.js snippet"
  56.    
  57.     result = ""
  58.     if FreeCADGui:
  59.         # getting camera position
  60.         pos = FreeCADGui.ActiveDocument.ActiveView.viewPosition().Base
  61.         result += "camera.position.set( "
  62.         result += str(pos.x) + ", "
  63.         result += str(pos.y) + ", "
  64.         result += str(pos.z) + " );\n"
  65.     else:
  66.         result += "camera.position.set(200,250,200);\n"
  67.     result += tab+"camera.lookAt( scene.position );\n"+tab
  68.     # print result
  69.     return result
  70.    
  71. def getObjectData(obj,wireframeMode="multimaterial"):
  72.     """returns the geometry data of an object as three.js snippet. wireframeMode
  73.    can be multimaterial, faceloop or None"""
  74.    
  75.     result = ""
  76.     wires = []
  77.  
  78.     if obj.isDerivedFrom("Part::Feature"):
  79.         fcmesh = obj.Shape.tessellate(0.1)
  80.         result = "var geom = new THREE.Geometry();\n"
  81.         # adding vertices data
  82.         for i in range(len(fcmesh[0])):
  83.             v = fcmesh[0][i]
  84.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  85.         result += tab+"console.log(geom.vertices)\n"
  86.         for i in range(len(fcmesh[0])):
  87.             result += tab+"geom.vertices.push(v"+str(i)+");\n"
  88.         # adding facets data
  89.         for f in fcmesh[1]:
  90.             result += tab+"geom.faces.push( new THREE.Face3"+str(f)+" );\n"
  91.         for f in obj.Shape.Faces:
  92.             for w in f.Wires:
  93.                 wo = Part.Wire(DraftGeomUtils.sortEdges(w.Edges))
  94.                 p = []
  95.                 for v in wo.Vertexes:
  96.                     p.append(v.Point)
  97.                 p.append(wo.Vertexes[0].Point)
  98.                 wires.append(p)
  99.  
  100.     elif obj.isDerivedFrom("Part::TopoShape") :
  101.         fcmesh = obj.tessellate(0.1)
  102.         result = "var geom = new THREE.Geometry();\n"
  103.         # adding vertices data
  104.         for i in range(len(fcmesh[0])):
  105.             v = fcmesh[0][i]
  106.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  107.         result += tab+"console.log(geom.vertices)\n"
  108.         for i in range(len(fcmesh[0])):
  109.             result += tab+"geom.vertices.push(v"+str(i)+");\n"
  110.         # adding facets data
  111.         for f in fcmesh[1]:
  112.             result += tab+"geom.faces.push( new THREE.Face3"+str(f)+" );\n"
  113.         for f in obj.Faces:
  114.             for w in f.Wires:
  115.                 wo = Part.Wire(DraftGeomUtils.sortEdges(w.Edges))
  116.                 p = []
  117.                 for v in wo.Vertexes:
  118.                     p.append(v.Point)
  119.                 p.append(wo.Vertexes[0].Point)
  120.                 wires.append(p)
  121.  
  122.  
  123.     elif obj.isDerivedFrom("Mesh::Feature"):
  124.         mesh = obj.Mesh
  125.         result = "var geom = new THREE.Geometry();\n"
  126.         # adding vertices data
  127.         for p in mesh.Points:
  128.             v = p.Vector
  129.             i = p.Index
  130.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  131.         result += tab+"console.log(geom.vertices)\n"
  132.         for p in mesh.Points:
  133.             result += tab+"geom.vertices.push(v"+str(p.Index)+");\n"
  134.         # adding facets data
  135.         for f in mesh.Facets:
  136.             result += tab+"geom.faces.push( new THREE.Face3"+str(f.PointIndices)+" );\n"
  137.            
  138.     if result:
  139.         # adding a base material
  140.         if FreeCADGui:
  141.             col = obj.ViewObject.ShapeColor
  142.             rgb = Draft.getrgb(col,testbw=False)
  143.         else:
  144. #            rgb = "#f85500" # test color
  145.             rgb = "#cccccc"
  146.         result += tab+"var basematerial = new THREE.MeshBasicMaterial( { color: 0x"+str(rgb)[1:]+" } );\n"
  147.         #result += tab+"var basematerial = new THREE.MeshLambertMaterial( { color: 0x"+str(rgb)[1:]+" } );\n"
  148.         #result += tab+"var basematerial = new THREE.MeshPhongMaterial( { color: 0x"+str(rgb)[1:]+" } );\n"
  149.  
  150.         if wireframeMode == "faceloop":
  151.             # adding the mesh to the scene with a wireframe copy
  152.             result += tab+"var mesh = new THREE.Mesh( geom, basematerial );\n"
  153.             result += tab+"scene.add( mesh );\n"
  154.             result += tab+"var linematerial = new THREE.LineBasicMaterial({color: 0x000000,});\n"
  155.             for w in wires:
  156.                 result += tab+"var wire = new THREE.Geometry();\n"
  157.                 for p in w:
  158.                     result += tab+"wire.vertices.push(new THREE.Vector3("
  159.                     result += str(p.x)+", "+str(p.y)+", "+str(p.z)+"));\n"
  160.  
  161.                 result += tab+"var line = new THREE.Line(wire, linematerial);\n"
  162.                 result += tab+"scene.add(line);\n"
  163.            
  164.         elif wireframeMode == "multimaterial":
  165.             # adding a wireframe material
  166.             result += tab+"var wireframe = new THREE.MeshBasicMaterial( { color: "
  167.             result += "0x555555, wireframe: true, transparent: true } );\n"
  168.             result += tab+"var material = [ basematerial, wireframe ];\n"
  169.             result += tab+"var mesh = new THREE.SceneUtils.createMultiMaterialObject( geom, material );\n"
  170.             result += tab+"scene.add( mesh );\n"+tab
  171.  
  172.         elif wireframeMode == "edges":
  173.             # adding the mesh to the scene with a wireframe copy
  174. #            result += tab+"var mesh = new THREE.Mesh( geom, basematerial );\n"
  175. #            result += tab+"scene.add( mesh );\n"
  176. #            result += tab+"var linematerial = new THREE.LineBasicMaterial({color: 0x000000,});\n"
  177.             for f in obj.Faces:
  178.                 for w in f.Wires:
  179.                     for edge in w.Edges:
  180.                         if isinstance(edge.Curve,Part.Line):
  181. #                            result += tab+"wire.vertices.push(new THREE.Vector3("
  182.                             print "wire.vertices.push(new THREE.Vector3("
  183. #                            result += str(edge.Vertexes[1].X)+", "+str(edge.Vertexes[1].Y)+", "+str(edge.Vertexes[1].Z)+"));\n"
  184.                             print str(edge.Vertexes[1].X)+", "+str(edge.Vertexes[1].Y)+", "+str(edge.Vertexes[1].Z)+"));\n"
  185. #                        elif isinstance(edge.Curve,Part.Circle):
  186. #                            pass
  187.  
  188.         else:
  189.             # adding the mesh to the scene with simple material
  190.             result += tab+"var mesh = new THREE.Mesh( geom, basematerial );\n"
  191.             result += tab+"scene.add( mesh );\n"+tab
  192.        
  193.     return result
  194.  
  195. def getTemplate():
  196.     "returns a html template"
  197.    
  198.     result = """<!DOCTYPE html>
  199.        <html>
  200.        <head>
  201.            <title>FreeCAD model</title>
  202.            <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r50/three.min.js"></script>
  203.            
  204.            <script>
  205.            
  206.            var camera, controls, scene, renderer;
  207.            
  208.            window.onload = function() {
  209.  
  210.                var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
  211.                var VIEW_ANGLE = 35, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
  212.                //var ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 1000;
  213.                renderer = new THREE.WebGLRenderer();
  214.                //renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
  215.         renderer.setSize(SCREEN_WIDTH/2.0 , SCREEN_HEIGHT/2.0);
  216.                // Set the background color of the renderer to black, with full opacity
  217.                renderer.setClearColorHex(0x000000, 1);
  218.                //renderer.setClearColorHex(0x9797AA, 1);
  219.                
  220.                document.body.appendChild( renderer.domElement );
  221.        
  222.                scene = new THREE.Scene();
  223.        
  224.                camera = new THREE.PerspectiveCamera(
  225.                    VIEW_ANGLE,      // Field of view
  226.                    ASPECT,          // Aspect ratio
  227.                    NEAR,            // Near plane
  228.                    FAR              // Far plane
  229.                );
  230.  
  231.                //var camera = new THREE.OrthographicCamera( -SCREEN_WIDTH / 2, SCREEN_WIDTH / 2,   SCREEN_HEIGHT / 2, -SCREEN_HEIGHT / 2, NEAR, FAR );
  232.                $CameraData // placeholder for the FreeCAD camera
  233.                
  234.                controls = new THREE.TrackballControls( camera );
  235.                controls.rotateSpeed = 2.0;
  236.                controls.zoomSpeed = 1.2;
  237.                controls.panSpeed = 0.8;
  238.                controls.noZoom = false;
  239.                controls.noPan = false;
  240.                controls.staticMoving = true;
  241.                controls.dynamicDampingFactor = 0.3;
  242.                controls.keys = [ 65, 83, 68 ];
  243.        
  244.                $ObjectsData // placeholder for the FreeCAD objects
  245.        
  246.                //var light = new THREE.PointLight( 0xFFFF00 );
  247.                //light.position.set( -10000, -10000, 10000 );
  248.                //scene.add( light );
  249.                var directionalLight = new THREE.DirectionalLight(0xffffff);
  250.                directionalLight.position.set(1, 1, 1).normalize();
  251.                scene.add(directionalLight);
  252.                renderer.render( scene, camera );
  253.                
  254.                animate();
  255.            };
  256.            
  257.            function animate(){
  258.                requestAnimationFrame( animate );
  259.                render();
  260.            };
  261.            
  262.            function render(){
  263.                controls.update();
  264.                renderer.render( scene, camera );
  265.            };
  266.            </script>
  267.        </head>
  268.        <body></body>
  269.        </html>"""
  270.    
  271.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement