"""
Edward Dale
2006-2-20
Animation Algorithms
Articulated Figure Motion

Copyright (c) 2006, Edward Dale
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of Edward Dale nor the names of its contributors
  may be used to endorse or promote products derived from this software
  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

from os import environ
from cgkit.all import *
from cgkit.bvh import BVHReader
from math import pi,radians

class MyReader(BVHReader):
    """
    A BVH file reader that knows how to draw itself using the draw method.
    """
    def __init__(self,filename):
        """
        Initialize some stuff.
        """
        BVHReader.__init__(self,filename)
        self.values=[]
        self.minY=99999
    
    def onHierarchy(self, root):
        """
        Called after the hierarchy has been read.
        Stores the root and finds the lowest y of the model.
        """
        self.root=root
        self.findFloor([mat4().translation(vec3(self.root.offset))], self.root)
    
    def findFloor(self,stack,node):
        """
        Finds the floor by recursively examining each node and finding
        the minimum y-coordinate.
        """
        y=(stack[0]*vec3()).y
        if self.minY > y:
            self.minY = y
        for child in node.children:
            stack.insert(0, mat4(stack[0]).translate(vec3(child.offset)))        
            self.findFloor(stack,child)
            stack.pop(0)
                        
    def onFrame(self, values):
        """
        Called each time a frame is read.
        They're stored and used later to draw.
        """
        self.values.append(values)

    def draw(self,stack=None,node=None,t=0,c=0):
        """
        Recursively draws a node.
        If node is None, it uses the root.
        t is the frame number
        c is the offset in the values list for the frame
        """
        
        frame=self.values[t]
        if stack is None:
            stack=[mat4().translation(vec3(self.root.offset))]
            node=self.root

            # Get the rotation and offset of the root node
            if len(node.channels)==6:
                trans=vec3(frame[c], frame[c+1], frame[c+2])
                stack[0].translate(trans)
                rot=quat(mat3().fromEulerZXY(radians(frame[c+3]), 
                                             radians(frame[c+4]), 
                                             radians(frame[c+5]))).toAngleAxis()
                if rot[0]:
                    stack[0].rotate(rot[0],rot[1])
                c+=6
            else:
                # For simplicity
                raise "Non 6-channel root"

        # drawText( stack[0]*vec3(), node.name)
    
        for child in node.children:

            rot=None
            if len(child.channels)==3:
                rot=quat(mat3().fromEulerZXY(radians(frame[c]), 
                                             radians(frame[c+1]), 
                                             radians(frame[c+2]))).toAngleAxis()
                c+=3
            else:
                # If it's not 3, we just ignore it
                c += len(child.channels)

            # Make sure there's actually a rotation to be done
            if rot and rot[0]:
                stack[0].rotate(rot[0],rot[1])

            # Draw, recurse, etc.
            drawLine( stack[0]*vec3(), stack[0]*vec3(child.offset) )
            stack.insert(0, mat4(stack[0]).translate(vec3(child.offset)))
            self.draw(stack, child, t=t, c=c)
            stack.pop(0)            
        
scale = 400
# Lights
light = GLPointLight( pos = vec3(scale), intensity=0.8 )

# Camera
cam = TargetCamera(
    pos    = vec3(scale),
    up=vec3(0,1,0),
    target = vec3(0)
)

# Read the file specified in the environment variables
filename = environ.get("INFILE", "jog.bvh")
r=MyReader(filename)
r.read()

def modelCenter(time=0.0):
    """
    Returns the offset of the model at the current frame.
    """
    frame=r.values[int(getScene().timer().frame)]
    return vec3(r.root.offset)+vec3(frame[0], frame[1], frame[2])

# Connect the center of the model to the target slot of the camera to get 
# the camera to follow the model    
Follow = createFunctionComponent(modelCenter)
f=Follow()
f.output_slot.connect(cam.target_slot)

# Draw a plane
Plane(pos=vec3(r.root.offset)+vec3(0,r.minY,0), # At the bottom of the model
      lx=500,ly=500, # Big
      rot=mat3().rotation(pi/2,vec3(1,0,0)) # Rotate it to be on the xz plane
     )
     
def tick():
    """
    At each tick, draw the next frame of the animation.
    Disregards the sample rate of the input data
    """
    drawClear()
    r.draw(t=int(getScene().timer().frame))
    
eventmanager.eventManager().connect(STEP_FRAME, tick)