package {
    import flash.ui.*;
    import flash.events.*;

    import org.papervision3d.objects.primitives.*;
    import org.papervision3d.materials.shadematerials.*;
    import org.papervision3d.materials.utils.*;
    import org.papervision3d.materials.*;
    import org.papervision3d.lights.*;
    import org.papervision3d.view.*;

    [SWF(width="400", height="400", backgroundColor="#FFFFFF", frameRate="30")]

    public class Pv3D20Sample1 extends BasicView {

        private var box:Cube;
        private var light:PointLight3D;
        private var frame:int = 0;
        private var gourandRender:Boolean = true;

        /**
         * コンストラクタ
         * 
         */
        public function Pv3D20Sample1() {
            super(400, 400);

            camera.z = -1500;

            light = new PointLight3D();
            light.x = light.y = light.z = 0;

            box = new Cube( getMaterialsList() );
            scene.addChild(box);

            addEventListener(Event.ENTER_FRAME, enterFrameHandler);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            startRendering();
        }

        /**
         * マテリアルリストの作成、取得
         * 
         */
        private function getMaterialsList() : MaterialsList{
            return new MaterialsList({ all: new GouraudMaterial(light,0xFFFFFF, 0x555555) });
        }

        /**
         * 毎フレームの処理
         * 
         */
        private function enterFrameHandler(event:Event):void {
            box.rotationY = frame*10;
            box.x = Math.cos(frame * 0.1) * 700;
            box.z = Math.sin(frame * 0.1) * 700;
            ++frame;
        }

        /**
         * キー入力処理
         * 
         */
        private function keyDownHandler(event:KeyboardEvent):void {

            switch(event.charCode){
            case Keyboard.ENTER:
                gourandRender = (gourandRender == true ? false : true);
                break;
            }

            if( gourandRender ){
                scene.removeChild(box);
                box = new Cube( getMaterialsList() );
                scene.addChild(box);
            }else{
                scene.removeChild(box);
                box = new Cube( new MaterialsList({ all: new WireframeMaterial( 0xDDDDDD, 100, 1 ) }) );
                scene.addChild(box);
            }
        }

    }
}