+# Some global settings
+
+class config:
+ polygons = dict()
+ polygons['FILL'] = True
+ polygons['STYLE'] = None
+ # Hidden to the user for now
+ polygons['EXPANSION_TRICK'] = True
+
+ edges = dict()
+ edges['SHOW'] = True
+ edges['SHOW_HIDDEN'] = False
+ edges['STYLE'] = 'silhouette'
+ edges['WIDTH'] = 2
+
+ output = dict()
+ output['FORMAT'] = 'SVG'
+ output['ANIMATION'] = False
+ output['MERGED_OBJECTS'] = True
+
+
+
+# ---------------------------------------------------------------------
+#
+## Utility Mesh class
+#
+# ---------------------------------------------------------------------
+class MeshUtils:
+
+ def getEdgeAdjacentFaces(edge, mesh):
+ """Get the faces adjacent to a given edge.
+
+ There can be 0, 1 or more (usually 2) faces adjacent to an edge.
+ """
+ adjface_list = []
+
+ for f in mesh.faces:
+ if (edge.v1 in f.v) and (edge.v2 in f.v):
+ adjface_list.append(f)
+
+ return adjface_list
+
+ def isVisibleEdge(e, mesh):
+ """Normal edge selection rule.
+
+ An edge is visible if _any_ of its adjacent faces is selected.
+ Note: if the edge has no adjacent faces we want to show it as well,
+ useful for "edge only" portion of objects.
+ """
+
+ adjacent_faces = MeshUtils.getEdgeAdjacentFaces(e, mesh)
+
+ if len(adjacent_faces) == 0:
+ return True
+
+ selected_faces = [f for f in adjacent_faces if f.sel]
+
+ if len(selected_faces) != 0:
+ return True
+ else:
+ return False
+
+ def isSilhouetteEdge(e, mesh):
+ """Silhuette selection rule.
+
+ An edge is a silhuette edge if it is shared by two faces with
+ different selection status or if it is a boundary edge of a selected
+ face.
+ """
+
+ adjacent_faces = MeshUtils.getEdgeAdjacentFaces(e, mesh)
+
+ if ((len(adjacent_faces) == 1 and adjacent_faces[0].sel == 1) or
+ (len(adjacent_faces) == 2 and
+ adjacent_faces[0].sel != adjacent_faces[1].sel)
+ ):
+ return True
+ else:
+ return False
+
+ def toonShading(u):
+
+ levels = 2
+ texels = 2*levels - 1
+ map = [0.0] + [(i)/float(texels-1) for i in range(1, texels-1) ] + [1.0]
+
+ v = 1.0
+ for i in range(0, len(map)-1):
+ pivot = (map[i]+map[i+1])/2.0
+ j = int(u>pivot)
+
+ v = map[i+j]
+
+ if v<map[i+1]:
+ return v
+
+ return v
+
+
+ getEdgeAdjacentFaces = staticmethod(getEdgeAdjacentFaces)
+ isVisibleEdge = staticmethod(isVisibleEdge)
+ isSilhouetteEdge = staticmethod(isSilhouetteEdge)
+ toonShading = staticmethod(toonShading)
+
+
+
+# ---------------------------------------------------------------------
+#
+## Projections classes
+#
+# ---------------------------------------------------------------------
+
+class Projector:
+ """Calculate the projection of an object given the camera.
+
+ A projector is useful to so some per-object transformation to obtain the
+ projection of an object given the camera.
+
+ The main method is #doProjection# see the method description for the
+ parameter list.
+ """
+
+ def __init__(self, cameraObj, canvasRatio):
+ """Calculate the projection matrix.
+
+ The projection matrix depends, in this case, on the camera settings.
+ TAKE CARE: This projector expects vertices in World Coordinates!
+ """
+
+ camera = cameraObj.getData()
+
+ aspect = float(canvasRatio[0])/float(canvasRatio[1])
+ near = camera.clipStart
+ far = camera.clipEnd
+
+ scale = float(camera.scale)
+
+ fovy = atan(0.5/aspect/(camera.lens/32))
+ fovy = fovy * 360.0/pi
+
+ # What projection do we want?
+ if camera.type:
+ #mP = self._calcOrthoMatrix(fovy, aspect, near, far, 17) #camera.scale)
+ mP = self._calcOrthoMatrix(fovy, aspect, near, far, scale)
+ else:
+ mP = self._calcPerspectiveMatrix(fovy, aspect, near, far)
+
+ # View transformation
+ cam = Matrix(cameraObj.getInverseMatrix())
+ cam.transpose()
+
+ mP = mP * cam
+
+ self.projectionMatrix = mP
+
+ ##
+ # Public methods
+ #
+
+ def doProjection(self, v):
+ """Project the point on the view plane.
+
+ Given a vertex calculate the projection using the current projection
+ matrix.
+ """
+
+ # Note that we have to work on the vertex using homogeneous coordinates
+ p = self.projectionMatrix * Vector(v).resize4D()
+
+ if p[3]>0:
+ p[0] = p[0]/p[3]
+ p[1] = p[1]/p[3]
+
+ # restore the size
+ p[3] = 1.0
+ p.resize3D()
+
+ return p
+
+ ##
+ # Private methods
+ #
+
+ def _calcPerspectiveMatrix(self, fovy, aspect, near, far):
+ """Return a perspective projection matrix.
+ """
+
+ top = near * tan(fovy * pi / 360.0)
+ bottom = -top
+ left = bottom*aspect
+ right= top*aspect
+ x = (2.0 * near) / (right-left)
+ y = (2.0 * near) / (top-bottom)
+ a = (right+left) / (right-left)
+ b = (top+bottom) / (top - bottom)
+ c = - ((far+near) / (far-near))
+ d = - ((2*far*near)/(far-near))
+
+ m = Matrix(
+ [x, 0.0, a, 0.0],
+ [0.0, y, b, 0.0],
+ [0.0, 0.0, c, d],
+ [0.0, 0.0, -1.0, 0.0])
+
+ return m
+
+ def _calcOrthoMatrix(self, fovy, aspect , near, far, scale):
+ """Return an orthogonal projection matrix.
+ """
+
+ # The 11 in the formula was found emiprically
+ top = near * tan(fovy * pi / 360.0) * (scale * 11)
+ bottom = -top
+ left = bottom * aspect
+ right= top * aspect
+ rl = right-left
+ tb = top-bottom
+ fn = near-far
+ tx = -((right+left)/rl)
+ ty = -((top+bottom)/tb)
+ tz = ((far+near)/fn)
+
+ m = Matrix(
+ [2.0/rl, 0.0, 0.0, tx],
+ [0.0, 2.0/tb, 0.0, ty],
+ [0.0, 0.0, 2.0/fn, tz],
+ [0.0, 0.0, 0.0, 1.0])
+
+ return m
+
+
+
+# ---------------------------------------------------------------------
+#
+## 2D Object representation class
+#
+# ---------------------------------------------------------------------
+
+# TODO: a class to represent the needed properties of a 2D vector image
+# For now just using a [N]Mesh structure.
+
+
+# ---------------------------------------------------------------------
+#
+## Vector Drawing Classes
+#
+# ---------------------------------------------------------------------
+
+## A generic Writer
+
+class VectorWriter:
+ """
+ A class for printing output in a vectorial format.
+
+ Given a 2D representation of the 3D scene the class is responsible to
+ write it is a vector format.
+
+ Every subclasses of VectorWriter must have at last the following public
+ methods:
+ - open(self)
+ - close(self)
+ - printCanvas(self, scene,
+ doPrintPolygons=True, doPrintEdges=False, showHiddenEdges=False):
+ """
+
+ def __init__(self, fileName):
+ """Set the output file name and other properties"""
+
+ self.outputFileName = fileName
+ self.file = None
+
+ context = Scene.GetCurrent().getRenderingContext()
+ self.canvasSize = ( context.imageSizeX(), context.imageSizeY() )
+
+ self.startFrame = 1
+ self.endFrame = 1
+ self.animation = False
+
+
+ ##
+ # Public Methods
+ #
+
+ def open(self, startFrame=1, endFrame=1):
+ if startFrame != endFrame:
+ self.startFrame = startFrame
+ self.endFrame = endFrame
+ self.animation = True
+
+ self.file = open(self.outputFileName, "w")
+ print "Outputting to: ", self.outputFileName
+
+ return
+
+ def close(self):
+ self.file.close()
+ return
+
+ def printCanvas(self, scene, doPrintPolygons=True, doPrintEdges=False,
+ showHiddenEdges=False):
+ """This is the interface for the needed printing routine.
+ """
+ return
+
+
+## SVG Writer
+
+class SVGVectorWriter(VectorWriter):
+ """A concrete class for writing SVG output.
+ """
+
+ def __init__(self, fileName):
+ """Simply call the parent Contructor.
+ """
+ VectorWriter.__init__(self, fileName)
+
+
+ ##
+ # Public Methods
+ #
+
+ def open(self, startFrame=1, endFrame=1):
+ """Do some initialization operations.
+ """
+ VectorWriter.open(self, startFrame, endFrame)
+ self._printHeader()
+
+ def close(self):
+ """Do some finalization operation.
+ """
+ self._printFooter()
+
+ # remember to call the close method of the parent
+ VectorWriter.close(self)
+
+
+ def printCanvas(self, scene, doPrintPolygons=True, doPrintEdges=False,
+ showHiddenEdges=False):
+ """Convert the scene representation to SVG.
+ """
+
+ Objects = scene.getChildren()
+
+ context = scene.getRenderingContext()
+ framenumber = context.currentFrame()
+
+ if self.animation:
+ framestyle = "display:none"
+ else:
+ framestyle = "display:block"
+
+ # Assign an id to this group so we can set properties on it using DOM
+ self.file.write("<g id=\"frame%d\" style=\"%s\">\n" %
+ (framenumber, framestyle) )
+
+
+ for obj in Objects:
+
+ if(obj.getType() != 'Mesh'):
+ continue
+
+ self.file.write("<g id=\"%s\">\n" % obj.getName())
+
+ mesh = obj.getData(mesh=1)
+
+ if doPrintPolygons:
+ self._printPolygons(mesh)
+
+ if doPrintEdges:
+ self._printEdges(mesh, showHiddenEdges)
+
+ self.file.write("</g>\n")
+
+ self.file.write("</g>\n")
+
+
+ ##
+ # Private Methods
+ #
+
+ def _calcCanvasCoord(self, v):
+ """Convert vertex in scene coordinates to canvas coordinates.
+ """
+
+ pt = Vector([0, 0, 0])
+
+ mW = float(self.canvasSize[0])/2.0
+ mH = float(self.canvasSize[1])/2.0
+
+ # rescale to canvas size
+ pt[0] = v.co[0]*mW + mW
+ pt[1] = v.co[1]*mH + mH
+ pt[2] = v.co[2]
+
+ # For now we want (0,0) in the top-left corner of the canvas.
+ # Mirror and translate along y
+ pt[1] *= -1
+ pt[1] += self.canvasSize[1]
+
+ return pt
+
+ def _printHeader(self):
+ """Print SVG header."""
+
+ self.file.write("<?xml version=\"1.0\"?>\n")
+ self.file.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n")
+ self.file.write("\t\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
+ self.file.write("<svg version=\"1.1\"\n")
+ self.file.write("\txmlns=\"http://www.w3.org/2000/svg\"\n")
+ self.file.write("\twidth=\"%d\" height=\"%d\" streamable=\"true\">\n\n" %
+ self.canvasSize)
+
+ if self.animation:
+
+ self.file.write("""\n<script><![CDATA[
+ globalStartFrame=%d;
+ globalEndFrame=%d;
+
+ /* FIXME: Use 1000 as interval as lower values gives problems */
+ timerID = setInterval("NextFrame()", 1000);
+ globalFrameCounter=%d;
+
+ function NextFrame()
+ {
+ currentElement = document.getElementById('frame'+globalFrameCounter)
+ previousElement = document.getElementById('frame'+(globalFrameCounter-1))
+
+ if (!currentElement)
+ {
+ return;
+ }
+
+ if (globalFrameCounter > globalEndFrame)
+ {
+ clearInterval(timerID)
+ }
+ else
+ {
+ if(previousElement)
+ {
+ previousElement.style.display="none";
+ }
+ currentElement.style.display="block";
+ globalFrameCounter++;
+ }
+ }
+ \n]]></script>\n
+ \n""" % (self.startFrame, self.endFrame, self.startFrame) )
+
+ def _printFooter(self):
+ """Print the SVG footer."""
+
+ self.file.write("\n</svg>\n")
+
+ def _printPolygons(self, mesh):
+ """Print the selected (visible) polygons.
+ """
+
+ if len(mesh.faces) == 0:
+ return
+
+ self.file.write("<g>\n")
+
+ for face in mesh.faces:
+ if not face.sel:
+ continue
+
+ self.file.write("<polygon points=\"")
+
+ for v in face:
+ p = self._calcCanvasCoord(v)
+ self.file.write("%g,%g " % (p[0], p[1]))
+
+ # get rid of the last blank space, just cosmetics here.
+ self.file.seek(-1, 1)
+ self.file.write("\"\n")
+
+ # take as face color the first vertex color
+ # TODO: the average of vetrex colors?
+ if face.col:
+ fcol = face.col[0]
+ color = [fcol.r, fcol.g, fcol.b, fcol.a]
+ else:
+ color = [255, 255, 255, 255]
+
+ # use the stroke property to alleviate the "adjacent edges" problem,
+ # we simulate polygon expansion using borders,
+ # see http://www.antigrain.com/svg/index.html for more info
+ stroke_col = color
+ stroke_width = 0.5
+
+ # Convert the color to the #RRGGBB form
+ str_col = "#%02X%02X%02X" % (color[0], color[1], color[2])
+
+ # Handle transparent polygons
+ opacity_string = ""
+ if color[3] != 255:
+ opacity = float(color[3])/255.0
+ opacity_string = " fill-opacity: %g; stroke-opacity: %g; opacity: 1;" % (opacity, opacity)
+
+ self.file.write("\tstyle=\"fill:" + str_col + ";")
+ self.file.write(opacity_string)
+ if config.polygons['EXPANSION_TRICK']:
+ self.file.write(" stroke:" + str_col + ";")
+ self.file.write(" stroke-width:" + str(stroke_width) + ";\n")
+ self.file.write(" stroke-linecap:round;stroke-linejoin:round")
+ self.file.write("\"/>\n")
+
+ self.file.write("</g>\n")
+
+ def _printEdges(self, mesh, showHiddenEdges=False):
+ """Print the wireframe using mesh edges.
+ """
+
+ stroke_width=EDGES_WIDTH
+ stroke_col = [0, 0, 0]
+
+ self.file.write("<g>\n")
+
+ for e in mesh.edges:
+
+ hidden_stroke_style = ""
+
+ if e.sel == 0:
+ if showHiddenEdges == False:
+ continue
+ else:
+ hidden_stroke_style = ";\n stroke-dasharray:3, 3"
+
+ p1 = self._calcCanvasCoord(e.v1)
+ p2 = self._calcCanvasCoord(e.v2)
+
+ self.file.write("<line x1=\"%g\" y1=\"%g\" x2=\"%g\" y2=\"%g\"\n"
+ % ( p1[0], p1[1], p2[0], p2[1] ) )
+ self.file.write(" style=\"stroke:rgb("+str(stroke_col[0])+","+str(stroke_col[1])+","+str(stroke_col[2])+");")
+ self.file.write(" stroke-width:"+str(stroke_width)+";\n")
+ self.file.write(" stroke-linecap:round;stroke-linejoin:round")
+ self.file.write(hidden_stroke_style)
+ self.file.write("\"/>\n")
+
+ self.file.write("</g>\n")
+
+
+
+# ---------------------------------------------------------------------
+#
+## Rendering Classes
+#
+# ---------------------------------------------------------------------
+
+# A dictionary to collect all the different edge styles and their edge
+# selection criteria
+edgeSelectionStyles = {
+ 'normal': MeshUtils.isVisibleEdge,
+ 'silhouette': MeshUtils.isSilhouetteEdge
+ }
+
+# A dictionary to collect the supported output formats
+outputWriters = {
+ 'SVG': SVGVectorWriter,
+ }
+
+
+class Renderer:
+ """Render a scene viewed from a given camera.
+
+ This class is responsible of the rendering process, transformation and
+ projection of the objects in the scene are invoked by the renderer.
+
+ The rendering is done using the active camera for the current scene.
+ """
+
+ def __init__(self):
+ """Make the rendering process only for the current scene by default.
+
+ We will work on a copy of the scene, be sure that the current scene do
+ not get modified in any way.
+ """
+
+ # Render the current Scene, this should be a READ-ONLY property
+ self._SCENE = Scene.GetCurrent()
+
+ # Use the aspect ratio of the scene rendering context
+ context = self._SCENE.getRenderingContext()
+
+ aspect_ratio = float(context.imageSizeX())/float(context.imageSizeY())
+ self.canvasRatio = (float(context.aspectRatioX())*aspect_ratio,
+ float(context.aspectRatioY())
+ )
+
+ # Render from the currently active camera
+ self.cameraObj = self._SCENE.getCurrentCamera()
+
+ # Get a projector for this camera.
+ # NOTE: the projector wants object in world coordinates,
+ # so we should remember to apply modelview transformations
+ # _before_ we do projection transformations.
+ self.proj = Projector(self.cameraObj, self.canvasRatio)
+
+ # Get the list of lighting sources
+ obj_lst = self._SCENE.getChildren()
+ self.lights = [ o for o in obj_lst if o.getType() == 'Lamp']
+
+ # When there are no lights we use a default lighting source
+ # that have the same position of the camera
+ if len(self.lights) == 0:
+ l = Lamp.New('Lamp')
+ lobj = Object.New('Lamp')
+ lobj.loc = self.cameraObj.loc
+ lobj.link(l)
+ self.lights.append(lobj)
+
+
+ ##
+ # Public Methods
+ #
+
+ def doRendering(self, outputWriter, animation=False):
+ """Render picture or animation and write it out.
+
+ The parameters are:
+ - a Vector writer object that will be used to output the result.
+ - a flag to tell if we want to render an animation or only the
+ current frame.
+ """
+
+ context = self._SCENE.getRenderingContext()
+ currentFrame = context.currentFrame()
+
+ # Handle the animation case
+ if not animation:
+ startFrame = currentFrame
+ endFrame = startFrame
+ outputWriter.open()
+ else:
+ startFrame = context.startFrame()
+ endFrame = context.endFrame()
+ outputWriter.open(startFrame, endFrame)
+
+ # Do the rendering process frame by frame
+ print "Start Rendering!"
+ for f in range(startFrame, endFrame+1):
+ context.currentFrame(f)
+
+ # Use some temporary workspace, a full copy of the scene
+ inputScene = self._SCENE.copy(2)
+
+ print "Before"
+
+ try:
+ renderedScene = self.doRenderScene(inputScene)
+ except:
+ self._SCENE.makeCurrent()
+ Scene.unlink(inputScene)
+ del inputScene
+
+ outputWriter.printCanvas(renderedScene,
+ doPrintPolygons = config.polygons['FILL'],
+ doPrintEdges = config.edges['SHOW'],
+ showHiddenEdges = config.edges['SHOW_HIDDEN'])
+
+ print "After"
+
+ # clear the rendered scene
+ self._SCENE.makeCurrent()
+ Scene.unlink(renderedScene)
+ del renderedScene
+
+ outputWriter.close()
+ print "Done!"
+ context.currentFrame(currentFrame)