"""
Edward Dale
2005-12-19
Computer Graphics 2
Ray Tracer
Copyright (c) 2005, 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."""

import timing
from cgtypes import vec3, mat4 # http://cgkit.sf.net
from math import pi
from PIL import Image
from PIL import ImageDraw
from primitives import *
from shaders import *

class Output:
    """
    The output of the ray tracer.
    TODO: Create static method to read configuration values from a file.
    """
    def __init__(self, filename="asdf.png", height=200, width=200, supersample=1, bgcolor=Color(0,0,0)):
        """
        Initialize things.
        """
        self.filename=filename
        self.realheight=height
        self.realwidth=width
        self.supersample=supersample
        self.height=self.realheight * self.supersample
        self.width=self.realwidth * self.supersample
        self.bgcolor=bgcolor
        self.open()

    def open(self):
        """
        Opens the output file.
        """
        self.im = Image.new( "RGB", (self.width, self.height), self.bgcolor.pilstr() )
        self.draw = ImageDraw.Draw( self.im )
    
    def close(self):
        """
        Does the finishing touches on the output file.
        """
        del self.draw
        output = open(self.filename, "w")
        self.im.resize((self.realwidth, self.realheight), Image.ANTIALIAS).save(output)
        output.close()
    
    def drawPixel(self, x, y, color):
        """
        Draws a pixel on the output.
        """
        self.draw.point((x,y), color.pilstr())

class Scene:
    """
    Represents the scene and all the parameters of it including the
    objects therein and the camera parameters.
    """
    def __init__(self):
        """
        Initializes everything.
        """
        self.objects = self.buildObjects()
        for i in self.objects:
            print i
        self.lights = self.buildLights()
        self.ambient = Lighting()

        self.d =20 # distance from eye to viewplane

        self.eye = vec3(-3.5, 2.5, 11) #world
        self.up = vec3(0,1,0)
        self.lookat = vec3(-2, 0, -10)
        self.dir = (self.eye-self.lookat).normalize()
        print "dir:%s"%self.dir
        print "dir(norm):%s"%self.dir.normalize()
        
        trans = mat4().lookAt(self.eye,self.lookat, self.up).inverse()
        self.rayorigin = vec3(trans*self.eye)
        print "eye(rayorigin):%s" % self.rayorigin
        
        viewnorm = -self.dir #dir.normalize()
        pointonplane = vec3((self.dir*self.d) + self.rayorigin)
        print "pointonplane:%s" % pointonplane
        
        self.ray = Ray( self.rayorigin, pointonplane, "Ray" )
        self.viewPlane = ViewPlane( viewnorm, pointonplane )
        print self.viewPlane
        
        self.planeCenter = self.viewPlane.intersect( self.ray )[0][0]
        print self.planeCenter

        # Translate the objects into camera coordinates        
        for i in self.objects:
            i.translate( trans )
        for i in self.lights:
            i.translate( trans )
        for i in self.objects:
            print i

    def buildLights(self):
        return [PointLight(pos=vec3(-3.5, 8, 11), lighting=Lighting() ),
#        PointLight(pos=vec3(20,0,0), lighting=Lighting()),
#        PointLight(pos=vec3(-20,0,0), lighting=Lighting())
]

    def buildObjects(self):
        """
        Creates all of the objects for the scene.
        """
        return [
            Sphere( pos=vec3(-3.5,2.25,6), radius=1, name="TransparentSphere", lighting=Lighting(ambient=Color(1,0,0)) ),
            Rectangle( normal=vec3(0,1,0), point=vec3(0), name="Checkerboard", lighting=Lighting(ambient=Color(0,1,0)), width=8, height=6),
            Sphere( pos=vec3(-1.5,1.25,4), radius=1, name="ReflectiveSphere",
lighting=Lighting(ambient=Color(0,0,1)) )
        ]        

output = Output()
scene = Scene()
shader = getShader( "flat", scene )

try:
    timing.start()
    for y in range(-output.height/2, output.height/2):
        for x in range(-output.width/2, output.width/2):
            target = scene.planeCenter + vec3( x*float(scene.d)/output.width, y*float(scene.d)/output.height , 0)
            #print target
            newray = Ray(scene.rayorigin, vec3(target), "Ray (%d,%d)"%(x,y))
            #print newray
     
            isects = []
            for i in scene.objects:
                isects += i.intersect(newray)
    
            if isects:
                deco = [ (abs(isect-scene.rayorigin), isect, normal, object) for isect, normal, object in isects ]
                deco.sort()
                isectDist, isect, isectNormal, isectObject = deco[0]
    
                color = shader.getColor(isectObject, isectNormal, isect)
                output.drawPixel(output.width/2-x-1,output.height/2-y-1, color )
finally:
    timing.finish()
    print "seconds:%d" % timing.seconds()
    output.close()
