// http://alteredqualia.com/three/examples/webgl_postprocessing_ssao.html
        // http://alteredqualia.com/three/examples/webgl_cars.html
        // http://alteredqualia.com/xg/examples/animation_physics_terrain.html

        // https://chrome.google.com/webstore/detail/webglhzblendcharacter/cgnjcccfcjhdnbfgjgllglbhfcgndmea

        // Could not connect to the feed specified at 'http://my.jsc-solutions.net/nuget'. P
        // https://github.com/dotnet/roslyn/issues/98


        //Icon image is missing.
        //At least one new-style screenshot or video is required.
        //Small tile image is missing.
        //Please select a Primary Category for your item.
        //Language is not selected.

        // 640x400
        // 128x128
        // 440x280

        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150128

            Console.WriteLine("enter WebGLHZBlendCharacter");

            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                Console.WriteLine("invoke TheServerWithAppWindow.Invoke");
                ChromeTCPServer.TheServerWithAppWindow.Invoke(AppSource.Text);

                return;
            }
            #endregion


            { TexturesImages ref0; }

            // http://www.realitymeltdown.com/WebGL3/character-controller.html

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150127
            //Native.css
            Native.body.style.margin = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            //Error CS0246  The type or namespace name 'THREE' could not be found(are you missing a using directive or an assembly reference?)	WebGLHZBlendCharacter Application.cs  46
            // used by, for?
            var clock = new THREE.Clock();
            //var keys = new { LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, A = 65, S = 83, D = 68, W = 87 };


            var scene = new THREE.Scene();
            var skyScene = new THREE.Scene();

            scene.fog = new THREE.Fog(0xA26D41, 1000, 20000);

            //scene.add(new THREE.AmbientLight(0xaaaaaa));
            scene.add(new THREE.AmbientLight(0xffffff));

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            var light = new THREE.DirectionalLight(0xffffff, 1.0);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;
            //xlight.shadowCameraVisible = true;

            scene.add(light);

            var renderer = new THREE.WebGLRenderer(new { antialias = true, alpha = false });
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.autoClear = false;
            renderer.shadowMapEnabled = true;
            renderer.shadowMapType = THREE.PCFSoftShadowMap;

            renderer.domElement.AttachToDocument();

            // this will mess up
            // three.OrbitControls.js
            // onMouseMove

            //new IStyle(renderer.domElement)
            //{
            //    position = IStyle.PositionEnum.absolute,
            //    left = "0px",
            //    top = "0px",
            //    right = "0px",
            //    bottom = "0px",
            //};


            //new { }.With(
            //    async delegate
            //    {

            //        await Native.window.async.onresize;

            //        // if the reload were fast, then we could actually do that:D
            //        Native.document.location.reload();

            //    }
            //);





            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            var plane = new THREE.Mesh(planeGeometry,
                    new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

                );
            plane.castShadow = false;
            plane.receiveShadow = true;


            {

                var parent = new THREE.Object3D();
                parent.add(plane);
                parent.rotation.x = -Math.PI / 2;
                parent.scale.set(100, 100, 100);

                scene.add(parent);
            }

            var random = new Random();
            var meshArray = new List<THREE.Mesh>();
            var geometry = new THREE.CubeGeometry(1, 1, 1);

            for (var i = 1; i < 100; i++)
            {

                //THREE.MeshPhongMaterial
                var ii = new THREE.Mesh(geometry,


                    new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

                    //new THREE.MeshLambertMaterial(
                    //new
                    //{
                    //    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
                    //    specular = 0xffaaaa,
                    //    ambient= 0x050505, 
                    //})

                    );
                ii.position.x = i % 2 * 500 - 2.5f;

                // raise it up
                ii.position.y = .5f * 100;
                ii.position.z = -1 * i * 400;
                ii.castShadow = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);

            }
            #endregion


            #region HZCannon
            new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
                async cube =>
                {
                    // https://github.com/mrdoob/three.js/issues/1285
                    //cube.children.WithEach(c => c.castShadow = true);

                    //cube.traverse(
                    //    new Action<THREE.Object3D>(
                    //        child =>
                    //        {
                    //            // does it work? do we need it?
                    //            //if (child is THREE.Mesh)

                    //            child.castShadow = true;
                    //            //child.receiveShadow = true;

                    //        }
                    //    )
                    //);

                    // um can edit and continue insert code going back in time?
                    cube.scale.x = 10.0;
                    cube.scale.y = 10.0;
                    cube.scale.z = 10.0;



                    //cube.castShadow = true;
                    //dae.receiveShadow = true;

                    //cube.position.x = -100;

                    ////cube.position.y = (cube.scale.y * 50) / 2;
                    //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                    // if i want to rotate, how do I do it?
                    //cube.rotation.z = random() + Math.PI;
                    //cube.rotation.x = random() + Math.PI;
                    var sw = Stopwatch.StartNew();



                    scene.add(cube);
                    //interactiveObjects.Add(cube);


                    while (true)
                    {
                        await Native.window.async.onframe;

                        cube.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;

                    }
                }
            );
            #endregion



            var blendMesh = new THREE.SpeedBlendCharacter();
            blendMesh.load(
                new Models.marine_anims().Content.src,
                new Action(
                    delegate
                    {
                        // buildScene
                        //blendMesh.rotation.y = Math.PI * -135 / 180;
                        blendMesh.castShadow = true;
                        // we cannot scale down we want our shadows
                        //blendMesh.scale.set(0.1, 0.1, 0.1);

                        scene.add(blendMesh);

                        var xtrue = true;
                        // run
                        blendMesh.setSpeed(1.0);
                        blendMesh.showSkeleton(!xtrue);

                        var radius = blendMesh.geometry.boundingSphere.radius;


                        Native.document.title = new { radius }.ToString();


                        var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                        camera.position.set(0.0, radius * 3, radius * 3.5);

                        var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                        skyCamera.position.set(0.0, radius * 3, radius * 3.5);

                        var controls = new THREE.OrbitControls(camera);
                        //controls.noPan = true;


                        //var loader = new THREE.JSONLoader();
                        //loader.load(new Models.ground().Content.src,
                        //    new Action<THREE.Geometry, THREE.Material[]>(

                        //    (xgeometry, materials) =>
                        //    {

                        //        var ground = new THREE.Mesh(xgeometry, materials[0]);
                        //        ground.scale.set(20, 20, 20);
                        //        ground.receiveShadow = true;
                        //        ground.castShadow = true;
                        //        scene.add(ground);

                        //    }
                        //    )
                        // );

                        #region  createSky

                        var urls = new[] {
                            new px().src, new nx().src,
                            new py().src, new ny().src,
                            new pz().src, new nz().src,
                         };

                        var textureCube = THREE.ImageUtils.loadTextureCube(urls);

                        dynamic shader = THREE.ShaderLib["cube"];
                        shader.uniforms["tCube"].value = textureCube;

                        // We're inside the box, so make sure to render the backsides
                        // It will typically be rendered first in the scene and without depth so anything else will be drawn in front
                        var material = new THREE.ShaderMaterial(new
                        {
                            fragmentShader = shader.fragmentShader,
                            vertexShader = shader.vertexShader,
                            uniforms = shader.uniforms,
                            depthWrite = false,
                            side = THREE.BackSide
                        });

                        // THREE.CubeGeometry has been renamed to THREE.BoxGeometry
                        // The box dimension size doesn't matter that much when the camera is in the center.  Experiment with the values.
                        var skyMesh = new THREE.Mesh(new THREE.CubeGeometry(10000, 10000, 10000, 1, 1, 1), material);
                        //skyMesh.renderDepth = -10;


                        skyScene.add(skyMesh);
                        #endregion




                        ////var renderTarget = new THREE.WebGLRenderTarget((int)Native.window.Width, (int)Native.window.Height,
                        ////    new
                        ////    {
                        ////        minFilter = THREE.LinearFilter,
                        ////        magFilter = THREE.LinearFilter,
                        ////        format = THREE.RGBFormat,
                        ////        stencilBufer = false
                        ////    }
                        ////);

                        ////var composer = new THREE.EffectComposer(renderer, renderTarget);
                        ////composer.addPass(new THREE.RenderPass(skyScene, skyCamera));
                        ////composer.addPass(new THREE.RenderPass(scene, camera));

                        ////#region vblur
                        ////var hblur = new THREE.ShaderPass(THREE.HorizontalTiltShiftShader);
                        ////var vblur = new THREE.ShaderPass(THREE.VerticalTiltShiftShader);

                        ////var bluriness = 6;

                        ////// Show Details	Severity	Code	Description	Project	File	Line
                        //////Error CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' WebGLTiltShift Application.cs  183

                        ////(hblur.uniforms as dynamic).h.value = bluriness / Native.window.Width;
                        ////(vblur.uniforms as dynamic).v.value = bluriness / Native.window.Height;

                        ////(hblur.uniforms as dynamic).r.value = 0.5;
                        ////(vblur.uniforms as dynamic).r.value = 0.5;
                        ////vblur.renderToScreen = true;

                        ////composer.addPass(hblur);
                        ////composer.addPass(vblur);
                        ////#endregion

                        //composer.addPass(new THREE.RenderPass(scene, camera));
                        // 

                        #region onframe
                        Native.window.onframe +=
                            delegate
                            {
                                var scale = 1.0;
                                var delta = clock.getDelta();
                                var stepSize = delta * scale;

                                if (stepSize > 0)
                                {
                                    //characterController.update(stepSize, scale);
                                    //gui.setSpeed(blendMesh.speed);

                                    THREE.AnimationHandler.update(stepSize);
                                    blendMesh.updateSkeletonHelper();
                                }

                                controls.center.copy(blendMesh.position);
                                controls.center.y += radius * 2.0;
                                controls.update();

                                //var camOffset = camera.position.clone().sub(controls.center);
                                //camOffset.normalize().multiplyScalar(750);
                                camera.position = controls.center.clone();
                                //camera.position = controls.center.clone().add(camOffset);

                                skyCamera.rotation.copy(camera.rotation);


                                //composer.render(0.1);

                                //renderer.clear();
                                renderer.render(skyScene, skyCamera);
                                renderer.render(scene, camera);
                            };
                        #endregion

                        new { }.With(
                           async delegate
                           {
                               //while (true)
                               do
                               {
                                   camera.aspect = Native.window.aspect;
                                   camera.updateProjectionMatrix();
                                   renderer.setSize(Native.window.Width, Native.window.Height);

                                   // convert to bool?
                               } while (await Native.window.async.onresize);
                               //} while (await Native.window.async.onresize != null);

                           }
                       );
                    }
                )
           );




        }
Example #2
0
        protected void MakeLights()
        {
            // lights
            THREE.Light light;


            scene.add(new THREE.AmbientLight(0x666666));

            light = new THREE.DirectionalLight(0xdfebff, 1.75);
            light.position.set(50, 200, 100);
            light.position.multiplyScalar(1.3);

            light.castShadow          = true;
            light.shadowCameraVisible = false;

            light.shadowMapWidth  = 1024;
            light.shadowMapHeight = 1024;

            double lightBox = 300;

            light.shadowCameraLeft   = -lightBox;
            light.shadowCameraRight  = lightBox;
            light.shadowCameraTop    = lightBox;
            light.shadowCameraBottom = -lightBox;

            light.shadowCameraFar = 1000;

            scene.add(light);
        }
        public override void Init()
        {
            DivElement div = new DivElement( )
            {
                InnerHTML = @"
                W = translate |
                E = rotate |
                + = increase size |
               - = decrise seize <br />
               Press Q to toggle world/local space"
            };

            Container.AppendChild(div);

            renderer = new THREE.WebGLRenderer();

            renderer.setSize(Width, Height);
            renderer.sortObjects = false;
            Container.AppendChild(renderer.domElement);

            //

            camera = new THREE.PerspectiveCamera(70, Width /Height, 1, 3000);
            camera.position.set(1000, 500, 1000);
            camera.lookAt(new THREE.Vector3(0, 200, 0));

            scene = new THREE.Scene();
            scene.add(new THREE.GridHelper(500, 100));

            var light = new THREE.DirectionalLight(0xffffff, 2);
            light.position.set(1, 1, 1);
            scene.add(light);

            THREE.Texture texture = THREE.ImageUtils.loadTexture("textures/crate.gif", THREE.MappingMode.UVMapping, base.Render); //render
            texture.mapping = THREE.MappingMode.UVMapping;

            texture.anisotropy = renderer.getMaxAnisotropy();

            var geometry = new THREE.BoxGeometry(200, 200, 200);
            THREE.Material material = new THREE.MeshLambertMaterial();
            material.map = texture;

            controls = new THREE.TransformControls(camera, renderer.domElement);
            controls.addEventListener("change", base.Render);

            var mesh = new THREE.Mesh(geometry, material);
            scene.add(mesh);

            controls.attach(mesh);
            scene.add(controls);

            CreateTrackball();
            Window.AddEventListener("keydown", this.SwitchCase, false);
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                10000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();


            Native.window.document.onmousemove +=
                e =>
                {
                    mouseX = e.CursorX - Native.window.Width / 2;
                    mouseY = e.CursorY - Native.window.Height / 2;
                };


            Native.window.onframe +=
                delegate
            {

                oo.WithEach(
                    x =>
                        x.rotation.y = (st.ElapsedMilliseconds + mouseX * 100) * 0.00001
                );


                camera.position.x += (mouseX - camera.position.x) * .05;
                camera.position.y += (-mouseY - camera.position.y) * .05;

                camera.lookAt(scene.position);

                renderer.render(scene, camera);


            };

            Native.window.onresize +=
                delegate
            {
                camera.aspect = window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(window.Width, window.Height);

            };
            #endregion

            // why isnt it being found?
            new global::WebGLColladaExperiment.THREE_ColladaAsset(

                // we get purple small thingy
                "assets/WebGLHeatZeekerColladaExperiment/Promotion3D_daytime.dae"

            // maybe sketchup doesnt know how to export colors?
            //"assets/WebGLHeatZeekerColladaExperiment/sam_site.dae"
            ).Source.Task.ContinueWithResult(
                dae =>
                {

                    dae.position.y = -40;
                    //dae.position.z = 280;
                    scene.add(dae);
                    oo.Add(dae);

                    dae.scale = new THREE.Vector3(2, 2, 2);

                }
            );
        }
Example #5
0
        public override void Init()
        {
            base.Init();

            controls = new THREE.TrackballControls(camera, Container);

            controls.rotateSpeed = 3.0;
            controls.zoomSpeed   = 1.2;
            controls.panSpeed    = 0.8;

            controls.noZoom = false;
            controls.noPan  = false;

            controls.staticMoving         = true;
            controls.dynamicDampingFactor = 0.3;

            controls.keys = new int[] { 65, 83, 68 };


            scene = new THREE.Scene();
            // THREE.FogExp2 fg2 = new THREE.FogExp2(new THREE.Color().setHex(0xcccccc), 0.002);

            THREE.FogExp2 fg2 = new THREE.FogExp2(0xcccccc, 0.002);
            scene.fog = fg2;


            var geometry = new THREE.CylinderGeometry(0, 10, 30, 4, 1);
            var material = new THREE.MeshPhongMaterial();

            material.color   = new THREE.Color().setHex(0xffffff); // 0xffffff;
            material.shading = THREE.ShadingType.FlatShading;


            for (var i = 0; i < 500; i++)
            {
                var mesh = new THREE.Mesh(geometry, material);
                mesh.position.x = (Math.Random() - 0.5) * 1000;
                mesh.position.y = (Math.Random() - 0.5) * 1000;
                mesh.position.z = (Math.Random() - 0.5) * 1000;
                mesh.updateMatrix();
                mesh.matrixAutoUpdate = false;
                scene.add(mesh);
            }


            // lights

            THREE.Light light = new THREE.DirectionalLight();
            light.color = new THREE.Color().setHex(0xffffff);
            light.position.set(1, 1, 1);
            scene.add(light);

            light       = new THREE.DirectionalLight();
            light.color = new THREE.Color().setHex(0x002288);
            light.position.set(-1, -1, -1);
            scene.add(light);

            light       = new THREE.AmbientLight(0x222222);
            light.color = new THREE.Color().setHex(0x222222);
            scene.add(light);


            // renderer

            renderer           = new THREE.WebGLRenderer(false);
            renderer.antialias = false;
            renderer.setClearColor(scene.fog.color);
            //TODO: renderer.setPixelRatio( Window.devicePixelRatio );
            renderer.setSize(Width, Height);

            Container.AppendChild(renderer.domElement);

            //stats = new Stats();
            //stats.domElement.style.position = 'absolute';
            //stats.domElement.style.top = '0px';
            //stats.domElement.style.zIndex = 100;
            //container.appendChild( stats.domElement );

            //


            //
        }
Example #6
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            onMouseDownPosition = new THREE.Vector2();

            //camera = new THREE.PerspectiveCamera(
            //   45,
            //   Native.window.aspect,
            //   1,
            //   1000
            //    //2000
            //   );
            //camera.position.z = 400;

            camera            = new THREE.PerspectiveCamera(40, Native.window.Width / Native.window.Height, 1, 10000);
            camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
            camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
            camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);


            scene = new THREE.Scene();
            var ambientLight = new THREE.AmbientLight(0x404040);

            scene.add(ambientLight);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);

            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var obj = new THREE.Object3D();


            var buttomCylinder1 = new THREE.Mesh(
                new THREE.CylinderGeometry(50, 50, 50, 32),
                new THREE.MeshPhongMaterial(
                    new
            {
                specular = new THREE.Color(0xa0a0a0),
                color    = new THREE.Color(0xa0a0a0),
            })
                );

            buttomCylinder1.rotation.x = -90 * Math.PI / 180;

            //buttomCylinder1.position.x = 0;
            //buttomCylinder1.position.y = 0;
            //buttomCylinder1.position.z = 0;

            obj.add(buttomCylinder1);
            scene.add(obj);


            var renderer = new THREE.WebGLRenderer(
                new
            {
                preserveDrawingBuffer = true
            }

                );

            renderer.setSize(Native.window.Width, Native.window.Height);
            this.canvas = (IHTMLCanvas)renderer.domElement;
            this.canvas.AttachToDocument();
            this.canvas.style.SetLocation(0, 0);

            camera.lookAt(scene.position);
            scene.add(obj);

            //var plane = new THREE.Mesh(new THREE.Plane(1000, 1000));
            //plane.rotation.x = -90 * Math.PI / 180;
            //scene.add(plane);

            #region onmousedown
            this.canvas.onmousedown +=
                e =>
            {
                e.preventDefault();

                isMouseDown = true;

                onMouseDownTheta      = theta;
                onMouseDownPhi        = phi;
                onMouseDownPosition.x = e.CursorX;
                onMouseDownPosition.y = e.CursorY;
            };
            #endregion


            this.canvas.onmousewheel +=
                e =>
            {
                radious -= e.WheelDirection;

                camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
                camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                camera.updateMatrix();
            };

            #region onmousemove
            this.canvas.onmousemove +=
                e =>
            {
                e.preventDefault();

                if (isMouseDown)
                {
                    theta = -((e.CursorX - onMouseDownPosition.x) * 0.5) + onMouseDownTheta;
                    phi   = ((e.CursorX - onMouseDownPosition.y) * 0.5) + onMouseDownPhi;

                    phi = Math.Min(360, Math.Max(0, phi));

                    camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                    camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
                    camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                    camera.updateMatrix();
                }
            };
            #endregion

            this.canvas.onmouseup += e =>
            {
                e.preventDefault();

                isMouseDown = false;

                onMouseDownPosition.x = e.CursorX - onMouseDownPosition.x;
                onMouseDownPosition.y = e.CursorY - onMouseDownPosition.y;
            };



            // could we
            Native.window.onframe +=
                e =>
            {
                renderer.clear();
                camera.updateProjectionMatrix();
                camera.lookAt(scene.position);
                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                //if (canvas.parentNode == Native.document.body)

                // are we embedded?
                if (page != null)
                {
                    renderer.setSize();
                }
            };
        }
        // the eye nor the display will be able to do any stereo
        // until tech is near matrix capability. 2019?

        // cubemap can be used for all long range scenes
        // http://www.imdb.com/title/tt0112111/?ref_=nv_sr_1


        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150808/cubemapcamera
        // subst a: s:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeCubeCameraExperiment\ChromeCubeCameraExperiment\bin\Debug\staging\ChromeCubeCameraExperiment.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeCubeCameraExperiment\ChromeCubeCameraExperiment\bin\Debug\staging\ChromeCubeCameraExperiment.Application\web

        // ColladaLoader: Empty or non-existing file (assets/ChromeCubeCameraExperiment/S6Edge.dae)

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //FormStyler.AtFormCreated =
            //s =>
            //{
            //    s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

            //    //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            //    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



            //    s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
            //    //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            //};

#if AsWEBSERVER
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                // if we run as a server. we can open up on android.

                //chrome.Notification.DefaultTitle = "Nexus7";
                //chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text
                //, AtFormCreated: FormStyler.AtFormCreated

                //AtFormConstructor:
                //    f =>
                //    {
                //        //arg[0] is typeof System.Int32
                //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                //    }
                );
                return;
            }
            #endregion
#else

            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    //chrome.runtime.UpdateAvailable += delegate
                    //{
                    //    new chrome.Notification(title: "UpdateAvailable");

                    //};

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "ChromeCubeCameraExperiment");

                        // https://developer.chrome.com/apps/app_window#type-CreateWindowOptions
                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: new
                               {
                                   alwaysOnTop = true,
                                   visibleOnAllWorkspaces = true
                               }
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion


#endif


            Native.css.style.backgroundColor = "blue";
            Native.css.style.overflow = IStyle.OverflowEnum.hidden;

            Native.body.Clear();

            new IHTMLPre { "can we stream it into VR, shadertoy, youtube 360, youtube stereo yet?" }.AttachToDocument();


            var pause = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.checkbox, title = "pause" }.AttachToDocument();

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;


            // what about physics and that portal rendering?

            // if we are running as a chrome web server, we may also be opened as android ndk webview app
            //var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: window.aspect, near: 1, far: 2000);
            // once we update source
            // save the source
            // manually recompile 
            //cameraPX.position.z = 400;

            //// the camera should be close enough for the object to float off the FOV of PX
            //cameraPX.position.z = 200;

            // scene
            // can we make the 3D object orbit around us ?
            // and
            // stream it to vr?
            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x303030);
            scene.add(ambient);

            // should we fix jsc to do a more correct IDL?
            var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);



            // whats WebGLRenderTargetCube do?

            // WebGLRenderer preserveDrawingBuffer 

            //const int size = 128;
            //const int size = 256; // 6 faces, 12KB
            const int size = 512; // 6 faces, ?
            //const int size = 1024; // 6 faces, ?

            var renderer0 = new THREE.WebGLRenderer(

                new
                {
                    antialias = true,
                    alpha = true,
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836

            // the construct. white bg
            renderer0.setClearColor(0xfffff, 1);

            //renderer.setSize(window.Width, window.Height);
            renderer0.setSize(size, size);

            //renderer0.domElement.AttachToDocument();
            //rendererPX.domElement.style.SetLocation(0, 0);
            //renderer0.domElement.style.SetLocation(4, 4);


            // top

            // http://stackoverflow.com/questions/27612524/can-multiple-webglrenderers-render-the-same-scene


            // need a place to show the cubemap face to GUI 
            // how does the stereo OTOY do it?
            // https://www.opengl.org/wiki/Sampler_(GLSL)

            // http://www.richardssoftware.net/Home/Post/25

            // [+X, –X, +Y, –Y, +Z, –Z] fa

            var uizoom = 0.25;


            #region x
            var cameraNX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            var canvasNX = new CanvasRenderingContext2D(size, size);
            canvasNX.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 2, 8 + (int)(uizoom * size + 8) * 1);
            canvasNX.canvas.title = "NX";
            canvasNX.canvas.AttachToDocument();
            canvasNX.canvas.style.transformOrigin = "0 0";
            canvasNX.canvas.style.transform = $"scale({uizoom})";

            var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraPX.lookAt(new THREE.Vector3(1, 0, 0));
            var canvasPX = new CanvasRenderingContext2D(size, size);
            canvasPX.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 0, 8 + (int)(uizoom * size + 8) * 1);
            canvasPX.canvas.title = "PX";
            canvasPX.canvas.AttachToDocument();
            canvasPX.canvas.style.transformOrigin = "0 0";
            canvasPX.canvas.style.transform = $"scale({uizoom})";
            #endregion


            #region y
            // need to rotate90?
            var cameraNY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraNY.lookAt(new THREE.Vector3(0, -1, 0));
            var canvasNY = new CanvasRenderingContext2D(size, size);
            canvasNY.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 2);
            canvasNY.canvas.title = "NY";
            canvasNY.canvas.AttachToDocument();
            canvasNY.canvas.style.transformOrigin = "0 0";
            canvasNY.canvas.style.transform = $"scale({uizoom})";

            var cameraPY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraPY.lookAt(new THREE.Vector3(0, 1, 0));
            var canvasPY = new CanvasRenderingContext2D(size, size);
            canvasPY.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 0);
            canvasPY.canvas.title = "PY";
            canvasPY.canvas.AttachToDocument();
            canvasPY.canvas.style.transformOrigin = "0 0";
            canvasPY.canvas.style.transform = $"scale({uizoom})";
            #endregion

            #region z
            var cameraNZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraNZ.lookAt(new THREE.Vector3(0, 0, -1));
            var canvasNZ = new CanvasRenderingContext2D(size, size);
            canvasNZ.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 3, 8 + (int)(uizoom * size + 8) * 1);
            canvasNZ.canvas.title = "NZ";
            canvasNZ.canvas.AttachToDocument();
            canvasNZ.canvas.style.transformOrigin = "0 0";
            canvasNZ.canvas.style.transform = $"scale({uizoom})";

            var cameraPZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: 2000);
            cameraPZ.lookAt(new THREE.Vector3(0, 0, 1));
            var canvasPZ = new CanvasRenderingContext2D(size, size);
            canvasPZ.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 1);
            canvasPZ.canvas.title = "PZ";
            canvasPZ.canvas.AttachToDocument();
            canvasPZ.canvas.style.transformOrigin = "0 0";
            canvasPZ.canvas.style.transform = $"scale({uizoom})";
            #endregion




            // c++ alias locals would be nice..
            var canvas0 = (IHTMLCanvas)renderer0.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var st = new Stopwatch();
            st.Start();

            //canvas0.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            Native.body.onmousedown +=
                async e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                        return;

                    // movementX no longer works
                    old = new
                    {


                        e.CursorX,
                        e.CursorY
                    };


                    //e.CaptureMouse();
                    var release = e.Element.CaptureMouse();
                    await e.Element.async.onmouseup;

                    release();


                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            Native.body.onmousemove +=
                e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                    {
                        Native.body.style.cursor = IStyle.CursorEnum.@default;
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();


                    Native.body.style.cursor = IStyle.CursorEnum.move;

                    var pointerLock = canvas0 == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion

            // THREE.WebGLProgram: gl.getProgramInfoLog() C:\fakepath(78,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll
            // THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

            // http://www.roadtovr.com/youtube-confirms-stereo-3d-360-video-support-coming-soon/
            // https://www.youtube.com/watch?v=D-Wl9jAB45Q

            new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = -(65 - 200);





                       var scale = 0.9;

                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;


                       #region onmousewheel
                       Native.body.onmousewheel +=
                           e =>
                           {
                               e.preventDefault();

                               //camera.position.z = 1.5;

                               // min max. shall adjust speed also!
                               // max 4.0
                               // min 0.6
                               dae.position.z -= 10.0 * e.WheelDirection;

                               //camera.position.z = 400;
                               //dae.position.z = dae.position.z.Max(-200).Min(200);

                               //Native.document.title = new { z }.ToString();

                           };
                       #endregion


                       //dae.position.y = -80;

                       scene.add(dae);
                       oo.Add(dae);


                       var sw = Stopwatch.StartNew();


                       // view-source:http://threejs.org/examples/webgl_multiple_canvases_circle.html
                       // https://threejsdoc.appspot.com/doc/three.js/src.source/extras/cameras/CubeCamera.js.html
                       Native.window.onframe +=
                           e =>
                           {
                               //if (pause) return;
                               if (pause.@checked)
                                   return;


                               // can we float out of frame?
                               // haha. a bit too flickery.
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.01) * 50.0;
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.001) * 190.0;
                               dae.position.x = Math.Sin(sw.ElapsedMilliseconds * 0.0001) * 190.0;
                               dae.position.y = Math.Cos(sw.ElapsedMilliseconds * 0.0001) * 90.0;
                               // manual rebuild?
                               // red compiler notifies laptop chrome of pending update
                               // app reloads


                               renderer0.clear();
                               //rendererPY.clear();

                               //cameraPX.aspect = canvasPX.aspect;
                               //cameraPX.updateProjectionMatrix();

                               // um what does this do?
                               //cameraPX.position.z += (z - cameraPX.position.z) * e.delay.ElapsedMilliseconds / 200.0;
                               // mousewheel allos the camera to move closer
                               // once we see the frame in vr, can we udp sync vr tracking back to laptop?


                               //this.targetPX.x += 1;
                               //this.targetNX.x -= 1;

                               //this.targetPY.y += 1;
                               //this.targetNY.y -= 1;

                               //this.targetPZ.z += 1;
                               //this.targetNZ.z -= 1;

                               // how does the 360 or shadertoy want our cubemaps?


                               // and then rotate right?

                               // how can we render cubemap?


                               #region x
                               // upside down?
                               renderer0.render(scene, cameraPX);
                               canvasPX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);

                               renderer0.render(scene, cameraNX);
                               canvasNX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               #endregion

                               #region z
                               renderer0.render(scene, cameraPZ);
                               canvasPZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);

                               renderer0.render(scene, cameraNZ);
                               canvasNZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               #endregion



                               #region y
                               renderer0.render(scene, cameraPY);

                               canvasPY.save();
                               canvasPY.translate(0, size);
                               canvasPY.rotate((float)(-Math.PI / 2));
                               canvasPY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               canvasPY.restore();

                               // ?

                               renderer0.render(scene, cameraNY);
                               canvasNY.save();
                               canvasNY.translate(size, 0);
                               canvasNY.rotate((float)(Math.PI / 2));
                               canvasNY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               canvasNY.restore();
                               // ?
                               #endregion


                               //renderer0.render(scene, cameraPX);


                               //rendererPY.render(scene, cameraPY);


                           };


                   }
               );


            #endregion



            Console.WriteLine("do you see it?");
        }
Example #8
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // if we are running in a SYSTEM account
            // the chrome no-sandbox only allows software renderer
            // where we get 1 frame per sec.


            // on older systems we may not get GL_OES_standard_derivatives
            // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app
            //          ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
            // or that system is just old as hell


            // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app

            //http://thematicmapping.org/playground/webgl/earth/
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222


            // Earth params
            var radius = 0.5;

            //var segments = 32;
            var segments = 128;
            var rotation = 6;

            var scene = new THREE.Scene();

            locations = new ArrayList();

            var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000);

            camera.position.z = 1.5;

            var renderer = new THREE.WebGLRenderer(
                new
            {
                preserveDrawingBuffer = true
            }
                );

            renderer.setSize();

            scene.add(new THREE.AmbientLight(0x333333));

            var light = new THREE.DirectionalLight(0xffffff, 1);

            light.position.set(5, 3, 5);
            scene.add(light);

            parent = new THREE.Object3D();
            scene.add(parent);


            #region sphere
            var sphere = new THREE.Mesh(
                new THREE.SphereGeometry(radius, segments, segments),
                new THREE.MeshPhongMaterial(
                    new
            {
                map = new THREE.Texture().With(
                    async s =>
                {
                    //0:75ms event: _2_no_clouds_4k_low view-source:36543
                    //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1
                    //Application Cache Progress event (2 of 2)  192.168.1.72/:1
                    //Application Cache Cached event 192.168.1.72/:1
                    //1:1018ms event: _2_no_clouds_4k_low done view-source:36543
                    //1:1019ms event: _2_no_clouds_4k view-source:36543
                    //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995
                    //1:16445ms event: _2_no_clouds_4k done

                    // ~ tilde to open css editor?

                    Console.WriteLine("event: _2_no_clouds_4k_low");
                    s.image       = await new _2_no_clouds_4k_low();
                    s.needsUpdate = true;
                    Console.WriteLine("event: _2_no_clouds_4k_low done");

                    await 20000;

                    Console.WriteLine("event: _2_no_clouds_4k");
                    s.image       = await new _2_no_clouds_4k();
                    s.needsUpdate = true;
                    Console.WriteLine("event: _2_no_clouds_4k done");
                }
                    ),

                bumpMap = THREE.ImageUtils.loadTexture(
                    new elev_bump_4k().src
                    //new elev_bump_4k_low().src
                    ),


                // applies onyl to shaders to create the shadow
                bumpScale   = 0.001,
                specularMap = new THREE.Texture().With(
                    async s =>
                {
                    Console.WriteLine("event: water_4k_low");
                    s.image       = await new water_4k_low();
                    s.needsUpdate = true;
                    Console.WriteLine("event: water_4k_low done");

                    await 20000;

                    Console.WriteLine("event: water_4k");
                    s.image       = await new water_4k();
                    s.needsUpdate = true;
                    Console.WriteLine("event: water_4k done");
                }
                    ),


                //specular =    new THREE.Color("grey")
                specular = new THREE.Color(0xa0a0a0)
            })
                );
            #endregion

            // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane


            //sphere.rotation.y = rotation;
            parent.rotation.y = rotation;
            //sphere.position.x = 10;
            //sphere.position.y = 10;
            //sphere.position.z = 10;
            //sphere.position.normalize();
            //sphere.position.multiplyScalar(200);

            parent.add(sphere);
            //scene.add(sphere);


            #region clouds
            var clouds = new THREE.Mesh(
                new THREE.SphereGeometry(
                    //radius + 0.003,
                    radius + 0.006,
                    segments, segments),
                new THREE.MeshPhongMaterial(
                    new
            {
                //map = THREE.ImageUtils.loadTexture(
                //    //new fair_clouds_4k().src
                //    new fair_clouds_4k_low().src
                //    ),


                map = new THREE.Texture().With(
                    async s =>
                {
                    Console.WriteLine("event: fair_clouds_4k_low");
                    s.image       = await new fair_clouds_4k_low();
                    s.needsUpdate = true;
                    Console.WriteLine("event: fair_clouds_4k_low done");

                    await 20000;

                    Console.WriteLine("event: fair_clouds_4k");
                    s.image       = await new fair_clouds_4k();
                    s.needsUpdate = true;
                    Console.WriteLine("event: fair_clouds_4k done");
                }
                    ),

                transparent = true
            })
                );
            //clouds.rotation.y = rotation;
            parent.add(clouds);
            //scene.add(clouds);
            #endregion


            var citiesData = new XElement("cities");



            {
                var cityH = new XElement("city");
                cityH.Add(new XElement("name", "Tallinn"));
                cityH.Add(new XElement("longitude", "24.7281"));
                cityH.Add(new XElement("latitude", "59.4339"));
                citiesData.Add(cityH);
            }
            {
                var cityH = new XElement("city");
                cityH.Add(new XElement("name", "London"));
                cityH.Add(new XElement("longitude", "-0.116667"));
                cityH.Add(new XElement("latitude", "51.5"));
                citiesData.Add(cityH);
            }


            var shadowL = new ShadowLayout().AttachTo(Native.shadow);
            page.dataHolder = citiesData;

            #region Location on sphere

            Action AddCities = async delegate
            {
                //var table = await this.GetAllCities();
                //Console.WriteLine(table.Rows.Count.ToString());



                //for (var r = 0; r < table.Rows.Count; r++)
                //{
                //    var latitude = (double)table.Rows[r]["Latitude"];
                //    var longtitude = (double)table.Rows[r]["Longtitude"];
                //    addLocation(latitude, longtitude, radius, 0.001, parent, 6);
                //    Console.WriteLine(latitude.ToString());
                //    await 100;
                //}
                var elemList = citiesData.Elements();
                Console.WriteLine(elemList.Count().ToString());

                foreach (var i in elemList)
                {
                    //Console.WriteLine(i.ToString());

                    //foreach (var t in i.Elements())
                    //{
                    //    Console.WriteLine(t.ToString());
                    //}

                    //var l = i.Element("name");
                    //if (l == null)
                    //{
                    //    Console.WriteLine("F**k");
                    //}
                    //else
                    //{
                    //    Console.WriteLine(l.Value);
                    //}
                    //Console.WriteLine(i.Element("longitude"));
                    //Console.WriteLine(i.Element("latitude"));

                    var lat = i.Element("latitude");
                    if (lat != null)
                    {
                        Console.WriteLine("Latitude not null");
                        var latitude = Convert.ToDouble(lat.Value);
                        Console.WriteLine(latitude.ToString());

                        var longit = i.Element("longitude");
                        if (longit != null)
                        {
                            Console.WriteLine("Longitude not null");

                            var longtitude = Convert.ToDouble(longit.Value);
                            addLocation(latitude, longtitude, radius, 0.001, parent, 6);
                            Console.WriteLine(longtitude.ToString());
                        }
                    }
                }
            };

            citiesData.Changed += (send, arg) =>
            {
                //if(arg.ObjectChange == XObjectChange.Value)
                //{
                //Console.WriteLine(citiesData);

                //Console.WriteLine("Sender name "+((XAttribute)send).Name);
                //Console.WriteLine("Sender val " + ((XAttribute)send).Value);
                removeLocations();
                AddCities();
                //}
            };


            AddCities();


            #endregion

            var stars = new THREE.Mesh(
                new THREE.SphereGeometry(90, 64, 64),
                new THREE.MeshBasicMaterial(
                    new
            {
                map  = THREE.ImageUtils.loadTexture(new galaxy_starfield().src),
                side = THREE.BackSide
            })
                );
            scene.add(stars);

            this.canvas = (IHTMLCanvas)renderer.domElement;

            //renderer.domElement.AttachToDocument();
            this.canvas.AttachTo(shadowL.webGlCanvas);
            this.canvas.style.SetLocation(0, 0);

            // jsc, what pointers do we have in store?
            this.canvas.css.style.cursor        = IStyle.CursorEnum.pointer;
            this.canvas.css.active.style.cursor = IStyle.CursorEnum.move;


            var
                old = new
            {
                parent = new
                {
                    parent.rotation.x,
                    parent.rotation.y
                },
                //sphere = new
                //{
                //    //sphere.rotation.x,
                //    //sphere.rotation.y

                //},
                //clouds = new
                //{
                //    //clouds.rotation.x,
                //    //clouds.rotation.y,
                //},


                CursorX = 0,
                CursorY = 0
            };

            #region onmousedown
            this.canvas.onmousedown +=
                e =>
            {
                var pointerLock = this.canvas == Native.document.pointerLockElement;

                if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                {
                    this.canvas.requestFullscreen();
                    this.canvas.requestPointerLock();
                }
                else
                {
                    // movementX no longer works
                    old = new
                    {
                        parent = new
                        {
                            parent.rotation.x,
                            parent.rotation.y
                        },
                        //sphere = new
                        //{
                        //    sphere.rotation.x,
                        //    sphere.rotation.y

                        //},
                        //clouds = new
                        //{
                        //    clouds.rotation.x,
                        //    clouds.rotation.y,
                        //},


                        e.CursorX,
                        e.CursorY
                    };

                    if (pointerLock)
                    {
                        // skip
                    }
                    else
                    {
                        e.CaptureMouse();
                    }
                }
            };
            #endregion



            var z = camera.position.z;

            var sfx = new TestWebGLEarthShadowDomXML.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1
            {
                autobuffer = true,

                // this aint working
                //loop = true
            };

            sfx.play();

            //sfx.AttachToHead();


            // http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/

            this.canvas.onmousewheel +=
                e =>
            {
                //camera.position.z = 1.5;

                // min max. shall adjust speed also!
                // max 4.0
                // min 0.6
                z -= 0.1 * e.WheelDirection;

                z = z.Max(0.6).Min(4.5);

                //Native.document.title = new { camera.position.z }.ToString();
            };

            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            this.canvas.onmousemove +=
                e =>
            {
                var pointerLock = this.canvas == Native.document.pointerLockElement;


                //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                {
                    if (pointerLock)
                    {
                        parent.rotation.x += 0.01 * e.movementY;
                        parent.rotation.y += 0.01 * e.movementX;

                        //sphere.rotation.x += 0.01 * e.movementY;
                        //sphere.rotation.y += 0.01 * e.movementX;

                        //clouds.rotation.x += 0.01 * e.movementY;
                        //clouds.rotation.y += 0.01 * e.movementX;
                    }
                    else
                    {
                        parent.rotation.x = old.parent.x + 0.01 * (e.CursorY - old.CursorY);
                        parent.rotation.y = old.parent.y + 0.01 * (e.CursorX - old.CursorX);

                        //sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY);
                        //sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX);

                        //clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY);
                        //clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX);
                    }


                    //    Native.document.title = new { e.movementX, e.movementY }.ToString();
                }
            };
            #endregion


            // could we
            Native.window.onframe +=
                e =>
            {
                if (this.canvas.parentNode == null)
                {
                    return;
                }

                camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                camera.updateProjectionMatrix();

                camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                // the larger the vew the slower the rotation shall be
                var speed = 0.0001 * e.delay.ElapsedMilliseconds +
                            0.007
                            * 96.0 / canvas.clientHeight
                            * 1.0 / camera.position.z;

                //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString();
                //Native.document.title = new { speed }.ToString();


                //controls.update();
                //sphere.rotation.y += speed;
                //clouds.rotation.y += speed;

                parent.rotation.y += speed;


                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                //if (canvas.parentNode == Native.document.body)

                // are we embedded?
                if (page != null)
                {
                    renderer.setSize();
                }
            };


            //new IStyle(this.canvas.css.before)
            //{
            //    content = "'do a middle click to maximize the earth dashboard'",

            //    left = "1em",
            //    bottom = "1em",

            //    color = "white",

            //    position = IStyle.PositionEnum.absolute
            //};
        }
Example #9
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List <THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                1000
                //2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer
            var renderer = new THREE.WebGLRenderer(

                new
            {
                preserveDrawingBuffer = true
            }
                );

            // https://github.com/mrdoob/three.js/issues/3836
            renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            this.canvas = (IHTMLCanvas)renderer.domElement;


            var mouseX = 0;
            var mouseY = 0;
            var st     = new Stopwatch();
            st.Start();

            Native.window.onframe +=
                delegate
            {
                renderer.clear();


                //camera.aspect = window.aspect;
                //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                //camera.aspect = canvas.aspect;
                camera.updateProjectionMatrix();


                oo.WithEach(
                    x =>
                    x.rotation.y = st.ElapsedMilliseconds * 0.0001
                    );


                camera.position.x += (mouseX - camera.position.x) * .05;
                camera.position.y += (-mouseY - camera.position.y) * .05;

                camera.lookAt(scene.position);

                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                if (canvas.parentNode == Native.document.body)
                {
                    renderer.setSize(window.Width, window.Height);
                }
            };
            #endregion

            new Cisco().Source.Task.ContinueWithResult(
                dae =>
            {
                //dae.scale.x = 30;
                //dae.scale.y = 30;
                //dae.scale.z = 30;

                //dae.castShadow = true;
                //dae.receiveShadow = true;

                dae.scale.x = 5;
                dae.scale.y = 5;
                dae.scale.z = 5;

                dae.position.y = -80;

                scene.add(dae);
                oo.Add(dae);
            }
                );
        }
Example #10
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://chrome.google.com/webstore/detail/dglmddjmdpdbijfkoaiadbpmjampfdjh/publish-delayed


            #region ChromeTCPServer
            dynamic self               = Native.self;
            dynamic self_chrome        = self.chrome;
            object  self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                #region AtFormCreated
                FormStyler.AtFormCreated =
                    ss =>
                {
                    ss.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

                    // this is working?
                    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(ss.Context.GetHTMLTarget());
                };
                #endregion

                chrome.Notification.DefaultTitle   = "Heat Zeeker";
                chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Promotion3D_iso1_tiltshift_128().src;

                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                    AppSource.Text,
                    AtFormCreated: FormStyler.AtFormCreated
                    );

                return;
            }
            #endregion


            Native.body.style.margin   = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            // jsc, add THREE
            // ... ok.

            // X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs



            // this is not isometric.
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151112
            var camera = new THREE.OrthographicCamera(
                Native.window.Width / -2, Native.window.Width / 2,
                Native.window.Height / 2, Native.window.Height / -2
                ,
                // if we change these values what will change?
                -1000, 1000
                );
            camera.position.x = 200;
            camera.position.y = 100;
            camera.position.z = 200;

            var scene = new THREE.Scene();

            // Grid

            var size = 600;
            var step = 50;


            Func <double> random = new Random().NextDouble;


            // how do I add a new ground box?
            {
                var geometry = new THREE.BoxGeometry(size * 2, 2, size * 2);
                var material = new THREE.MeshLambertMaterial(new
                {
                    color = 0xB27D51
                            //                                                     , shading = THREE.FlatShading, overdraw = 0.5
                });

                {
                    var cube = new THREE.Mesh(geometry, material);


                    // why cant we get the shadows??
                    cube.receiveShadow = true;


                    cube.scale.y = Math.Floor(random() * 2 + 1);

                    cube.position.x = 0;
                    //cube.position.y = (cube.scale.y * 50) / 2;
                    cube.position.y = -2;
                    cube.position.z = 0;

                    scene.add(cube);
                }
            }


            {
                var geometry = new THREE.Geometry();

                for (var i = -size; i <= size; i += step)
                {
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(-size, 0, i));
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(size, 0, i));

                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(i, 0, -size));
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(i, 0, size));
                }

                var material = new THREE.LineBasicMaterial(new { color = 0, opacity = 0.2 });

                var line = new THREE.Line(geometry, material, mode: THREE.LinePieces);
                scene.add(line);
            }



            var interactiveObjects = new List <THREE.Object3D>();

            #region Cubes
            {
                for (var i = 0; i < 8; i++)
                {
                    new HZBunker().Source.Task.ContinueWithResult(
                        cube =>
                    {
                        // https://github.com/mrdoob/three.js/issues/1285
                        //cube.children.WithEach(c => c.castShadow = true);

                        //cube.traverse(
                        //    new Action<THREE.Object3D>(
                        //        child =>
                        //                {
                        //                    // does it work? do we need it?
                        //                    //if (child is THREE.Mesh)
                        //                    child.castShadow = true;
                        //                    child.receiveShadow = true;

                        //                }
                        //    )
                        //);

                        // um can edit and continue insert code going back in time?
                        cube.scale.x = 2.0;
                        cube.scale.y = 2.0;
                        cube.scale.z = 2.0;

                        //cube.castShadow = true;
                        //dae.receiveShadow = true;

                        cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
                        //cube.position.y = (cube.scale.y * 50) / 2;
                        cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

                        scene.add(cube);
                        interactiveObjects.Add(cube);
                    }
                        );


                    new HZWaterTower().Source.Task.ContinueWithResult(
                        cube =>
                    {
                        // https://github.com/mrdoob/three.js/issues/1285
                        // https://github.com/mrdoob/three.js/issues/1285
                        //cube.children.WithEach(c => c.castShadow = true);
                        // http://stackoverflow.com/questions/15906248/three-js-objloader-obj-model-not-casting-shadows


                        // http://stackoverflow.com/questions/22895120/imported-3d-objects-are-not-casting-shadows-with-three-js
                        //cube.traverse(
                        //    new Action<THREE.Object3D>(
                        //        child =>
                        //        {
                        //            // does it work? do we need it?
                        //            //if (child is THREE.Mesh)
                        //            child.castShadow = true;
                        //            child.receiveShadow = true;

                        //        }
                        //    )
                        //);

                        // um can edit and continue insert code going back in time?
                        cube.scale.x = 2.0;
                        cube.scale.y = 2.0;
                        cube.scale.z = 2.0;

                        //cube.castShadow = true;
                        //dae.receiveShadow = true;

                        cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
                        //cube.position.y = (cube.scale.y * 50) / 2;
                        cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

                        scene.add(cube);
                        interactiveObjects.Add(cube);
                    }
                        );

                    new HZCannon().Source.Task.ContinueWithResult(
                        cube =>
                    {
                        // https://github.com/mrdoob/three.js/issues/1285
                        //cube.children.WithEach(c => c.castShadow = true);

                        //cube.traverse(
                        //    new Action<THREE.Object3D>(
                        //        child =>
                        //                {
                        //                    // does it work? do we need it?
                        //                    //if (child is THREE.Mesh)
                        //                    child.castShadow = true;
                        //                    child.receiveShadow = true;

                        //                }
                        //    )
                        //);

                        // um can edit and continue insert code going back in time?
                        cube.scale.x = 2.0;
                        cube.scale.y = 2.0;
                        cube.scale.z = 2.0;



                        //cube.castShadow = true;
                        //dae.receiveShadow = true;

                        cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
                        //cube.position.y = (cube.scale.y * 50) / 2;
                        cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                        // if i want to rotate, how do I do it?
                        //cube.rotation.z = random() + Math.PI;
                        //cube.rotation.x = random() + Math.PI;
                        cube.rotation.y = random() * Math.PI * 2;


                        scene.add(cube);
                        interactiveObjects.Add(cube);
                    }
                        );
                }
            }
            #endregion

            // we need expression evaluator with intellisense for live debugging sessions
            #region  Lights

            var ambientLight = new THREE.AmbientLight((int)(random() * 0x10));
            scene.add(ambientLight);



            // can we get our shadows?
            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff), 0.5);

                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = 400;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }

            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff), 0.5);
                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = 400;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }
            #endregion


            //var renderer = new THREE.CanvasRenderer();
            var renderer = new THREE.WebGLRenderer();
            renderer.shadowMapEnabled = true;

            // background-color: #B27D51;
            renderer.setClearColor(0xB27D51);
            //renderer.setSize(
            //    Native.window.Width ,
            //    Native.window.Height * 10
            //    );
            renderer.setSize();

            renderer.domElement.AttachToDocument();

            Native.window.onresize +=
                delegate
            {
                camera.left   = Native.window.Width / -2;
                camera.right  = Native.window.Width / 2;
                camera.top    = Native.window.Height / 2;
                camera.bottom = Native.window.Height / -2;

                camera.updateProjectionMatrix();

                renderer.setSize();
            };

            //window.addEventListener( 'resize', onWindowResize, false );


            //#region Comanche
            //new Comanche().Source.Task.ContinueWithResult(
            //    Comanche =>
            //    {

            //        Comanche.position.y = 200;

            //        //dae.position.z = 280;

            //        Comanche.AttachTo(scene);

            //        //scene.add(dae);
            //        //oo.Add(Comanche);

            //        // wont do it
            //        //dae.castShadow = true;

            //        // http://stackoverflow.com/questions/15492857/any-way-to-get-a-bounding-box-from-a-three-js-object3d
            //        //var helper = new THREE.BoundingBoxHelper(dae, 0xff0000);
            //        //helper.update();
            //        //// If you want a visible bounding box
            //        //scene.add(helper);

            //        Comanche.children[0].children[0].children.WithEach(x => x.castShadow = true);


            //        // the rotors?
            //        Comanche.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


            //        Comanche.scale.set(0.5, 0.5, 0.5);
            //        //helper.scale.set(0.5, 0.5, 0.5);

            //        var sw = Stopwatch.StartNew();

            //        Native.window.onframe += delegate
            //        {
            //            //dae.children[0].children[0].children.Last().al
            //            //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
            //            //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
            //            //rotation.y = sw.ElapsedMilliseconds * 0.01;

            //            Comanche.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.001;

            //            //dae.children[0].children[0].children.Last().app
            //        };
            //    }
            //);
            //#endregion


            //#region ee
            //// X:\jsc.svn\examples\javascript\forms\NumericTextBox\NumericTextBox\ApplicationControl.cs
            //// can we restile the window as the pin window in IDE?
            //var ee = new Form { Left = 0, StartPosition = FormStartPosition.Manual };
            //var ee_camera_y = new TextBox { Dock = DockStyle.Fill, Text = camera.position.y + "" }.AttachTo(ee);
            ////ee.AutoSize = AutoSizeMode.

            ////ee.ClientSize = new System.Drawing.Size(ee_camera_y.Width, ee_camera_y.Height);
            //ee.ClientSize = new System.Drawing.Size(200, 24);

            //ee.Show();

            ////ee_camera_y.
            //ee_camera_y.TextChanged += delegate
            //{
            //    camera.position.y = double.Parse(ee_camera_y.Text);
            //};
            //#endregion

            var s        = Stopwatch.StartNew();
            var controls = new THREE.OrbitControls(camera, renderer.domElement);

            // http://stackoverflow.com/questions/26497903/nested-webglrendertargets-in-three-js
            //   var effect = new THREE.OculusRiftEffect(
            //renderer, new
            //{
            //    worldScale = 100,

            //           //HMD
            //       }
            //);

            //   effect.setSize(1920, 1080);

            Native.window.onframe +=
                e =>
            {
                // jsc, when can we have the edit and continue already?
                //var timer = s.ElapsedMilliseconds * 0.1;
                //var timer = s.ElapsedMilliseconds * 0.0001;

                //camera.position.x = Math.Cos(timer) * 200;
                //camera.position.z = Math.Sin(timer) * 200;


                // camera.position.z = 200;
                //camera.position.y = 100;
                //camera.position.y = Math.Sin(timer * 0.1) * 200;

                controls.update();
                camera.position = controls.center.clone();

                renderer.render(scene, camera);
                //effect.render(scene, camera);
            };

            //var ze = new ZeProperties();

            //ze.Show();
            //ze.treeView1.Nodes.Clear();

            //ze.Add(() => renderer);
            ////ze.Add(() => controls);
            //ze.Add(() => scene);
            //ze.Left = 0;

            // view-source:http://mrdoob.github.io/three.js/examples/webgl_interactive_voxelpainter.html
            //var mouse2D = new THREE.Vector3(0, 10000, 0.5);

            //renderer.domElement.onclick +=
            //    e =>
            //    {
            //        e.preventDefault();

            //        mouse2D.x = (e.CursorX / (double)Native.window.Width) * 2 - 1;
            //        mouse2D.y = -(e.CursorY / (double)Native.window.Height) * 2 + 1;

            //        var vector = new THREE.Vector3(
            //              (e.CursorX / (double)Native.window.Width) * 2 - 1,
            //              -(e.CursorY / (double)Native.window.Height) * 2 + 1,
            //             0.5);


            //        // X:\jsc.svn\examples\javascript\WebGL\WebGLInteractiveCubes\WebGLInteractiveCubes\Application.cs
            //        var projector = new THREE.Projector();
            //        projector.unprojectVector(vector, camera);

            //        // http://stackoverflow.com/questions/18553209/orthographic-camera-and-selecting-objects-with-raycast
            //        // http://stackoverflow.com/questions/20361776/orthographic-camera-and-pickingray
            //        // view-source:http://stemkoski.github.io/Three.js/Mouse-Click.html
            //        // http://stackoverflow.com/questions/11921033/projector-and-ray-with-orthographiccamera

            //        // use picking ray since it's an orthographic camera
            //        // doesnt fkin work ???
            //        //var raycaster = projector.pickingRay(vector, camera);

            //        var raycaster = projector.pickingRay(mouse2D.clone(), camera);

            //        //var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
            //        var intersects = raycaster.intersectObjects(interactiveObjects.ToArray());

            //        // https://github.com/mrdoob/three.js/issues/599
            //        Native.document.title = new { intersects.Length }.ToString();
            //    };
        }
Example #11
0
        public Application(IDefault page = null)
        {
            // https://github.com/mrdoob/three.js/wiki/Migration

            var size = 600;

            var windowHalfX = size / 2;
            var windowHalfY = size / 2;

            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            container.style.backgroundColor = JSColor.Black;

            var camera = new THREE.PerspectiveCamera(40, Native.window.aspect, 1, 3000);

            camera.position.z = 1000;

            var scene = new THREE.Scene();

            var light = new THREE.DirectionalLight(0xffffff);

            light.position.x = 1;
            light.position.y = 0;
            light.position.z = 1;
            //scene.addLight(light);
            scene.add(light);

            var renderer = new THREE.WebGLRenderer();

            var geometry = new THREE.TorusGeometry(50, 20, 15, 15);

            var uniforms = new MyUniforms();

            // ShaderMaterial
            var material_base = new THREE.ShaderMaterial(
                new
            {
                uniforms        = THREE.UniformsUtils.clone(uniforms),
                vertex_shader   = new GeometryVertexShader().ToString(),
                fragment_shader = new GeometryFragmentShader().ToString()
            }
                );

            //renderer.initMaterial(material_base, scene.lights, scene.fog);

            #region addObject
            var          r           = new Random();
            Func <float> Math_random = () => (float)r.NextDouble();


            for (var i = 0; i < 100; i++)
            {
                //var material_uniforms = (MyUniforms)THREE.__ThreeExtras.Uniforms.clone(uniforms);
                var material_uniforms = (MyUniforms)THREE.UniformsUtils.clone(uniforms);

                var material = new THREE.ShaderMaterial(
                    new
                {
                    uniforms        = material_uniforms,
                    vertex_shader   = new GeometryVertexShader().ToString(),
                    fragment_shader = new GeometryFragmentShader().ToString()
                }
                    );


                material.program = material_base.program;

                material_uniforms.uDirLightPos.value   = light.position;
                material_uniforms.uDirLightColor.value = light.color;
                material_uniforms.uBaseColor.value     = new THREE.Color((int)(Math_random() * 0xffffff));

                var mesh = new THREE.Mesh(geometry, material);
                mesh.position.x = Math_random() * 800f - 400f;
                mesh.position.y = Math_random() * 800f - 400f;
                mesh.position.z = Math_random() * 800f - 400f;

                mesh.rotation.x = Math_random() * 360f * (float)Math.PI / 180f;
                mesh.rotation.y = Math_random() * 360f * (float)Math.PI / 180f;
                mesh.rotation.z = Math_random() * 360f * (float)Math.PI / 180f;

                //scene.addObject(mesh);
                scene.add(mesh);
            }
            #endregion


            ///////////////////////////////

            var c = 0;

            container.appendChild(renderer.domElement);

            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                camera.aspect = (int)Native.window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(Native.window.Width, Native.window.Height);
            };

            Native.window.onresize +=
                delegate
            {
                AtResize();
            };

            AtResize();
            #endregion

            #region IsDisposed
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                IsDisposed = true;

                renderer.domElement.Orphanize();
            };
            #endregion

            #region tick

            Native.window.onframe += delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                c++;


                var l = scene.children.Length;

                Native.document.title = new { l }.ToString();

                var time = new IDate().getTime() * 0.0004;

                //var l = scene.objects.Length;

                for (var i = 0; i < l; i++)
                {
                    scene.children[i].rotation.x += 0.01f;
                    scene.children[i].rotation.y += 0.01f;
                }

                /*
                 * light.position.x = Math.sin( time );
                 * light.position.z = Math.cos( time );
                 * light.position.y = 0.5;
                 * light.position.normalize();
                 */

                renderer.render(scene, camera);
            };

            #endregion

            #region requestFullscreen
            Native.Document.body.ondblclick +=
                delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                Native.Document.body.requestFullscreen();
            };
            #endregion
        }
        // http://youtu.be/Lo1IU8UAutE
        // 60hz 2160 4K!

        // The equirectangular projection was used in map creation since it was invented around 100 A.D. by Marinus of Tyre. 

        //        C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hzsky.png" "/sdcard/oculus/360photos/"
        //1533 KB/s(3865902 bytes in 2.461s)

        //C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\tape360globe1\0000.png" "/sdcard/oculus/360photos/tape360globe1.png"
        //1556 KB/s(2714294 bytes in 1.703s)

        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hz2048c3840x2160.png" "/sdcard/oculus/360photos/"
        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push   "X:\vr\tape360globe1\0000.png" "/sdcard/oculus/360photos/tape360globe2.png"
        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push   "X:\vr\tape360globe1\0000.png" "/sdcard/oculus/360photos/tape360globenight.png"



        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809/chrome360hz

        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809

        // the eye nor the display will be able to do any stereo
        // until tech is near matrix capability. 2019?

        // cubemap can be used for all long range scenes
        // http://www.imdb.com/title/tt0112111/?ref_=nv_sr_1


        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150808/cubemapcamera
        // subst /D b:
        // subst b: s:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360GlobeAnimation\Chrome360GlobeAnimation\bin\Debug\staging\Chrome360GlobeAnimation.Application\web
        // subst a: z:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360GlobeAnimation\Chrome360GlobeAnimation\bin\Debug\staging\Chrome360GlobeAnimation.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360GlobeAnimation\Chrome360GlobeAnimation\bin\Debug\staging\Chrome360GlobeAnimation.Application\web
        // what if we want to do subst in another winstat or session?

        // ColladaLoader: Empty or non-existing file (assets/Chrome360GlobeAnimation/S6Edge.dae)

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //FormStyler.AtFormCreated =
            //s =>
            //{
            //    s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

            //    //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            //    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



            //    s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
            //    //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            //};

#if AsWEBSERVER
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                // if we run as a server. we can open up on android.

                //chrome.Notification.DefaultTitle = "Nexus7";
                //chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text
                //, AtFormCreated: FormStyler.AtFormCreated

                //AtFormConstructor:
                //    f =>
                //    {
                //        //arg[0] is typeof System.Int32
                //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                //    }
                );
                return;
            }
            #endregion
#else

            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    //chrome.runtime.UpdateAvailable += delegate
                    //{
                    //    new chrome.Notification(title: "UpdateAvailable");

                    //};

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "Chrome360GlobeAnimation");

                        // https://developer.chrome.com/apps/app_window#type-CreateWindowOptions
                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: new
                               {
                                   alwaysOnTop = true,
                                   visibleOnAllWorkspaces = true
                               }
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion


#endif

            // Earth params
            //var radius = 0.5;
            //var radius = 1024;
            //var radius = 2048;
            //var radius = 512;
            //var radius = 256;
            //var radius = 400;

            // can we have not fly beyond moon too much?
            //var radius = 500;
            var radius = 480;

            //var segments = 32;
            var segments = 128;
            //var rotation = 6;


            //const int size = 128;
            //const int size = 256; // 6 faces, 12KB
            //const int size = 512; // 6 faces, ?

            // WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled.

            //const int size = 720; // 6 faces, ?
            //const int size = 1024; // 6 faces, ?
            //const int cubefacesize = 1024; // 6 faces, ?

            // THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( chrome-extension://aemlnmcokphbneegoefdckonejmknohh/assets/Chrome360GlobeAnimation/anvil___spherical_hdri_panorama_skybox_by_macsix_d6vv4hs.jpg )
            int cubefacesize = 2048; // 6 faces, ?
                                     //int cubefacesize = 1024; // 6 faces, ?
                                     // "X:\vr\tape1\0000x2048.png"
                                     // for 60hz render we may want to use float camera percision, not available for ui.
                                     //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\tape1\0000x2048.png" "/sdcard/oculus/360photos/"
                                     //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\tape1\0000x128.png" "/sdcard/oculus/360photos/"

            //if (Environment.ProcessorCount < 8)
            //    //cubefacesize = 64; // 6 faces, ?
            //    cubefacesize = 1024; // 6 faces, ?

            new IHTMLPre { new { Environment.ProcessorCount, cubefacesize } }.AttachToDocument();

            // can we keep fast fps yet highp?

            // can we choose this on runtime? designtime wants fast fps, yet for end product we want highdef on our render farm?
            //const int cubefacesize = 128; // 6 faces, ?

            //var cubecameraoffsetx = 256;
            var cubecameraoffsetx = 400;


            //var uizoom = 0.1;
            //var uizoom = cubefacesize / 128f;
            var uizoom = 128f / cubefacesize;

            var far = 0xffffff;

            Native.css.style.backgroundColor = "blue";
            Native.css.style.overflow = IStyle.OverflowEnum.hidden;

            Native.body.Clear();
            (Native.body.style as dynamic).webkitUserSelect = "text";

            //new IHTMLPre { "can we stream it into VR, shadertoy, youtube 360, youtube stereo yet?" }.AttachToDocument();


            var sw = Stopwatch.StartNew();



            var oo = new List<THREE.Object3D>();

            var window = Native.window;


            // what about physics and that portal rendering?

            // if we are running as a chrome web server, we may also be opened as android ndk webview app
            //var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: window.aspect, near: 1, far: 2000);
            // once we update source
            // save the source
            // manually recompile 
            //cameraPX.position.z = 400;

            //// the camera should be close enough for the object to float off the FOV of PX
            //cameraPX.position.z = 200;

            // scene
            // can we make the 3D object orbit around us ?
            // and
            // stream it to vr?
            var scene = new THREE.Scene();

            // since our cube camera is somewhat a fixed thing
            // would it be easier to move mountains to come to us?
            // once we change code would chrome app be able to let VR know that a new view is available?
            var sceneg = new THREE.Group();
            sceneg.AttachTo(scene);


            // fly up?
            //sceneg.translateZ(-1024);
            // rotate the world, as the skybox then matches what we have on filesystem
            scene.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
            // yet for headtracking we shall rotate camera


            //sceneg.position.set(0, 0, -1024);
            //sceneg.position.set(0, -1024, 0);

            scene.add(new THREE.AmbientLight(0x333333));


            //384,400 km

            var distanceKM = 384400f;
            var earthdiameterKM = 12742f;
            var moondiameterKM = 3475f;
            var virtualDistance = radius / earthdiameterKM * distanceKM;
            // 12,742 km

            // 2,159.2 miles (3,475 km).


            var light = new THREE.DirectionalLight(0xffffff, 1);
            // sun should be beyond moon
            //light.position.set(-5 * virtualDistance, -3 * virtualDistance, -5 * virtualDistance);
            light.position.set(-15 * virtualDistance, -1 * virtualDistance, -15 * virtualDistance);
            scene.add(light);





            // whats WebGLRenderTargetCube do?

            // WebGLRenderer preserveDrawingBuffer 



            var renderer0 = new THREE.WebGLRenderer(

                new
                {
                    antialias = true,
                    alpha = true,
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836

            // the construct. white bg
            //renderer0.setClearColor(0xfffff, 1);
            renderer0.setClearColor(0x0, 1);

            //renderer.setSize(window.Width, window.Height);
            renderer0.setSize(cubefacesize, cubefacesize);

            //renderer0.domElement.AttachToDocument();
            //rendererPX.domElement.style.SetLocation(0, 0);
            //renderer0.domElement.style.SetLocation(4, 4);


            // top

            // http://stackoverflow.com/questions/27612524/can-multiple-webglrenderers-render-the-same-scene


            // need a place to show the cubemap face to GUI 
            // how does the stereo OTOY do it?
            // https://www.opengl.org/wiki/Sampler_(GLSL)

            // http://www.richardssoftware.net/Home/Post/25

            // [+X, –X, +Y, –Y, +Z, –Z] fa



            // move up
            //camera.position.set(-1200, 800, 1200);
            //var cameraoffset = new THREE.Vector3(0, 15, 0);

            // can we aniamte it?
            //var cameraoffset = new THREE.Vector3(0, 800, 1200);
            // can we have linear animation fromcenter of the map to the edge and back?
            // then do the flat earth sun orbit?
            var cameraoffset = new THREE.Vector3(
                // left?
                -512,
                // height?
                //0,
                //1600,
                //1024,

                // if the camera is in the center, would we need to move the scene?
                // we have to move the camera. as we move the scene the lights are messed up
                //2014,
                1024,

                //1200
                0
                // can we hover top of the map?
                );

            // original vieworigin
            //var cameraoffset = new THREE.Vector3(-1200, 800, 1200);



            var camerax = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 0 - 2048 * 4, max = 0 + 2048 * 4, valueAsNumber = 0, title = "camerax" }.AttachToDocument();
            // up. whats the most high a rocket can go 120km?
            new IHTMLHorizontalRule { }.AttachToDocument();


            // how high is the bunker?
            var cameray = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 0 - 2048 * 4, max = 2048 * 4, valueAsNumber = 0, title = "cameray" }.AttachToDocument();
            new IHTMLBreak { }.AttachToDocument();
            var camerayHigh = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = cameray.max, max = 1024 * 256, valueAsNumber = cameray.max, title = "cameray" }.AttachToDocument();
            new IHTMLHorizontalRule { }.AttachToDocument();
            var cameraz = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 0 - 2048 * 4, max = 0 + 2048 * 4, valueAsNumber = 0, title = "cameraz" }.AttachToDocument();

            // for render server
            var fcamerax = 0.0;
            var fcameray = 0.0;
            var fcameraz = 0.0;

            //while (await camerax.async.onchange)

            //cameray.onchange += delegate
            //{
            //    if (cameray.valueAsNumber < cameray.max)
            //        camerayHigh.valueAsNumber = camerayHigh.min;
            //};

            camerayHigh.onmousedown += delegate
            {
                //if (camerayHigh.valueAsNumber > camerayHigh.min)
                cameray.valueAsNumber = cameray.max;
            };


            Action applycameraoffset = delegate
            {
                // make sure UI and gpu sync up

                var cy = cameray;

                if (cameray.valueAsNumber < cameray.max)
                    camerayHigh.valueAsNumber = camerayHigh.min;

                if (camerayHigh.valueAsNumber > camerayHigh.min)
                    cameray.valueAsNumber = cameray.max;

                if (cameray.valueAsNumber == cameray.max)
                    cy = camerayHigh;



                cameraoffset = new THREE.Vector3(
                  // left?
                  camerax + fcamerax,
                   // height?
                   //0,
                   //1600,
                   //1024,

                   // if the camera is in the center, would we need to move the scene?
                   // we have to move the camera. as we move the scene the lights are messed up
                   //2014,
                   cy + fcameray,

                   //1200
                   cameraz + fcameraz
                   // can we hover top of the map?
                   );
            };


            #region y
            // need to rotate90?
            var cameraNY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraNY.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNY.lookAt(new THREE.Vector3(0, -1, 0));
                cameraNY.position.add(cameraoffset);
            };

            //cameraNY.lookAt(new THREE.Vector3(0, 1, 0));
            var canvasNY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNY.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 2);
            canvasNY.canvas.title = "NY";
            canvasNY.canvas.AttachToDocument();
            canvasNY.canvas.style.transformOrigin = "0 0";
            canvasNY.canvas.style.transform = "scale(" + uizoom + ")";

            var cameraPY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraPY.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPY.lookAt(new THREE.Vector3(0, 1, 0));
                cameraPY.position.add(cameraoffset);
            };
            //cameraPY.lookAt(new THREE.Vector3(0, -1, 0));
            var canvasPY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPY.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 0);
            canvasPY.canvas.title = "PY";
            canvasPY.canvas.AttachToDocument();
            canvasPY.canvas.style.transformOrigin = "0 0";
            canvasPY.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion

            // transpose xz?

            #region x
            var cameraNX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraNX.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNX.lookAt(new THREE.Vector3(0, 0, 1));
                cameraNX.position.add(cameraoffset);
            };
            //cameraNX.lookAt(new THREE.Vector3(0, 0, -1));
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNX.lookAt(new THREE.Vector3(1, 0, 0));
            var canvasNX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNX.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 2, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNX.canvas.title = "NX";
            canvasNX.canvas.AttachToDocument();
            canvasNX.canvas.style.transformOrigin = "0 0";
            canvasNX.canvas.style.transform = "scale(" + uizoom + ")";

            var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraPX.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPX.lookAt(new THREE.Vector3(0, 0, -1));
                cameraPX.position.add(cameraoffset);
            };
            //cameraPX.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPX.lookAt(new THREE.Vector3(1, 0, 0));
            //cameraPX.lookAt(new THREE.Vector3(-1, 0, 0));
            var canvasPX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPX.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPX.canvas.title = "PX";
            canvasPX.canvas.AttachToDocument();
            canvasPX.canvas.style.transformOrigin = "0 0";
            canvasPX.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion



            #region z
            var cameraNZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, -1));
            applycameraoffset += delegate
            {
                cameraNZ.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNZ.lookAt(new THREE.Vector3(1, 0, 0));
                cameraNZ.position.add(cameraoffset);
            };
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, 1));
            var canvasNZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNZ.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 3, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNZ.canvas.title = "NZ";
            canvasNZ.canvas.AttachToDocument();
            canvasNZ.canvas.style.transformOrigin = "0 0";
            canvasNZ.canvas.style.transform ="scale(" + uizoom + ")";

            var cameraPZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraPZ.lookAt(new THREE.Vector3(1, 0, 0));
            applycameraoffset += delegate
            {
                cameraPZ.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPZ.lookAt(new THREE.Vector3(-1, 0, 0));
                cameraPZ.position.add(cameraoffset);
            };
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, -1));
            var canvasPZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPZ.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPZ.canvas.title = "PZ";
            canvasPZ.canvas.AttachToDocument();
            canvasPZ.canvas.style.transformOrigin = "0 0";
            canvasPZ.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion




            // c++ alias locals would be nice..
            var canvas0 = (IHTMLCanvas)renderer0.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var st = new Stopwatch();
            st.Start();

            //canvas0.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            Native.body.onmousedown +=
                async e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                        return;

                    // movementX no longer works
                    old = new
                    {


                        e.CursorX,
                        e.CursorY
                    };


                    //e.CaptureMouse();
                    var release = e.Element.CaptureMouse();
                    await e.Element.async.onmouseup;

                    release();


                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            Native.body.onmousemove +=
                e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                    {
                        Native.body.style.cursor = IStyle.CursorEnum.@default;
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();


                    Native.body.style.cursor = IStyle.CursorEnum.move;

                    var pointerLock = canvas0 == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion

            // THREE.WebGLProgram: gl.getProgramInfoLog() C:\fakepath(78,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll
            // THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

            // http://www.roadtovr.com/youtube-confirms-stereo-3d-360-video-support-coming-soon/
            // https://www.youtube.com/watch?v=D-Wl9jAB45Q



            #region spherical
            var gl = new WebGLRenderingContext(alpha: true, preserveDrawingBuffer: true);
            var c = gl.canvas.AttachToDocument();

            //  3840x2160

            //c.style.SetSize(3840, 2160);

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150722/360-youtube


            c.width = 3840;
            c.height = 2160;


            //c.width = 3840 * 2;
            //c.height = 2160 * 2;


            //c.width = 3840;
            //c.height = 2160;
            // 1,777777777777778

            // https://www.youtube.com/watch?v=fTfJwzRsE-w
            //c.width = 7580;
            //c.height = 3840;
            //1,973958333333333

            //7580
            //    3840

            // wont work
            //c.width = 8192;
            //c.height = 4096;


            // this has the wrong aspect?
            //c.width = 6466;
            //c.height = 3232;

            new IHTMLPre { new { c.width, c.height } }.AttachToDocument();

            //6466x3232

            //var suizoom = 720f / c.height;
            //var suizoom = 360f / c.height;
            var suizoom = 480f / c.width;

            c.style.transformOrigin = "0 0";
            c.style.transform = "scale(" + suizoom + ")";
            //c.style.backgroundColor = "yellow";
            c.style.position = IStyle.PositionEnum.absolute;

            c.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 3);

            var pass = new CubeToEquirectangular.Library.ShaderToy.EffectPass(
                       null,
                       gl,
                       precission: CubeToEquirectangular.Library.ShaderToy.DetermineShaderPrecission(gl),
                       supportDerivatives: gl.getExtension("OES_standard_derivatives") != null,
                       callback: null,
                       obj: null,
                       forceMuted: false,
                       forcePaused: false,
                       //quadVBO: Library.ShaderToy.createQuadVBO(gl, right: 0, top: 0),
                       outputGainNode: null
                   );

            // how shall we upload our textures?
            // can we reference GLSL.samplerCube yet?
            //pass.mInputs[0] = new samplerCube { };
            pass.mInputs[0] = new CubeToEquirectangular.Library.ShaderToy.samplerCube { };

            pass.MakeHeader_Image();
            var vs = new Shaders.ProgramFragmentShader();
            pass.NewShader_Image(vs);

            #endregion




            //var frame0 = new HTML.Images.FromAssets.tiles_regrid().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets.galaxy_starfield().AttachToDocument();
            var frame0 = new HTML.Images.FromAssets.galaxy_starfield150FOV().AttachToDocument();
            //var xor = new HTML.Images.FromAssets.Orion360_test_image_8192x4096().AttachToDocument();
            //var xor = new HTML.Images.FromAssets._2_no_clouds_4k().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().AttachToDocument();


            // 270px
            //xor.style.height = "";
            frame0.style.height = "270px";
            frame0.style.width = "480px";
            frame0.style.SetLocation(
                8 + (int)(uizoom * cubefacesize + 8) * 0 + 480 + 16, 8 + (int)(uizoom * cubefacesize + 8) * 3);





            #region fixup rotation

            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI / 2);
            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), -Math.PI / 2);

            // dont need the fixup. unless we want to animate the sky rotate?
            //mesh.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
            #endregion


            // hide the sky to see camera lines?
            //  can we show this as HUD on VR in webview?
            //skybox.visible = false;
            //scene.add(skybox);




            //new IHTMLButton { }

            #region DirectoryEntry
            var dir = default(DirectoryEntry);

            new IHTMLButton { "openDirectory" }.AttachToDocument().onclick += async delegate
            {
                dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });
            };

            frame0.onclick += delegate
            {
                // http://paulbourke.net/papers/vsmm2006/vsmm2006.pdf
                //            A method of creating synthetic stereoscopic panoramic images that can be implemented
                //in most rendering packages has been presented. If single panoramic pairs can be created
                //then stereoscopic panoramic movies are equally possible giving rise to the prospect of
                //movies where the viewer can interact with, at least with regard to what they choose to look
                //at.These images can be projected so as to engage the two features of the human visual
                //system that assist is giving us a sense of immersion, the feeling of “being there”. That is,
                //imagery that contains parallax information as captured from two horizontally separated eye
                //positions (stereopsis)and imagery that fills our peripheral vision.The details that define
                //how the two panoramic images should be created in rendering packages are provided, in
                //particular, how to precisely configure the virtual cameras and control the distance to zero
                //parallax.

                // grab a frame

                if (dir == null)
                {
                    // not exporting to file system?
                    var f0 = new IHTMLImage { src = gl.canvas.toDataURL() };

                    //var f0 = (IHTMLImage)gl.canvas;
                    //var f0 = (IHTMLImage)gl.canvas;
                    //var base64 = gl.canvas.toDataURL();


                    //frame0.src = base64;
                    frame0.src = f0.src;

                    // 7MB!

                    return;
                }

                //                // ---------------------------
                //IrfanView
                //---------------------------
                //Warning !
                //The file: "X:\vr\tape1\0001.jpg" is a PNG file with incorrect extension !
                //Rename ?
                //---------------------------
                //Yes   No   
                //---------------------------

                // haha this will render the thumbnail.
                //dir.WriteAllBytes("0000.png", frame0);

                //dir.WriteAllBytes("0000.png", gl.canvas);

                var glsw = Stopwatch.StartNew();
                dir.WriteAllBytes("0000.png", gl);

                new IHTMLPre { new { glsw.ElapsedMilliseconds } }.AttachToDocument();

                // {{ ElapsedMilliseconds = 1548 }}

                // 3.7MB
                // 3840x2160

            };

            #endregion

            var vsync = default(TaskCompletionSource<object>);

            new IHTMLButton {
                "render 60hz 30sec"
            }.AttachToDocument().onclick += async e =>
            {
                e.Element.disabled = true;


                var total = Stopwatch.StartNew();
                var status = "rendering... " + new { dir };

                new IHTMLPre { () => status }.AttachToDocument();

                if (dir == null)
                {
                    //dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });
                }

                total.Restart();



                vsync = new TaskCompletionSource<object>();
                await vsync.Task;

                status = "rendering... vsync";

                var frameid = 0;

                goto beforeframe;


                // parallax offset?

                await_nextframe:


                var filename = frameid.ToString().PadLeft(4, '0') + ".png";
                status = "rendering... " + new { frameid, filename };


                vsync = new TaskCompletionSource<object>();
                await vsync.Task;

                // frame0 has been rendered

                var swcapture = Stopwatch.StartNew();
                status = "WriteAllBytes... " + new { filename };
                //await Native.window.async.onframe;

                // https://code.google.com/p/chromium/issues/detail?id=404301
                if (dir != null)
                    await dir.WriteAllBytes(filename, gl);
                //await dir.WriteAllBytes(filename, gl.canvas);

                status = "WriteAllBytes... done " + new { fcamerax, filename, swcapture.ElapsedMilliseconds };
                status = "rdy " + new { filename, fcamerax };
                //await Native.window.async.onframe;


                beforeframe:

                // speed? S6 slow motion?
                // this is really slow. if we do x4x2 =x8 
                // https://www.youtube.com/watch?v=r76ULW16Ib8
                //fcamerax += 16 * (1.0 / 60.0);
                fcamerax = radius * Math.Cos(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f));

                cameraz.valueAsNumber = (int)(cameraz.max * Math.Sin(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f)));


                // up
                //fcameray = 128 * Math.Cos(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f));

                //fcamerax += (1.0 / 60.0);

                //fcamerax += (1.0 / 60.0) * 120;

                if (Environment.ProcessorCount < 8)
                    frameid += 15;
                else
                    frameid++;

                // 60hz 30sec
                if (frameid < 60 * 30)
                {
                    // Blob GC? either this helms or the that we made a Blob static. 
                    await Task.Delay(11);

                    goto await_nextframe;
                }

                total.Stop();
                status = "all done " + new { frameid, total.ElapsedMilliseconds };
                vsync = default(TaskCompletionSource<object>);
                // http://stackoverflow.com/questions/22899333/delete-javascript-blobs

                e.Element.disabled = false;
            };

            // "Z:\jsc.svn\examples\javascript\WebGL\WebGLColladaExperiment\WebGLColladaExperiment\WebGLColladaExperiment.csproj"


            #region moonsphere
            var moonsphere = new THREE.Mesh(
                    new THREE.SphereGeometry(radius / earthdiameterKM * moondiameterKM, segments, segments),
                    new THREE.MeshPhongMaterial(
                            new
                            {
                                map = new THREE.Texture().With(

                                    async s =>
                                    {
                                        //0:75ms event: _2_no_clouds_4k_low view-source:36543
                                        //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1
                                        //Application Cache Progress event (2 of 2)  192.168.1.72/:1
                                        //Application Cache Cached event 192.168.1.72/:1
                                        //1:1018ms event: _2_no_clouds_4k_low done view-source:36543
                                        //1:1019ms event: _2_no_clouds_4k view-source:36543
                                        //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995
                                        //1:16445ms event: _2_no_clouds_4k done 

                                        // ~ tilde to open css editor?


                                        //await 20000;

                                        //Console.WriteLine("event: _2_no_clouds_4k");
                                        s.image = await new moon();
                                        s.needsUpdate = true;
                                        //Console.WriteLine("event: _2_no_clouds_4k done");
                                    }
                                ),


                                //bumpMap = THREE.ImageUtils.loadTexture(
                                //    new elev_bump_4k().src
                                ////new elev_bump_4k_low().src
                                //),


                                //// applies onyl to shaders to create the shadow
                                //bumpScale = 0.005,

                                //specularMap = new THREE.Texture().With(
                                //    async s =>
                                //    {

                                //        Console.WriteLine("event: water_4k");
                                //        s.image = await new water_4k().async.oncomplete;
                                //        s.needsUpdate = true;
                                //        Console.WriteLine("event: water_4k done");
                                //    }
                                //),


                                ////specular =    new THREE.Color("grey")								
                                //specular = new THREE.Color(0xa0a0a0)
                            })
                );
            #endregion


            //moonsphere.position.set(radius * 4, 0, 0);
            //moonsphere.position.set(0, 0, -radius * 4);

            scene.add(moonsphere);


            #region globesphere
            var globesphere = new THREE.Mesh(
                    new THREE.SphereGeometry(radius, segments, segments),
                    new THREE.MeshPhongMaterial(
                            new
                            {
                                map = new THREE.Texture().With(

                                    async s =>
                                    {
                                        //0:75ms event: _2_no_clouds_4k_low view-source:36543
                                        //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1
                                        //Application Cache Progress event (2 of 2)  192.168.1.72/:1
                                        //Application Cache Cached event 192.168.1.72/:1
                                        //1:1018ms event: _2_no_clouds_4k_low done view-source:36543
                                        //1:1019ms event: _2_no_clouds_4k view-source:36543
                                        //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995
                                        //1:16445ms event: _2_no_clouds_4k done 

                                        // ~ tilde to open css editor?


                                        //await 20000;

                                        //Console.WriteLine("event: _2_no_clouds_4k");
                                        s.image = await new _2_no_clouds_4k();
                                        s.needsUpdate = true;
                                        //Console.WriteLine("event: _2_no_clouds_4k done");
                                    }
                                ),


                                bumpMap = THREE.ImageUtils.loadTexture(
                                    new elev_bump_4k().src
                                //new elev_bump_4k_low().src
                                ),


                                // applies onyl to shaders to create the shadow
                                bumpScale = 0.005,

                                specularMap = new THREE.Texture().With(
                                    async s =>
                                    {

                                        Console.WriteLine("event: water_4k");
                                        s.image = await new water_4k().async.oncomplete;
                                        s.needsUpdate = true;
                                        Console.WriteLine("event: water_4k done");
                                    }
                                ),


                                //specular =    new THREE.Color("grey")								
                                specular = new THREE.Color(0xa0a0a0)
                            })
                );
            #endregion



            // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane


            //globesphere.rotation.y = rotation;
            scene.add(globesphere);


            #region clouds
            var clouds = new THREE.Mesh(
                    new THREE.SphereGeometry(
                        //radius + 0.003,
                        radius + radius * 0.01,
                        segments, segments),
                    new THREE.MeshPhongMaterial(
                        new
                        {
                            //map = THREE.ImageUtils.loadTexture(
                            //    //new fair_clouds_4k().src
                            //    new fair_clouds_4k_low().src
                            //    ),


                            map = new THREE.Texture().With(
                                async s =>
                                {


                                    Console.WriteLine("event: fair_clouds_4k");
                                    s.image = await new fair_clouds_4k().async.oncomplete;
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: fair_clouds_4k done");
                                }
                            ),


                            transparent = true
                        })
                );
            //clouds.rotation.y = rotation;
            scene.add(clouds);
            #endregion



            //clouds.position.set(0, virtualDistance / -2, 0);
            //globesphere.position.set(0, virtualDistance / -2, 0);

            //moonsphere.position.set(0, virtualDistance / 2, 0);


            //clouds.position.set(virtualDistance / -2, 0, 0);
            //globesphere.position.set(virtualDistance / -2, 0, 0);

            //moonsphere.position.set(virtualDistance / 2, 0, 0);

            clouds.position.set(virtualDistance / 2, (int)(-radius * 1.06), 0);
            globesphere.position.set(virtualDistance / 2, (int)(-radius * 1.06), 0);

            // moon dark side away from earth?
            //moonsphere.position.set(virtualDistance / -2, -radius, 0);
            moonsphere.position.set(virtualDistance / -2, radius / earthdiameterKM * moondiameterKM, 0);

            applycameraoffset += delegate
            {
                globesphere.rotation.y = Math.Sin((cameraz.max * 0.5 + cameraz.valueAsNumber) * 0.0005);
                clouds.rotation.y = Math.Sin((cameraz.max * 0.5 + cameraz.valueAsNumber) * 0.0006);
            };

            //globesphere.position.set(0, radius / earthdiameterKM * distanceKM, 0);

            //clouds.rotateOnAxis(new THREE.Vector3(0, 1, 0), Math.PI / 2);
            //globesphere.rotateOnAxis(new THREE.Vector3(0, 1, 0), Math.PI / 2);



            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeEarth\ChromeEarth\Application.cs
            // X:\jsc.svn\examples\javascript\canvas\ConvertBlackToAlpha\ConvertBlackToAlpha\Application.cs
            // hidden for alpha AppWindows
            //#if FBACKGROUND

            #region galaxy_starfield
            new THREE.Texture().With(
                async s =>
                {
                    //var i = new HTML.Images.FromAssets.galaxy_starfield();
                    var i = new HTML.Images.FromAssets.galaxy_starfield150FOV();

                    var bytes = await i.async.bytes;

                    //for (int ii = 0; ii < bytes.Length; ii += 4)
                    //{

                    //    bytes[ii + 3] = (byte)(bytes[ii + 0]);

                    //    bytes[ii + 0] = 0xff;
                    //    bytes[ii + 1] = 0xff;
                    //    bytes[ii + 2] = 0xff;
                    //}

                    var cc = new CanvasRenderingContext2D(i.width, i.height);

                    cc.bytes = bytes;

                    s.image = cc;
                    s.needsUpdate = true;

                    var stars_material = new THREE.MeshBasicMaterial(
                            new
                            {
                                //map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src),
                                map = s,
                                side = THREE.BackSide,
                                transparent = true
                            });


                    var stars = new THREE.Mesh(
                            new THREE.SphereGeometry(far * 0.9, 64, 64),
                           stars_material
                        );

                    // http://stackoverflow.com/questions/8502150/three-js-how-can-i-dynamically-change-objects-opacity
                    //(stars_material as dynamic).opacity = 0.5;


                    scene.add(stars);
                }
           );
            #endregion




            new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = -(65 - 200);





                       var scale = 0.9;

                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;


                       #region onmousewheel
                       Native.body.onmousewheel +=
                           e =>
                           {
                               e.preventDefault();

                               //camera.position.z = 1.5;

                               // min max. shall adjust speed also!
                               // max 4.0
                               // min 0.6
                               dae.position.z -= 10.0 * e.WheelDirection;

                               //camera.position.z = 400;
                               //dae.position.z = dae.position.z.Max(-200).Min(200);

                               //Native.document.title = new { z }.ToString();

                           };
                       #endregion


                       //dae.position.y = -80;

                       //dae.AttachTo(sceneg);
                       //scene.add(dae);
                       //oo.Add(dae);




                       // view-source:http://threejs.org/examples/webgl_multiple_canvases_circle.html
                       // https://threejsdoc.appspot.com/doc/three.js/src.source/extras/cameras/CubeCamera.js.html
                       Native.window.onframe +=
                           e =>
                           {
                               // let render man know..
                               if (vsync != null)
                                   if (vsync.Task.IsCompleted)
                                       return;


                               //if (pause) return;
                               //if (pause.@checked)
                               //    return;


                               // can we float out of frame?
                               // haha. a bit too flickery.
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.01) * 50.0;
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.001) * 190.0;
                               //globesphere.position.y = Math.Sin(fcamerax * 0.001) * 90.0;
                               //clouds.position.y = Math.Cos(fcamerax * 0.001) * 90.0;

                               //sphere.rotation.y += speed;
                               //clouds.rotation.y += speed;

                               // manual rebuild?
                               // red compiler notifies laptop chrome of pending update
                               // app reloads

                               applycameraoffset();
                               renderer0.clear();
                               //rendererPY.clear();

                               //cameraPX.aspect = canvasPX.aspect;
                               //cameraPX.updateProjectionMatrix();

                               // um what does this do?
                               //cameraPX.position.z += (z - cameraPX.position.z) * e.delay.ElapsedMilliseconds / 200.0;
                               // mousewheel allos the camera to move closer
                               // once we see the frame in vr, can we udp sync vr tracking back to laptop?


                               //this.targetPX.x += 1;
                               //this.targetNX.x -= 1;

                               //this.targetPY.y += 1;
                               //this.targetNY.y -= 1;

                               //this.targetPZ.z += 1;
                               //this.targetNZ.z -= 1;

                               // how does the 360 or shadertoy want our cubemaps?


                               // and then rotate right?

                               // how can we render cubemap?


                               #region x
                               // upside down?
                               renderer0.render(scene, cameraPX);
                               canvasPX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNX);
                               canvasNX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion

                               #region z
                               renderer0.render(scene, cameraPZ);
                               canvasPZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNZ);
                               canvasNZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion



                               #region y
                               renderer0.render(scene, cameraPY);

                               //canvasPY.save();
                               //canvasPY.translate(0, size);
                               //canvasPY.rotate((float)(-Math.PI / 2));
                               canvasPY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasPY.restore();


                               renderer0.render(scene, cameraNY);
                               //canvasNY.save();
                               //canvasNY.translate(size, 0);
                               //canvasNY.rotate((float)(Math.PI / 2));
                               canvasNY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasNY.restore();
                               // ?
                               #endregion


                               //renderer0.render(scene, cameraPX);


                               //rendererPY.render(scene, cameraPY);

                               // at this point we should be able to render the sphere texture

                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_X = 34070;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Y = 34071;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Z = 34073;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074;


                               //var cube0 = new IHTMLImage[] {
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_px(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nx(),

                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_py(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_ny(),


                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_pz(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nz()
                               //};

                               new[] {
                                   canvasPX, canvasNX,
                                   canvasPY, canvasNY,
                                   canvasPZ, canvasNZ
                               }.WithEachIndex(
                                   (img, index) =>
                                   {
                                       gl.bindTexture(gl.TEXTURE_CUBE_MAP, pass.tex);

                                       //gl.pixelStorei(gl.UNPACK_FLIP_X_WEBGL, false);
                                       gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

                                       // http://stackoverflow.com/questions/15364517/pixelstoreigl-unpack-flip-y-webgl-true

                                       // https://msdn.microsoft.com/en-us/library/dn302429(v=vs.85).aspx
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);

                                       gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + (uint)index, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img.canvas);

                                   }
                                );

                               // could do dynamic resolution- fog of war or fog of FOV. where up to 150deg field of vision is encouragedm, not 360
                               pass.Paint_Image(
                                     0,

                                     0,
                                     0,
                                     0,
                                     0
                                //,

                                // gl_FragCoord
                                // cannot be scaled, and can be referenced directly.
                                // need another way to scale
                                //zoom: 0.3f
                                );

                               //paintsw.Stop();


                               // what does it do?
                               gl.flush();

                               // let render man know..
                               if (vsync != null)
                                   if (!vsync.Task.IsCompleted)
                                       vsync.SetResult(null);
                           };


                   }
               );





            Console.WriteLine("do you see it?");
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // what are we looking at?

            var scene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 1000);
            camera.position.z = 300;

            var renderer = new THREE.WebGLRenderer(
                   new
                   {
                       preserveDrawingBuffer = true
                   }
                );
            renderer.setSize();

            scene.add(new THREE.AmbientLight(0x333333));

            var light = new THREE.DirectionalLight(0xffffff, 1);
            light.position.set(5, 3, 5);
            scene.add(light);
   
            var cube = new THREE.CubeGeometry(0.5,0.5,0.5);
            var material = new THREE.MeshBasicMaterial(new
                        {
                            color = new THREE.Color(0xADD8E6),
                        });

            var obj = new THREE.Object3D();

            for (var x = 0; x < 100; x++)
            {
                for (var y = 0; y < 100; y++)
                {
                    for (var zz = 0; zz < 15; zz++)
                    {
                        var mesh1 = new THREE.Mesh(cube, material);
                        mesh1.position.x = x;
                        mesh1.position.y = y;
                        mesh1.position.z = zz;
                        obj.add(mesh1);
                    }
                }
            }

            //var mesh1 = new THREE.Mesh(cube, material);
            //mesh1.position.x = 1;
            //mesh1.position.y = 1;
            //mesh1.position.z = 1;
            //obj.add(mesh1);
            scene.add(obj);

            var z = camera.position.z;

            this.canvas = (IHTMLCanvas)renderer.domElement;

            //renderer.domElement.AttachToDocument();
            this.canvas.AttachToDocument();
            this.canvas.style.SetLocation(0, 0);

            Native.window.onframe +=
                e =>
                {
                    //if (this.canvas.parentNode == null)
                    //    return;

                    camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                    camera.updateProjectionMatrix();

                    camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                    // the larger the vew the slower the rotation shall be
                    var speed = 0.0001 * e.delay.ElapsedMilliseconds +
                        0.007
                        * 96.0 / canvas.clientHeight
                        * 1.0 / camera.position.z;

                    //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString();
                    //Native.document.title = new { speed }.ToString();


                    //controls.update();
                    //sphere.rotation.y += speed;
                    obj.rotation.y += speed;


                    renderer.render(scene, camera);
                };

            Native.window.onresize +=
                delegate
                {


                    //if (canvas.parentNode == Native.document.body)

                    // are we embedded?
                    if (page != null)
                        renderer.setSize();
                };
        }
Example #14
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List <THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                10000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);


            var mouseX = 0;
            var mouseY = 0;
            var st     = new Stopwatch();
            st.Start();


            Native.window.document.onmousemove +=
                e =>
            {
                mouseX = e.CursorX - Native.window.Width / 2;
                mouseY = e.CursorY - Native.window.Height / 2;
            };


            Native.window.onframe +=
                delegate
            {
                oo.WithEach(
                    x =>
                    x.rotation.y = (st.ElapsedMilliseconds + mouseX * 100) * 0.00001
                    );


                camera.position.x += (mouseX - camera.position.x) * .05;
                camera.position.y += (-mouseY - camera.position.y) * .05;

                camera.lookAt(scene.position);

                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                camera.aspect = window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(window.Width, window.Height);
            };
            #endregion

            // why isnt it being found?
            new global::WebGLColladaExperiment.THREE_ColladaAsset(

                // we get purple small thingy
                "assets/WebGLHeatZeekerColladaExperiment/Promotion3D_daytime.dae"

                // maybe sketchup doesnt know how to export colors?
                //"assets/WebGLHeatZeekerColladaExperiment/sam_site.dae"
                ).Source.Task.ContinueWithResult(
                dae =>
            {
                dae.position.y = -40;
                //dae.position.z = 280;
                scene.add(dae);
                oo.Add(dae);

                dae.scale = new THREE.Vector3(2, 2, 2);
            }
                );
        }
Example #15
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // 1e40:01:01 RewriteToAssembly error: System.MissingMethodException: Method not found: 'Void ScriptCoreLib.JavaScript.DOM.IWindow.add_onframe(System.Action`1<Int32>)'.

#if chrome_works_again
            #region AtFormCreated
            FormStyler.AtFormCreated =
                s =>
            {
                s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

                var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            };
            #endregion


            // chrome 31 wont load view-source
            // chrome 33 shows black window. nice.
            #region ChromeTCPServer
            dynamic self               = Native.self;
            dynamic self_chrome        = self.chrome;
            object  self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                chrome.Notification.DefaultTitle = "Droplet";
                //chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Preview().src;

                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                    AppSource.Text,
                    AtFormCreated: FormStyler.AtFormCreated
                    );

                return;
            }
            #endregion
#endif


            #region clouds
            new WebGLClouds.HTML.Pages.Default().With(
                layout =>
            {
                layout.body.AttachTo(page.clouds);

                new WebGLClouds.Application(layout);
            }
                );
            #endregion



            page.header.style.backgroundColor = "";

            page.header.css.style.transition      = "background-color 200ms linear";
            page.header.css.style.backgroundColor = "rgba(255, 255, 0, 0)";
            //page.header.css.style.backgroundColor = "rgba(255, 255, 0, 0.2)";

            page.header.css.hover.style.backgroundColor = "rgba(255, 255, 0, 1.0)";

            Native.window.onframe +=
                delegate
            {
                if (Native.document.body.scrollTop == 0)
                {
                    page.header.css.style.backgroundColor = "rgba(255, 255, 0, 0)";
                }
                else
                {
                    page.header.css.style.backgroundColor = "rgba(0, 0, 0, 0.3)";
                }
            };

            var oo = new List <THREE.Object3D>();

            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                page.header.clientWidth / (double)page.header.clientHeight,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var renderer = new THREE.WebGLRenderer();

            //renderer.domElement.AttachToDocument();
            renderer.domElement.AttachTo(page.header);
            renderer.setSize(page.header.clientWidth, page.header.clientHeight);
            //renderer.setSize(window.Width, window.Height);
            //renderer.domElement.style.SetLocation(0, 0);


            var mouseX = 0;
            var mouseY = 0;
            var st     = new Stopwatch();
            st.Start();

            Native.window.onframe +=
                delegate
            {
                oo.WithEach(
                    x =>
                    x.rotation.y = st.ElapsedMilliseconds * 0.001
                    );


                camera.position.x += (mouseX - camera.position.x) * .05;
                camera.position.y += (-mouseY - camera.position.y) * .05;

                camera.lookAt(scene.position);

                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                camera.aspect = page.header.clientWidth / (double)page.header.clientHeight;

                camera.updateProjectionMatrix();

                //renderer.setSize(window.Width, window.Height);
                renderer.setSize(page.header.clientWidth, page.header.clientHeight);
            };



            var data = Book1.GetDataSet();

            #region bind
            Func <string, IHTMLElement, DataGridView> bind =
                (DataMember, c) =>
            {
                var g = new DataGridView
                {
                    BackgroundColor = Color.Transparent,


                    // does this work?
                    DefaultCellStyle = new DataGridViewCellStyle
                    {
                        SelectionBackColor = Color.Black,
                        SelectionForeColor = Color.Yellow,

                        //BackColor = Color.Transparent
                        //BackColor = Color.FromArgb(0x05, 0, 0, 0)
                        BackColor = Color.FromArgb(0x3f, 255, 255, 255)
                    },

                    ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
                    {
                        BackColor = Color.FromArgb(0x8f, 255, 255, 255)
                    },


                    SelectionMode       = DataGridViewSelectionMode.FullRowSelect,
                    AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,

                    // do we have a test for this?
                    AllowUserToAddRows = false,

                    //AllowUserToDeleteRows = false,

                    RowHeadersVisible = false,


                    // cannot hide column headers yet
                    // script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.DataGridView.set_ColumnHeadersVisible(System.Boolean)]
                    //ColumnHeadersVisible = false,

                    DataSource = data,
                    DataMember = DataMember,
                };

                // this should be the one that maximizes itself onto the parent which is supposed to be absolute in size
                //g.GetHTMLTarget().With(
                //    div =>
                //    {
                //        //div.style.reset();

                //        // no scrollbars, thanks
                //        div.style.overflow = IStyle.OverflowEnum.hidden;
                //        (div.style as dynamic).zIndex = "";

                //        div.style.position = IStyle.PositionEnum.relative;
                //        div.style.left = "";
                //        div.style.top = "";
                //        div.style.right = "";
                //    }
                //);

                c.style.position = IStyle.PositionEnum.relative;
                c.style.height   = "20em";

                c.Clear();
                g.AttachControlTo(c);

                return(g);
            };
            #endregion


            bind("Assets", page.assets);
            bind("Transactions", page.transactions).ReadOnly = true;

            // script: error JSC1000: No implementation found for this native method, please implement [System.Data.DataTableCollection.get_Item(System.String)]
            var data_Assets       = data.Tables["Assets"];
            var data_Transactions = data.Tables["Transactions"];


            #region data_Assets_NewRow
            Action <DataRow> data_Assets_NewRow =
                SourceRow =>
            {
                var r = new Random();

                new sack_of_gold2().Source.Task.ContinueWithResult(
                    o =>
                {
                    o.position.y = -80;
                    scene.add(o);
                    oo.Add(o);

                    o.position.x         = r.Next(-250, 250);
                    o.position.z         = r.Next(-400, 200);
                    (o as dynamic).scale = new THREE.Vector3(0.5, 0.5, 0.5);

                    data_Assets.RowDeleting +=
                        (sender, e) =>
                    {
                        if (SourceRow != e.Row)
                        {
                            return;
                        }

                        scene.remove(o);
                        oo.Remove(o);

                        data_Transactions.Rows.Add(
                            "now", "item removed -" + SourceRow["Net worth"]
                            );
                    };
                }
                    );
            };
            #endregion


            data_Assets.Rows.AsEnumerable().WithEach(data_Assets_NewRow);

            // "X:\jsc.svn\examples\javascript\DropFileIntoSQLite\DropFileIntoSQLite.sln"
            // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs
            #region ondragstart
            page.header.ondragstart +=
                e =>
            {
                data_Assets.Rows.AsEnumerable().FirstOrDefault().With(
                    SourceRow =>
                {
                    // x:\jsc.svn\examples\javascript\dropfileintosqlite\dropfileintosqlite\application.cs

                    data_Assets.Rows.Remove(SourceRow);
                    //data_Assets.Rows.RemoveAt(0);


                    var clipboard = new DataTable();

                    clipboard.Columns.AddRange(
                        Enumerable.ToArray(
                            from x in data_Assets.Columns.AsEnumerable()
                            select new DataColumn {
                        ColumnName = x.ColumnName
                    }
                            )
                        );

                    clipboard.Rows.Add(
                        Enumerable.ToArray(
                            from x in data_Assets.Columns.AsEnumerable()
                            select SourceRow[x]
                            )
                        );

                    e.dataTransfer.effectAllowed = "copy";

                    var clipboard_string = StringConversionsForDataTable.ConvertToString(clipboard);
                    e.dataTransfer.setData(typeof(DataTable).Name, clipboard_string);
                }
                    );
            };
            #endregion


            // X:\jsc.svn\market\javascript\Abstractatech.JavaScript.FileStorage\Abstractatech.JavaScript.FileStorage\Application.cs
            var dz = new DropZone();


            var TimerHide = new ScriptCoreLib.JavaScript.Runtime.Timer(
                delegate
            {
                dz.body.Orphanize();
            }
                );

            #region ondragover
            Action <DragEvent> ondragover =
                evt =>
            {
                evt.stopPropagation();
                evt.preventDefault();


                if (evt.dataTransfer.types.Contains(typeof(DataTable).Name.ToLower()))
                {
                    evt.dataTransfer.dropEffect = "copy";     // Explicitly show this is a copy.

                    dz.body.AttachTo(Native.document.documentElement);
                    dz.bglayer.style.transition      = "background-color 500ms linear";
                    dz.bglayer.style.backgroundColor = "rgba(0,0,0, 0.7)";

                    TimerHide.Stop();
                }
            };

            Native.Document.body.ondragover += ondragover;
            dz.Container.ondragover         += ondragover;
            #endregion



            dz.Container.ondragleave +=
                evt =>
            {
                //Console.WriteLine("ondragleave");

                //Console.WriteLine(" dz.Container.ondragleave");
                TimerHide.StartTimeout(90);

                evt.stopPropagation();
                evt.preventDefault();
            };

            Native.window.onblur +=
                delegate
            {
                data_Transactions.Rows.Add(
                    //"now", "item added +" + SourceRow["Net worth"]
                    "now", "blur"
                    );
            };

            Native.window.onfocus +=
                delegate
            {
                data_Transactions.Rows.Add(
                    //"now", "item added +" + SourceRow["Net worth"]
                    "now", "focus"
                    );
            };

            data_Assets_NewRow +=
                SourceRow =>
            {
                data_Transactions.Rows.Add(
                    //"now", "item added +" + SourceRow["Net worth"]
                    "now", "item added"
                    );
            };

            data_Assets.TableNewRow +=
                (sender, e) =>
            {
                data_Assets_NewRow(e.Row);
            };


            #region ondrop
            dz.Container.ondrop +=
                evt =>
            {
                //Console.WriteLine("ondrop");

                TimerHide.StartTimeout(90);

                evt.stopPropagation();
                evt.preventDefault();

                if (evt.dataTransfer.items != null)
                {
                    // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs

                    evt.dataTransfer.items.AsEnumerable().Where(
                        x =>

                        x.type.ToLower() ==

                        // let jsc type system sort it out?
                        // how much reflection does jsc give us nowadays?
                        typeof(DataTable).Name.ToLower()

                        ).WithEach(
                        async xx =>
                    {
                        // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dfnReturnLink-0
                        var DataTable_xml = await xx.getAsString();

                        var DataTable = StringConversionsForDataTable.ConvertFromString(DataTable_xml);

                        DataTable.Rows.AsEnumerable().WithEach(
                            SourceRow =>
                        {
                            data_Assets.Rows.Add(
                                Enumerable.ToArray(
                                    from x in data_Assets.Columns.AsEnumerable()
                                    select SourceRow[x]
                                    )
                                );
                        }
                            );
                    }
                        );
                }
            };
            #endregion
        }
        public override void Init()
        {
            base.Init();

            controls = new THREE.TrackballControls(camera, Container);

            controls.rotateSpeed = 3.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;

            controls.noZoom = false;
            controls.noPan = false;

            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;

            controls.keys = new int[] { 65, 83, 68 };

            scene = new THREE.Scene();
               // THREE.FogExp2 fg2 = new THREE.FogExp2(new THREE.Color().setHex(0xcccccc), 0.002);

            THREE.FogExp2 fg2 = new THREE.FogExp2(0xcccccc, 0.002);
            scene.fog = fg2;

            var geometry = new THREE.CylinderGeometry(0, 10, 30, 4, 1);
            var material = new THREE.MeshPhongMaterial();

            material.color = new THREE.Color().setHex(0xffffff); // 0xffffff;
            material.shading = THREE.ShadingType.FlatShading;

            for (var i = 0; i < 500; i++)
            {

                var mesh = new THREE.Mesh(geometry, material);
                mesh.position.x = (Math.Random() - 0.5) * 1000;
                mesh.position.y = (Math.Random() - 0.5) * 1000;
                mesh.position.z = (Math.Random() - 0.5) * 1000;
                mesh.updateMatrix();
                mesh.matrixAutoUpdate = false;
                scene.add(mesh);

            }

            // lights

            THREE.Light light = new THREE.DirectionalLight();
            light.color = new THREE.Color().setHex(0xffffff);
            light.position.set(1, 1, 1);
            scene.add(light);

            light = new THREE.DirectionalLight();
            light.color = new THREE.Color().setHex(0x002288);
            light.position.set(-1, -1, -1);
            scene.add(light);

            light = new THREE.AmbientLight(0x222222);
            light.color = new THREE.Color().setHex(0x222222);
            scene.add(light);

            // renderer

            renderer = new THREE.WebGLRenderer(false);
            renderer.antialias = false;
            renderer.setClearColor(scene.fog.color);
            //TODO: renderer.setPixelRatio( Window.devicePixelRatio );
            renderer.setSize(Width, Height);

            Container.AppendChild(renderer.domElement);

            //stats = new Stats();
            //stats.domElement.style.position = 'absolute';
            //stats.domElement.style.top = '0px';
            //stats.domElement.style.zIndex = 100;
            //container.appendChild( stats.domElement );

            //

            //
        }
Example #17
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            var oo = new List <THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);


            var mouseX = 0;
            var mouseY = 0;
            var st     = new Stopwatch();
            st.Start();

            Native.window.onframe +=
                delegate
            {
                oo.WithEach(
                    x =>
                    x.rotation.y = st.ElapsedMilliseconds * 0.001
                    );


                camera.position.x += (mouseX - camera.position.x) * .05;
                camera.position.y += (-mouseY - camera.position.y) * .05;

                camera.lookAt(scene.position);

                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                camera.aspect = window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(window.Width, window.Height);
            };
            #endregion


            var ref0 = new TexturesImages();

            //var texture = new THREE.Texture(
            //    //new HTML.Images.FromAssets.ash_uvgrid01()
            //    //new HTML.Images.FromAssets.texture_palm()
            //           new TLC200_Side_89pc()
            //      );
            //texture.needsUpdate = true;

            // X:\jsc.svn\examples\javascript\WebGL\WebGLMTLExperiment\WebGLMTLExperiment\Application.cs

            var loader = new THREE.OBJMTLLoader();
            loader.load(
                "assets/WebGLOBJToyota/LX570_2008.obj",
                "assets/WebGLOBJToyota/LX570_2008.mtl",
                new Action <THREE.Object3D>(
                    o =>
            {
                Console.WriteLine("onload " + new { o });

                // need to use
                // Toyota Land Cruiser 200 Series aka Lexus LX 570_2008.mtl
                // http://pages.cs.wisc.edu/~lizy/mrdoob-three.js-ef5f05d/examples/webgl_loader_obj_mtl.html


                o.scale = new THREE.Vector3(40, 40, 40);

                o.position.y = -80;
                scene.add(o);
                oo.Add(o);
            }
                    ),
                new Action <object>(
                    o =>
            {
                Console.WriteLine("progress " + new { o });
            }
                    ),

                new Action <object>(
                    o =>
            {
                Console.WriteLine("error " + new { o });
            }
                    )
                );
        }
Example #18
0
        // Could not connect to the feed specified at 'http://my.jsc-solutions.net/nuget'. P


        public Application(IApp page)
        {
            //{ var ref0 = typeof(dirt_tx); }
            { var ref0 = new dirt_tx {
              }; }
            //{ var ref0 = typeof(MarineCv2_color); }
            { var ref0 = new MarineCv2_color {
              }; }

            // http://www.realitymeltdown.com/WebGL3/character-controller.html

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150127
            //Native.css
            Native.body.style.margin   = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            //Error CS0246  The type or namespace name 'THREE' could not be found(are you missing a using directive or an assembly reference?)	WebGLSpeedBlendCharacter Application.cs  46
            // used by, for?
            var clock = new THREE.Clock();
            //var keys = new { LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, A = 65, S = 83, D = 68, W = 87 };


            var scene    = new THREE.Scene();
            var skyScene = new THREE.Scene();

            scene.fog = new THREE.Fog(0xB0CAE1, 1000, 20000);
            scene.add(new THREE.AmbientLight(0xaaaaaa));

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            var light = new THREE.DirectionalLight(0xffffff, 1.5);

            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;

            xlight.shadowMapWidth      = 4096;
            xlight.shadowMapHeight     = 2048;
            xlight.shadowDarkness      = 0.5;
            xlight.shadowCameraNear    = 10;
            xlight.shadowCameraFar     = 10000;
            xlight.shadowBias          = 0.00001;
            xlight.shadowCameraRight   = 4000;
            xlight.shadowCameraLeft    = -4000;
            xlight.shadowCameraTop     = 4000;
            xlight.shadowCameraBottom  = -4000;
            xlight.shadowCameraVisible = true;

            scene.add(light);

            #region renderer
            var renderer = new THREE.WebGLRenderer(new { antialias = true, alpha = false });
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.autoClear        = false;
            renderer.shadowMapEnabled = true;
            renderer.shadowMapType    = THREE.PCFSoftShadowMap;

            renderer.domElement.AttachToDocument();
            #endregion



            // this will mess up
            // three.OrbitControls.js
            // onMouseMove

            //new IStyle(renderer.domElement)
            //{
            //    position = IStyle.PositionEnum.absolute,
            //    left = "0px",
            //    top = "0px",
            //    right = "0px",
            //    bottom = "0px",
            //};


            //new { }.With(
            //    async delegate
            //    {

            //        await Native.window.async.onresize;

            //        // if the reload were fast, then we could actually do that:D
            //        Native.document.location.reload();

            //    }
            //);



            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            //var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            //var planeMaterial = new THREE.MeshLambertMaterial(
            //    new
            //    {
            //        map = THREE.ImageUtils.loadTexture(new HTML.Images.FromAssets.dirt_tx().src),
            //        color = 0xffffff
            //    }
            //);

            //planeMaterial.map.repeat.x = 300;
            //planeMaterial.map.repeat.y = 300;
            //planeMaterial.map.wrapS = THREE.RepeatWrapping;
            //planeMaterial.map.wrapT = THREE.RepeatWrapping;
            //var plane = new THREE.Mesh(planeGeometry, planeMaterial);
            //plane.castShadow = false;
            //plane.receiveShadow = true;


            //{

            //    var parent = new THREE.Object3D();
            //    parent.add(plane);
            //    parent.rotation.x = -Math.PI / 2;
            //    parent.scale.set(100, 100, 100);

            //    scene.add(parent);
            //}

            var random    = new Random();
            var meshArray = new List <THREE.Mesh>();
            //var geometry = new THREE.CubeGeometry(1, 1, 1);
            var geometry = new THREE.BoxGeometry(1, 1, 1);

            for (var i = 1; i < 100; i++)
            {
                var ii = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial(
                                            new
                {
                    color = (Convert.ToInt32(0xffffff * random.NextDouble()))
                }));
                ii.position.x = i % 2 * 500 - 2.5f;

                // raise it up
                ii.position.y    = .5f * 100;
                ii.position.z    = -1 * i * 400;
                ii.castShadow    = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);
            }
            #endregion



            var blendMesh = new THREE.SpeedBlendCharacter();


            blendMesh.load(
                new Models.marine_anims().Content.src,
                new Action(
                    delegate
            {
                // buildScene

                //blendMesh.rotation.y = Math.PI * -135 / 180;
                blendMesh.castShadow = true;
                // we cannot scale down we want our shadows
                //blendMesh.scale.set(0.1, 0.1, 0.1);

                scene.add(blendMesh);

                //var characterController = new THREE.CharacterController(blendMesh);

                // run
                blendMesh.setSpeed(1.0);

                var radius = blendMesh.geometry.boundingSphere.radius;


                Native.document.title = new { radius }.ToString();


                var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                camera.position.set(0.0, radius * 3, radius * 3.5);

                var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                skyCamera.position.set(0.0, radius * 3, radius * 3.5);

                var controls = new THREE.OrbitControls(camera);
                //controls.noPan = true;


                var loader = new THREE.JSONLoader();
                loader.load(new Models.ground().Content.src,
                            new Action <THREE.Geometry, THREE.Material[]>(

                                (xgeometry, materials) =>
                {
                    // cannot see the ground?
                    var ground = new THREE.Mesh(xgeometry, materials[0]);
                    ground.scale.set(20, 20, 20);
                    ground.receiveShadow = true;
                    ground.castShadow    = true;
                    scene.add(ground);
                }
                                )
                            );

                #region  createSky
                // gearvr has photos360 app
                var urls = new[] {
                    new px().src, new nx().src,
                    new py().src, new ny().src,
                    new pz().src, new nz().src,
                };

                var textureCube = THREE.ImageUtils.loadTextureCube(urls);

                dynamic shader = THREE.ShaderLib["cube"];
                shader.uniforms["tCube"].value = textureCube;

                // We're inside the box, so make sure to render the backsides
                // It will typically be rendered first in the scene and without depth so anything else will be drawn in front
                var material = new THREE.ShaderMaterial(new
                {
                    fragmentShader = shader.fragmentShader,
                    vertexShader   = shader.vertexShader,
                    uniforms       = shader.uniforms,
                    depthWrite     = false,
                    side           = THREE.BackSide
                });

                // THREE.CubeGeometry has been renamed to THREE.BoxGeometry
                // The box dimension size doesn't matter that much when the camera is in the center.  Experiment with the values.
                //var skyMesh = new THREE.Mesh(new THREE.CubeGeometry(10000, 10000, 10000, 1, 1, 1), material);
                var skyMesh = new THREE.Mesh(new THREE.BoxGeometry(10000, 10000, 10000), material);
                //skyMesh.renderDepth = -10;


                skyScene.add(skyMesh);
                #endregion

                #region onframe
                Native.window.onframe +=
                    delegate
                {
                    var scale    = 1.0;
                    var delta    = clock.getDelta();
                    var stepSize = delta * scale;

                    if (stepSize > 0)
                    {
                        //characterController.update(stepSize, scale);
                        //gui.setSpeed(blendMesh.speed);

                        THREE.AnimationHandler.update(stepSize);
                        blendMesh.updateSkeletonHelper();
                    }

                    controls.center.copy(blendMesh.position);
                    controls.center.y += radius * 2.0;
                    controls.update();

                    var camOffset = camera.position.clone().sub(controls.center);
                    camOffset.normalize().multiplyScalar(750);
                    camera.position = controls.center.clone().add(camOffset);

                    skyCamera.rotation.copy(camera.rotation);



                    renderer.clear();
                    renderer.render(skyScene, skyCamera);
                    renderer.render(scene, camera);
                };
                #endregion


                #region onresize
                new { }.With(
                    async delegate
                {
                    do
                    {
                        camera.aspect = Native.window.aspect;
                        camera.updateProjectionMatrix();
                        renderer.setSize(Native.window.Width, Native.window.Height);
                    } while (await Native.window.async.onresize);
                }
                    );
                #endregion
            }
                    )
                );
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150824

            // http://stackoverflow.com/questions/14103986/canvas-and-spritematerial

            // X:\jsc.svn\examples\javascript\WebGL\WebGLSVGAnonymous\WebGLSVGAnonymous\Application.cs
            // X:\jsc.svn\examples\javascript\WebGL\WebGLVRCreativeLeadership\WebGLVRCreativeLeadership\Application.cs
            // X:\jsc.svn\examples\javascript\WebGL\WebGLSVGSprite\WebGLSVGSprite\Application.cs

            //var l = new NotificationLayout().layout;

            //l.AttachToDocument();

            // : INodeConvertible<IHTMLElement>
            //var c = (IHTMLCanvas)l.layout;
            //var c = (IHTMLCanvas)l;

            // look we have a databound 2D image!

            // make it implicit operator for assetslibrary?

            //l.style



            //c.AttachToDocument();



            // https://play.google.com/store/apps/details?id=com.abstractatech.vr
            // could we display LAN UDP notifications too. like
            // which youtube video is playing?

            Native.body.Clear();
            Native.body.style.margin = "0px";
            Native.body.style.backgroundColor = "black";

            // https://vronecontest.zeiss.com/index.php?controller=ideas&view=show&id=652

            //          hResolution: 1920,
            //vResolution: 1080,

            // "X:\jsc.svn\examples\javascript\synergy\webgl\WebGLEquirectangularPanorama\WebGLEquirectangularPanorama.sln"

            // http://oculusstreetview.eu.pn/?lat=44.301987&lng=9.211561999999958&q=3&s=false&heading=0
            // https://github.com/troffmo5/OculusStreetView

            // http://stackoverflow.com/questions/23817633/threejs-using-a-sprite-with-the-oculusrifteffect
            // http://laht.info/dk2-parameters-for-three-oculusrifteffect-js/

            // http://stemkoski.github.io/Three.js/Sprites.html
            // http://stemkoski.github.io/Three.js/Texture-Animation.html
            // http://blog.thematicmapping.org/2013/10/terrain-visualization-with-threejs-and.html

            // http://mrdoob.github.io/three.js/examples/webgl_panorama_equirectangular.html

            var window = Native.window;

            var fov = 70.0;

            var camera = new THREE.PerspectiveCamera(fov,
                1920.0 / 1080.0,
                //window.aspect,
                1, 1100);
            var target = new THREE.Vector3(0, 0, 0);

            //(camera as dynamic).target = target;

            var scene = new THREE.Scene();
            //scene.add(new THREE.AmbientLight(0xffffff));
            //scene.add(new THREE.AmbientLight(0xafafaf));

            // http://www.html5canvastutorials.com/three/html5-canvas-webgl-ambient-lighting-with-three-js/

            // http://stackoverflow.com/questions/14717135/three-js-ambient-light-unexpected-effect

            scene.add(new THREE.AmbientLight(0x2f2f2f));


            //var light = new THREE.DirectionalLight(0xffffff, 1.0);
            #region light
            var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            //var lightOffset = new THREE.Vector3(0, 1000, 2500.0);
            var lightOffset = new THREE.Vector3(
                2000,
                700,

                // lower makes longer shadows 
                700.0
                );
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;

            xlight.shadowCameraVisible = true;

            scene.add(light);
            #endregion

            var mesh = new THREE.Mesh(new THREE.SphereGeometry(500, 60, 40),
                new THREE.MeshBasicMaterial(new
                {
                    map = THREE.ImageUtils.loadTexture(
                        new _2294472375_24a3b8ef46_o().src
                        //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20130616_222058().src
                        //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20121225_210448().src

                        )
                }));
            mesh.scale.x = -1;
            scene.add(mesh);

            var labove = new NotificationLayout();

            #region sprite2 above
            {
                labove.Message.innerText = "VR CREATIVE LEADERSHIP";
                labove.layout.style.background = "";

                new { }.With(
                    async delegate
                    {
                        retry:

                        // make it blink. gaze cursor is on it?


                        labove.box.style.background = "rgba(255,255,0,0.7)";
                        labove.box.setAttribute("invoke", "onmutation1");
                        await Task.Delay(1500);

                        // is mutation observer noticing it?
                        labove.box.style.background = "rgba(255,255,255,0.7)";
                        labove.box.setAttribute("invoke", "onmutation2");
                        await Task.Delay(1500);


                        goto retry;
                    }
                );



                var c = labove.AsCanvas();

                var xcrateTexture = new THREE.Texture(c);

                // like video texture
                Native.window.onframe += delegate { xcrateTexture.needsUpdate = true; };

                var xcrateMaterial = new THREE.SpriteMaterial(
                    new
                    {
                        map = xcrateTexture,
                        useScreenCoordinates = false,
                        //color = 0xff0000
                        color = 0xffffff
                    }
            );



                var xsprite2 = new THREE.Sprite(xcrateMaterial);

                //floor
                //sprite2.position.set(0, -200, 0);

                // left
                xsprite2.position.set(200, 0, 0);

                //sprite2.position.set(0, 0, 200);

                //sprite2.position.set(-100, 0, 0);
                xsprite2.scale.set(
                   c.width * 0.5,
                   c.height * 0.5,
                    //64, 64,
                    1.0); // imageWidth, imageHeight
                scene.add(xsprite2);
            }
            #endregion




            //var lineTo = new List<THREE.Vector3>();
            var others = new
            {
                ui = default(NotificationLayout),
                canvas = default(IHTMLCanvas),

                map = default(THREE.Texture),

                sprite = default(THREE.Sprite)

            }.ToEmptyList();

            #region add
            Action<NotificationLayout> add = ui =>
            {
                ui.layout.style.background = "";

                var canvas = ui.AsCanvas();
                var index = others.Count;

                //ui.Message  += new { index };
                //ui.Message.innerText += new { index };

                //lbelow0.Message = new { THREE.REVISION }.ToString();

                // THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( undefined )

                var map = new THREE.Texture(canvas);

                map.minFilter = THREE.LinearFilter;

                // like video texture

                var xcrateMaterial = new THREE.SpriteMaterial(
                    new
                    {
                        map,
                        useScreenCoordinates = false,
                        //color = 0xff0000
                        color = 0xffffff
                    }
                );



                var sprite = new THREE.Sprite(xcrateMaterial);

                //floor
                //sprite2.position.set(0, -200, 0);

                // left middle
                //sprite2.position.set(200, 0, 0);
                //sprite.position.set(250, -50, 50);
                //lineTo.Add(sprite.position);




                //sprite2.position.set(0, 0, 200);

                //sprite2.position.set(-100, 0, 0);
                sprite.scale.set(
                   canvas.width * 0.5,
                   canvas.height * 0.5,
                    //64, 64,
                    1.0); // imageWidth, imageHeight
                scene.add(sprite);

                others.Add(
                    new
                    {
                        ui,
                        canvas,
                        map,
                        sprite
                    }
                );

                var sw = Stopwatch.StartNew();

                Native.window.onframe += delegate
                {
                    // can we get some of the crazy c++ template bitmapbuffer code from the past?
                    map.needsUpdate = true;

                    var offset = Math.PI * 2 * ((double)(index + 1) / others.Count);

                    sprite.position.x = 300;

                    sprite.position.z = Math.Sin(sw.ElapsedMilliseconds * 0.00001 + offset) * 120;
                    sprite.position.y = Math.Cos(sw.ElapsedMilliseconds * 0.00001 + offset) * 120;
                };

            };
            #endregion


            add(
                new NotificationLayout
                {
                    // keep attributes around?
                    // like we do with XElement sync?
                    Icon = new HTML.Images.FromAssets._0_10122014_ECAF4B1F638429B44F4B142C2A4F38EE().With(
                        x =>
                        {
                            x.style.width = "96px";
                            x.style.height = "96px";
                        }
                    ),
                    Message = "Advanced Mechanics by Portugal Design Lab"
                }
              );

            add(
                   new NotificationLayout
                   {
                       // keep attributes around?
                       // like we do with XElement sync?
                       Icon = new HTML.Images.FromAssets._42_08122014_D2639E0AAA3E54E5F4568760AEE605EE().With(
                           x =>
                           {
                               x.style.width = "96px";
                               x.style.height = "96px";
                           }
                       ),
                       Message = "Face Value by mshariful"
                   }
                 );



            add(
                   new NotificationLayout
                   {
                       // keep attributes around?
                       // like we do with XElement sync?
                       Icon = new HTML.Images.FromAssets._371_28122014_2045510F2F7974319A9F7E9F4B39DF07().With(
                           x =>
                           {
                               x.style.width = "96px";
                               x.style.height = "96px";
                           }
                       ),
                       Message = "Mind Wall. by Sumit Goski"
                   }
                 );


            #region lines
            {
                var geometry = new THREE.Geometry
                {
                    // how can we keep streaming verticies data points to gpu?
                    vertices =

                        others.SelectMany(
                            lineTo =>
                                new[]
                                {
                                    new THREE.Vector3(200, 0, 0),
                                    lineTo.sprite.position
                                }
                        ).ToArray()

                    // https://github.com/mrdoob/three.js/wiki/Updates
                    // http://stackoverflow.com/questions/17842521/adding-geometry-to-a-three-js-mesh-after-render
                    //verticesNeedUpdate = true
                };

                Native.window.onframe += delegate { geometry.verticesNeedUpdate = true; };

                var o = new THREE.Line(geometry, new THREE.LineDashedMaterial(
                    new { color = 0x00aaff, dashSize = 1, gapSize = 0.5, linewidth = 1 }
                    ), THREE.LineStrip);

                //objects.Add(o);
                scene.add(o);
            }
            #endregion


            //          // DK2
            //          hResolution: 1920,
            //vResolution: 1080,

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(1920, 1080);

            #region HMD
            // broken?
            var distortionK = new double[] { 1.0, 0.22, 0.24, 0.0 };
            var chromaAbParameter = new double[] { 0.996, -0.004, 1.014, 0.0 };

            var HMD = new OculusRiftEffectOptions
            {
                hResolution = window.Width,
                vResolution = window.Height,

                hScreenSize = 0.12576,
                vScreenSize = 0.07074,
                interpupillaryDistance = 0.0635,
                lensSeparationDistance = 0.0635,
                eyeToScreenDistance = 0.041,

                //  j.distortionK = [0, 1.875, -71.68, 1.595, -3.218644E+26, 1.615, 0, 0];
                //distortionK = new double[] { 1.0, 0.22, 0.24, 0.0 },
                distortionK = distortionK,

                // j.chromaAbParameter = [1.609382E+22, 1.874, -5.189695E+11, -0.939, 4.463059E-29, 1.87675, 0, 0];
                //chromaAbParameter = new double[] { 0.996, -0.004, 1.014, 0.0 }
                chromaAbParameter = chromaAbParameter

            };
            #endregion


            //var effect = new THREE.OculusRiftEffect(
            //    renderer, new
            //    {
            //        worldScale = 100,

            //        //HMD
            //    }
            //    );

            //effect.setSize(1920, 1080);


            renderer.domElement.AttachToDocument();

            //renderer.domElement.style.position = IStyle.PositionEnum.absolute;
            renderer.domElement.style.SetLocation(0, 0);

            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;

            // x:\jsc.svn\examples\javascript\synergy\comanchebysiorki\comanchebysiorki\application.cs

            new { }.With(
                     async delegate
                     {
                         retry:

                         var s = (double)Native.window.Width / 1920.0;


                         Native.document.body.style.transform = "scale(" + s + ")";
                         Native.document.body.style.transformOrigin = "0% 0%";

                         await Native.window.async.onresize;
                         goto retry;
                     }
                   );

            //#region onresize
            //Native.window.onresize +=
            //    delegate
            //    {
            //        camera.aspect = Native.window.aspect;
            //        camera.updateProjectionMatrix();

            //        renderer.setSize(window.Width, window.Height);
            //        effect.setSize(window.Width, window.Height);
            //    };
            //#endregion


            //Native.document.body.onmousewheel +=
            //    e =>
            //    {
            //        fov -= e.WheelDirection * 5.0;
            //        camera.projectionMatrix.makePerspective(fov,
            //            (double)window.Width / window.Height, 1, 1100);
            //    };

            var lon0 = -45.0;
            var lon1 = 0.0;

            var lon = new sum(
                 () => lon0,
                 () => lon1
             );

            var lat0 = 0.0;
            var lat1 = 0.0;

            // or could we do it with byref or pointers?
            var lat = new sum(
                () => lat0,
                () => lat1
            );

            var phi = 0.0;
            var theta = 0.0;

            //var controls = new THREE.OrbitControls(camera);

            var camera_rotation_z = 0.0;

            //Native.document.onmousemove +=
            //  e =>
            //  {

            //      l.Message = new { e.CursorX, e.CursorY }.ToString();
            //  };


            Native.window.onframe +=
                        ee =>
                        {
                            //labove.Message = new
                            //{
                            //    lon,
                            //    lat,
                            //    ee.counter
                            //}.ToString();

                            //if (Native.document.pointerLockElement == Native.document.body)
                            //    lon += 0.00;
                            //else
                            //    lon += 0.01;

                            //lat = Math.Max(-85, Math.Min(85, lat));

                            //Native.document.title = new { lon, lat }.ToString();


                            phi = THREE.Math.degToRad(90 - lat);
                            theta = THREE.Math.degToRad(lon);

                            target.x = 500 * Math.Sin(phi) * Math.Cos(theta);
                            target.y = 500 * Math.Cos(phi);
                            target.z = 500 * Math.Sin(phi) * Math.Sin(theta);


                            //controls.update();
                            //camera.position = controls.center.clone();


                            camera.lookAt(target);
                            camera.rotation.z += camera_rotation_z;

                            renderer.render(scene, camera);

                            //effect.render(scene, camera);
                        };



            // http://blog.thematicmapping.org/2013/10/terrain-visualization-with-threejs-and.html

            // http://stackoverflow.com/questions/13278087/determine-vertical-direction-of-a-touchmove



            var compassHeadingOffset = 0.0;
            var compassHeadingInitialized = 0;

            #region compassHeading
            // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeading\TestCompassHeading\Application.cs
            Native.window.ondeviceorientation +=
                          dataValues =>
                          {
                              // Convert degrees to radians
                              var alphaRad = dataValues.alpha * (Math.PI / 180);
                              var betaRad = dataValues.beta * (Math.PI / 180);
                              var gammaRad = dataValues.gamma * (Math.PI / 180);

                              // Calculate equation components
                              var cA = Math.Cos(alphaRad);
                              var sA = Math.Sin(alphaRad);
                              var cB = Math.Cos(betaRad);
                              var sB = Math.Sin(betaRad);
                              var cG = Math.Cos(gammaRad);
                              var sG = Math.Sin(gammaRad);

                              // Calculate A, B, C rotation components
                              var rA = -cA * sG - sA * sB * cG;
                              var rB = -sA * sG + cA * sB * cG;
                              var rC = -cB * cG;

                              // Calculate compass heading
                              var compassHeading = Math.Atan(rA / rB);

                              // Convert from half unit circle to whole unit circle
                              if (rB < 0)
                              {
                                  compassHeading += Math.PI;
                              }
                              else if (rA < 0)
                              {
                                  compassHeading += 2 * Math.PI;
                              }

                              /*
                              Alternative calculation (replacing lines 99-107 above):

                                var compassHeading = Math.atan2(rA, rB);

                                if(rA < 0) {
                                  compassHeading += 2 * Math.PI;
                                }
                              */

                              // Convert radians to degrees
                              compassHeading *= 180 / Math.PI;

                              // Compass heading can only be derived if returned values are 'absolute'

                              // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeadingWithReset\TestCompassHeadingWithReset\Application.cs

                              //Native.document.body.innerText = new { compassHeading }.ToString();
                              if (compassHeadingInitialized > 0)
                              {
                                  lon1 = compassHeading - compassHeadingOffset;
                              }
                              else
                              {
                                  compassHeadingOffset = compassHeading;
                                  compassHeadingInitialized++;
                              }

                          };
            #endregion

            #region gamma
            Native.window.ondeviceorientation +=
                //e => Native.body.innerText = new { e.alpha, e.beta, e.gamma }.ToString();
                //e => lon = e.gamma;
                e =>
                {
                    lat1 = e.gamma;

                    // after servicing a running instance would be nice
                    // either by patching or just re running the whole iteration in the backgrou
                    camera_rotation_z = e.beta * 0.02;
                };
            #endregion



            #region camera rotation
            var old = new { clientX = 0, clientY = 0 };

            Native.document.body.ontouchstart +=
                            e =>
                            {
                                var n = new { e.touches[0].clientX, e.touches[0].clientY };
                                old = n;
                            };

            Native.document.body.ontouchmove +=
                    e =>
                    {
                        var n = new { e.touches[0].clientX, e.touches[0].clientY };

                        e.preventDefault();

                        lon0 += (n.clientX - old.clientX) * 0.2;
                        lat0 -= (n.clientY - old.clientY) * 0.2;

                        old = n;
                    };


            Native.document.body.onmousemove +=
                e =>
                {
                    e.preventDefault();

                    if (Native.document.pointerLockElement == Native.document.body)
                    {
                        lon0 += e.movementX * 0.1;
                        lat0 -= e.movementY * 0.1;

                        //Console.WriteLine(new { lon, lat, e.movementX, e.movementY });
                    }
                };


            Native.document.body.onmouseup +=
              e =>
              {
                  //drag = false;
                  e.preventDefault();
              };

            Native.document.body.onmousedown +=
                e =>
                {
                    //e.CaptureMouse();

                    //drag = true;
                    e.preventDefault();
                    Native.document.body.requestPointerLock();

                };


            Native.document.body.ondblclick +=
                e =>
                {
                    e.preventDefault();

                    Console.WriteLine("requestPointerLock");
                };

            #endregion

            Native.body.onmousewheel +=
                e =>
                {

                    camera_rotation_z += 0.1 * e.WheelDirection; ;

                };
            // https://developer.android.com/training/system-ui/immersive.html




            //var ze = new ZeProperties();

            //ze.Show();
            //ze.treeView1.Nodes.Clear();

            //ze.Add(() => renderer);
            ////ze.Add(() => controls);
            //ze.Add(() => scene);
            //ze.Left = 0;
        }
        /* Source: http://www.webspaceinvader.com/2011/09/21/first-try-at-webgl/
         */


        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            var SCREEN_WIDTH = Native.window.Width;
            var SCREEN_HEIGHT = Native.window.Height;

            //var ,stats;


            //var mesh, zmesh, geometry;

            var mouseX = 0;
            var mouseY = 0;

            var windowHalfX = SCREEN_WIDTH / 2;
            var windowHalfY = SCREEN_HEIGHT / 2;
            var lastUpdate = new IDate().getTime();




            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

            var camera = new THREE.PerspectiveCamera(75, Native.window.aspect, 1, 100000);
            camera.position.z = 50;
            camera.updateMatrix();

            var scene = new THREE.Scene();

            // LIGHTS

            var ambient = new THREE.AmbientLight(0x222222);
            ambient.position.z = -300;
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(-1, 0, 1);
            directionalLight.position.normalize();
            scene.add(directionalLight);

            var dLight = new THREE.DirectionalLight(0xffeedd);
            dLight.position.set(1, 0, 1);
            dLight.position.normalize();
            scene.add(dLight);

            // init the WebGL renderer and append it to the Dom
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
            renderer.autoClear = false;

            renderer.domElement.AttachTo(container);

            #region createScene
            Action<object, f, f, f, f> createScene = (geometry, x, y, z, b) =>
            {
                
                //var zmesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
                var zmesh = new THREE.Mesh(geometry);
                zmesh.position.x = x;
                zmesh.position.z = y;
                zmesh.position.y = z;
                zmesh.scale.x = 5f;
                zmesh.scale.y = 5f;
                zmesh.scale.z = 5f;
                //zmesh.overdraw = true;
                zmesh.updateMatrix();
                scene.add(zmesh);
            };
            #endregion

            // message: "Unexpected token /"
            var loader = new THREE.JSONLoader();

            Action<object> callbackMale = (geometry) => { createScene(geometry, 90, 50, 0, 105); };

            loader.load(
                    url: new invade().Content.src,
                    callback: IFunction.OfDelegate(callbackMale)
            );

            // postprocessing



            var composer = new THREE.EffectComposer(renderer);

            var renderModel = new THREE.RenderPass(scene, camera);
            composer.addPass(renderModel);


            var effectFilm = new THREE.FilmPass(0.35, 0.50, 2048, false); //( 0.35, 0.75, 2048, false );
            effectFilm.renderToScreen = true;
            composer.addPass(effectFilm);

            #region IsDisposed
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;

                renderer.domElement.Orphanize();
            };
            #endregion


            #region getFrametime
            Func<long> getFrametime = () =>
            {

                var now = new IDate().getTime();
                var tdiff = (now - lastUpdate) / 1000;
                lastUpdate = now;
                return tdiff;
            };
            #endregion

            #region render
            Action render = delegate
            {
                var delta = getFrametime();
                camera.position.x += (mouseX - camera.position.x) * .05f;
                camera.position.y += (-mouseY - camera.position.y) * .05f;
                camera.updateMatrix();

                //renderer.render( scene, camera );
                renderer.clear();
                composer.render(delta);
            };
            #endregion

            #region onmousemove
            Native.document.onmousemove +=
                e =>
                {
                    mouseX = (e.CursorX - windowHalfX);
                    mouseY = (e.CursorY - windowHalfY);
                };
            #endregion

            Native.window.onframe +=
            delegate
            {
                if (IsDisposed)
                    return;

                render();

            };


            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                camera.aspect = Native.window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(Native.window.Width, Native.window.Height);
            };

            Native.window.onresize +=
                delegate
                {
                    AtResize();
                };

            AtResize();
            #endregion

            #region requestFullscreen
            Native.document.body.ondblclick +=
                delegate
                {
                    if (IsDisposed)
                        return;

                    // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                    Native.document.body.requestFullscreen();


                };
            #endregion

        }
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809/chrome360hz

        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809/chromeequirectangularcameraexperiment

        // "x:\util\android-sdk-windows\platform-tools\adb.exe" install -r "r:\jsc.svn\examples\javascript\WebGL\WebGLVRHZTeaser\WebGLVRHZTeaser\bin\Debug\staging\WebGLVRHZTeaser.ApplicationWebService\staging.apk\staging\apk\bin\WebGLVRHZTeaser.Activities-release.apk"

        //I/Web Console(25108): 0ms NewInstanceConstructor restore fields.. at http://10.144.157.179:23222/view-source:50800
        //I/Web Console(25108): THREE.WebGLRenderer at http://10.144.157.179:23222/view-source:90370
        //E/Web Console(25108): Error creating WebGL context. at http://10.144.157.179:23222/view-source:90581
        //E/Web Console(25108): Uncaught TypeError: Cannot read property 'getShaderPrecisionFormat' of null at http://10.144.157.179:23222/view-source:90585

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
		{

#if false
			#region += Launched chrome.app.window
			// X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
			dynamic self = Native.self;
			dynamic self_chrome = self.chrome;
			object self_chrome_socket = self_chrome.socket;

			if (self_chrome_socket != null)
			{

				chrome.Notification.DefaultTitle = "HZ";
				chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Preview().src;

				ChromeTCPServer.TheServerWithAppWindow.Invoke(AppSource.Text);

				return;
			}
			#endregion
#endif

			// https://code.google.com/p/chromium/issues/detail?id=483890

			Native.document.body.style.margin = "0px";
			Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
			Native.body.style.backgroundColor = "black";
			Native.document.body.Clear();

			// what dto do if webgl not supported?


			double SCREEN_WIDTH = Native.window.Width;
			double SCREEN_HEIGHT = Native.window.Height;

			#region scene
			var scene = new THREE.Scene();
			var clock = new THREE.Clock();

			var sceneRenderTarget = new THREE.Scene();
			var cameraOrtho = new THREE.OrthographicCamera(
				(int)SCREEN_WIDTH / -2,
				(int)SCREEN_WIDTH / 2,
				(int)SCREEN_HEIGHT / 2,
				(int)SCREEN_HEIGHT / -2,
				-100000,
				100000
			);

			cameraOrtho.position.z = 100;
			sceneRenderTarget.add(cameraOrtho);



			var camera = new THREE.PerspectiveCamera(

				//40,
				20,
				//10,

				Native.window.aspect, 2,

				// how far out do we want to zoom?
				200000
				//9000
				);
			camera.position.set(-1200, 800, 1200);
			var target = new THREE.Vector3(0, 0, 0);

			scene.add(camera);
			//scene.add(new THREE.AmbientLight(0x212121));

			//var spotLight = new THREE.SpotLight(0xffffff, 1.15);
			//spotLight.position.set(500, 2000, 0);
			//spotLight.castShadow = true;
			//scene.add(spotLight);

			//var pointLight = new THREE.PointLight(0xff4400, 1.5);
			//pointLight.position.set(0, 0, 0);
			//scene.add(pointLight);


			//scene.add(new THREE.AmbientLight(0xaaaaaa));
			scene.add(new THREE.AmbientLight(0x101030));
			#endregion


			#region light
			//var light = new THREE.DirectionalLight(0xffffff, 1.0);
			var light = new THREE.DirectionalLight(0xffffff, 2.5);
			//var light = new THREE.DirectionalLight(0xffffff, 2.5);
			//var light = new THREE.DirectionalLight(0xffffff, 1.5);
			//var lightOffset = new THREE.Vector3(0, 1000, 2500.0);
			var lightOffset = new THREE.Vector3(
				2000,
				700,

				// lower makes longer shadows 
				700.0
				);
			light.position.copy(lightOffset);
			light.castShadow = true;

			var xlight = light as dynamic;
			xlight.shadowMapWidth = 4096;
			xlight.shadowMapHeight = 2048;

			xlight.shadowDarkness = 0.1;
			//xlight.shadowDarkness = 0.5;

			xlight.shadowCameraNear = 10;
			xlight.shadowCameraFar = 10000;
			xlight.shadowBias = 0.00001;
			xlight.shadowCameraRight = 4000;
			xlight.shadowCameraLeft = -4000;
			xlight.shadowCameraTop = 4000;
			xlight.shadowCameraBottom = -4000;

			xlight.shadowCameraVisible = true;

			scene.add(light);
			#endregion



			var renderer = new THREE.WebGLRenderer(
				new
				{

					// http://stackoverflow.com/questions/20495302/transparent-background-with-three-js
					alpha = true,
					preserveDrawingBuffer = true,
					antialias = true
				}

				);
			renderer.setSize(1920, 1080);
			//renderer.setSize(2560, 1440);
			renderer.domElement.AttachToDocument();
			renderer.shadowMapEnabled = true;
			renderer.shadowMapType = THREE.PCFSoftShadowMap;



			var renderTarget = new THREE.WebGLRenderTarget(
				   Native.window.Width, Native.window.Height,
				   new
				   {
					   minFilter = THREE.LinearFilter,
					   magFilter = THREE.LinearFilter,
					   format = THREE.RGBAFormat,
					   stencilBufer = false
				   }
			   );

			//var composer = new THREE.EffectComposer(renderer, renderTarget);
			//var renderModel = new THREE.RenderPass(scene, camera);
			//composer.addPass(renderModel);

			//#region vblur
			//var hblur = new THREE.ShaderPass(THREE.HorizontalTiltShiftShader);
			//var vblur = new THREE.ShaderPass(THREE.VerticalTiltShiftShader);

			////var bluriness = 6.0;
			//var bluriness = 4.0;

			//// Show Details	Severity	Code	Description	Project	File	Line
			////Error CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' WebGLTiltShift Application.cs  183

			//(hblur.uniforms as dynamic).h.value = bluriness / Native.window.Width;
			//(vblur.uniforms as dynamic).v.value = bluriness / Native.window.Height;

			//(hblur.uniforms as dynamic).r.value = 0.5;
			//(vblur.uniforms as dynamic).r.value = 0.5;
			////vblur.renderToScreen = true;

			//composer.addPass(hblur);
			//composer.addPass(vblur);
			//#endregion

			// Uncaught TypeError: renderer.setSize is not a function
			// Uncaught TypeError: renderer.getClearColor is not a function

			var effect = new THREE.OculusRiftEffect(
				renderer,

				// how to get the vblur into oculus effect?

				//renderModel,
				//composer,
				//renderTarget,
				new
				{
					worldScale = 100,

					//HMD
				}
				);

			effect.setSize(1920, 1080);
            //effect.setSize(2560, 1440);

            #region WebGLRah66Comanche
            // why isnt it being found?
            // "Z:\jsc.svn\examples\javascript\WebGL\collada\WebGLRah66Comanche\WebGLRah66Comanche\WebGLRah66Comanche.csproj"
            new global::WebGLRah66Comanche.Comanche(
			).Source.Task.ContinueWithResult(
				dae =>
				{

					//dae.position.y = -40;
					//dae.position.z = 280;
					scene.add(dae);
					//oo.Add(dae);

					// wont do it
					//dae.castShadow = true;

					dae.children[0].children[0].children.WithEach(x => x.castShadow = true);


					// the rotors?
					dae.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


					dae.scale.set(0.5, 0.5, 0.5);
					dae.position.x = -900;
					dae.position.z = +900;

					// raise it up
					dae.position.y = 400;

					//var sw = Stopwatch.StartNew();

					//Native.window.onframe += delegate
					//{
					//    //dae.children[0].children[0].children.Last().al
					//    //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
					//    //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
					//    dae.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.01;
					//};
				}
			);
			#endregion



			#region tree
			// X:\jsc.svn\examples\javascript\WebGL\WebGLGodRay\WebGLGodRay\Application.cs

			var materialScene = new THREE.MeshBasicMaterial(new { color = 0x000000, shading = THREE.FlatShading });
			var tloader = new THREE.JSONLoader();

			// http://stackoverflow.com/questions/16539736/do-not-use-system-runtime-compilerservices-dynamicattribute-use-the-dynamic
			// https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.dynamicattribute%28v=vs.110%29.aspx
			//System.Runtime.CompilerServices.DynamicAttribute

			tloader.load(

				new WebGLGodRay.Models.tree().Content.src,

				new Action<THREE.Geometry>(
				xgeometry =>
				{

					var treeMesh = new THREE.Mesh(xgeometry, materialScene);
					treeMesh.position.set(0, -150, -150);
					treeMesh.position.x = -900;
					treeMesh.position.z = -900;

					treeMesh.position.y = 25;

					var tsc = 400;
					treeMesh.scale.set(tsc, tsc, tsc);

					treeMesh.matrixAutoUpdate = false;
					treeMesh.updateMatrix();


					treeMesh.AttachTo(scene);

				}
				)
				);
			#endregion

			#region create field

			// THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.

			// could we get some film grain?
			var planeGeometry = new THREE.CubeGeometry(512, 512, 1);
			var plane = new THREE.Mesh(planeGeometry,
					new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

				);
			//plane.castShadow = false;
			plane.receiveShadow = true;


			{

				var parent = new THREE.Object3D();
				parent.add(plane);
				parent.rotation.x = -Math.PI / 2;
				parent.scale.set(10, 10, 10);

				scene.add(parent);
			}

			var random = new Random();
			var meshArray = new List<THREE.Mesh>();
			var geometry = new THREE.CubeGeometry(1, 1, 1);
			var sw = Stopwatch.StartNew();

			for (var i = 3; i < 9; i++)
			{

				//THREE.MeshPhongMaterial
				var ii = new THREE.Mesh(geometry,


					new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

					//new THREE.MeshLambertMaterial(
					//new
					//{
					//    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
					//    specular = 0xffaaaa,
					//    ambient= 0x050505, 
					//})

					);
				ii.position.x = i % 7 * 200 - 2.5f;

				// raise it up
				ii.position.y = .5f * 100;
				ii.position.z = -1 * i * 100;
				ii.castShadow = true;
				ii.receiveShadow = true;
				//ii.scale.set(100, 100, 100 * i);
				ii.scale.set(100, 100 * i, 100);


				meshArray.Add(ii);

				scene.add(ii);

				if (i % 2 == 0)
				{
#if FWebGLHZBlendCharacter
					#region SpeedBlendCharacter
					var _i = i;
					{ WebGLHZBlendCharacter.HTML.Pages.TexturesImages ref0; }

					var blendMesh = new THREE.SpeedBlendCharacter();
					blendMesh.load(
						new WebGLHZBlendCharacter.Models.marine_anims().Content.src,
						new Action(
							delegate
							{
								// buildScene
								//blendMesh.rotation.y = Math.PI * -135 / 180;
								blendMesh.castShadow = true;
								// we cannot scale down we want our shadows
								//blendMesh.scale.set(0.1, 0.1, 0.1);

								blendMesh.position.x = (_i + 2) % 7 * 200 - 2.5f;

								// raise it up
								//blendMesh.position.y = .5f * 100;
								blendMesh.position.z = -1 * _i * 100;


								var xtrue = true;
								// run
								blendMesh.setSpeed(1.0);

								// will in turn call THREE.AnimationHandler.play( this );
								//blendMesh.run.play();
								// this wont help. bokah does not see the animation it seems.
								//blendMesh.run.update(1);

								blendMesh.showSkeleton(!xtrue);

								scene.add(blendMesh);


								Native.window.onframe +=
								 delegate
								 {

									 blendMesh.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;



									 ii.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;

								 };

							}
						)
					);
					#endregion
#endif
				}

			}
			#endregion


			#region HZCannon
			new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
				async cube =>
				{
					// https://github.com/mrdoob/three.js/issues/1285
					//cube.children.WithEach(c => c.castShadow = true);

					//cube.traverse(
					//    new Action<THREE.Object3D>(
					//        child =>
					//        {
					//            // does it work? do we need it?
					//            //if (child is THREE.Mesh)

					//            child.castShadow = true;
					//            //child.receiveShadow = true;

					//        }
					//    )
					//);

					// um can edit and continue insert code going back in time?
					cube.scale.x = 10.0;
					cube.scale.y = 10.0;
					cube.scale.z = 10.0;



					//cube.castShadow = true;
					//dae.receiveShadow = true;

					//cube.position.x = -100;

					////cube.position.y = (cube.scale.y * 50) / 2;
					//cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



					// if i want to rotate, how do I do it?
					//cube.rotation.z = random() + Math.PI;
					//cube.rotation.x = random() + Math.PI;
					var sw2 = Stopwatch.StartNew();



					scene.add(cube);
					//interactiveObjects.Add(cube);

					// offset is wrong
					//while (true)
					//{
					//    await Native.window.async.onframe;

					//    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

					//}
				}
			);
			#endregion


			#region HZCannon
			new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
				async cube =>
				{
					// https://github.com/mrdoob/three.js/issues/1285
					//cube.children.WithEach(c => c.castShadow = true);

					//cube.traverse(
					//    new Action<THREE.Object3D>(
					//        child =>
					//        {
					//            // does it work? do we need it?
					//            //if (child is THREE.Mesh)

					//            child.castShadow = true;
					//            //child.receiveShadow = true;

					//        }
					//    )
					//);

					// um can edit and continue insert code going back in time?
					cube.scale.x = 10.0;
					cube.scale.y = 10.0;
					cube.scale.z = 10.0;



					//cube.castShadow = true;
					//dae.receiveShadow = true;


					// jsc shat about out of band code patching?
					cube.position.z = 600;
					cube.position.x = -900;
					//cube.position.y = -400;

					//cube.position.x = -100;
					//cube.position.y = -400;

					////cube.position.y = (cube.scale.y * 50) / 2;
					//cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



					// if i want to rotate, how do I do it?
					//cube.rotation.z = random() + Math.PI;
					//cube.rotation.x = random() + Math.PI;
					var sw2 = Stopwatch.StartNew();



					scene.add(cube);
					//interactiveObjects.Add(cube);

					// offset is wrong
					//while (true)
					//{
					//    await Native.window.async.onframe;

					//    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

					//}
				}
			);
			#endregion


			#region HZBunker
			new HeatZeekerRTSOrto.HZBunker().Source.Task.ContinueWithResult(
					 cube =>
					 {
						 // https://github.com/mrdoob/three.js/issues/1285
						 //cube.children.WithEach(c => c.castShadow = true);
						 cube.castShadow = true;

						 //cube.traverse(
						 //    new Action<THREE.Object3D>(
						 //        child =>
						 //        {
						 //            // does it work? do we need it?
						 //            //if (child is THREE.Mesh)
						 //            child.castShadow = true;
						 //            //child.receiveShadow = true;

						 //        }
						 //    )
						 //);

						 // um can edit and continue insert code going back in time?
						 cube.scale.x = 10.0;
						 cube.scale.y = 10.0;
						 cube.scale.z = 10.0;

						 //cube.castShadow = true;
						 //dae.receiveShadow = true;

						 cube.position.x = -1000;
						 //cube.position.y = (cube.scale.y * 50) / 2;
						 cube.position.z = 0;

						 scene.add(cube);
					 }
				 );
			#endregion






			var lon0 = -45.0;
			var lon1 = 0.0;

			var lon = new sum(
				 () => lon0,
				 () => lon1
			 );

			var lat0 = 0.0;
			var lat1 = 0.0;

			// or could we do it with byref or pointers?
			var lat = new sum(
				() => lat0,
				() => lat1
			);

			var phi = 0.0;
			var theta = 0.0;

			//var controls = new THREE.OrbitControls(camera);
			var camera_rotation_z = 0.0;

			Native.window.onframe +=
				delegate
				{
					////var delta = clock.getDelta();

					//controls.update();



					var scale = 1.0;
					var delta = clock.getDelta();
					var stepSize = delta * scale;

					if (stepSize > 0)
					{
						//characterController.update(stepSize, scale);
						//gui.setSpeed(blendMesh.speed);

						THREE.AnimationHandler.update(stepSize);
					}

					//camera.position = controls.center.clone();

					//if (Native.document.pointerLockElement == Native.document.body)
					//    lon += 0.00;
					//else
					//    lon += 0.01;

					//var lat2 = Math.Max(-85, Math.Min(85, lat));

					//Native.document.title = new { lon, lat }.ToString();
					//Native.document.title = new { lon0 }.ToString();


					phi = THREE.Math.degToRad(90 - lat);
					theta = THREE.Math.degToRad(lon);

					target.x = camera.position.x + (500 * Math.Sin(phi) * Math.Cos(theta));
					target.y = camera.position.y + (500 * Math.Cos(phi));
					target.z = camera.position.z + (500 * Math.Sin(phi) * Math.Sin(theta));


					//controls.update();
					//camera.position = controls.center.clone();

					// camera beta tilt?

					camera.lookAt(target);
					camera.rotation.z += camera_rotation_z;

					//composer.render(0.1);
					//renderer.render(scene, camera);
					effect.render(scene, camera);
				};


			new { }.With(
					 async delegate
					 {
						 retry:

                         //var s = (double)Native.window.Width / 1920.0;
                         //var s = (double)Native.window.Height / Native.screen.height;
                         //var s = (double)Native.window.Height / 1440;
                         var s = (double)Native.window.Height / 1080;


						 Native.document.body.style.transform = "scale(" + s + ")";
						 Native.document.body.style.transformOrigin = "0% 0%";

						 await Native.window.async.onresize;
						 goto retry;
					 }
				   );

			// gamma -0 .. -90

			var compassHeadingOffset = 0.0;
			var compassHeadingInitialized = 0;

			#region compassHeading
			// X:\jsc.svn\examples\javascript\android\Test\TestCompassHeading\TestCompassHeading\Application.cs
			Native.window.ondeviceorientation +=
			  dataValues =>
			  {
				  // Convert degrees to radians
				  var alphaRad = dataValues.alpha * (Math.PI / 180);
				  var betaRad = dataValues.beta * (Math.PI / 180);
				  var gammaRad = dataValues.gamma * (Math.PI / 180);

				  // Calculate equation components
				  var cA = Math.Cos(alphaRad);
				  var sA = Math.Sin(alphaRad);
				  var cB = Math.Cos(betaRad);
				  var sB = Math.Sin(betaRad);
				  var cG = Math.Cos(gammaRad);
				  var sG = Math.Sin(gammaRad);

				  // Calculate A, B, C rotation components
				  var rA = -cA * sG - sA * sB * cG;
				  var rB = -sA * sG + cA * sB * cG;
				  var rC = -cB * cG;

				  // Calculate compass heading
				  var compassHeading = Math.Atan(rA / rB);

				  // Convert from half unit circle to whole unit circle
				  if (rB < 0)
				  {
					  compassHeading += Math.PI;
				  }
				  else if (rA < 0)
				  {
					  compassHeading += 2 * Math.PI;
				  }

				  /*
                  Alternative calculation (replacing lines 99-107 above):

                    var compassHeading = Math.atan2(rA, rB);

                    if(rA < 0) {
                      compassHeading += 2 * Math.PI;
                    }
                  */

				  // Convert radians to degrees
				  compassHeading *= 180 / Math.PI;

				  // Compass heading can only be derived if returned values are 'absolute'

				  // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeadingWithReset\TestCompassHeadingWithReset\Application.cs

				  //Native.document.body.innerText = new { compassHeading }.ToString();
				  if (compassHeadingInitialized > 0)
				  {
					  lon1 = compassHeading - compassHeadingOffset;
				  }
				  else
				  {
					  compassHeadingOffset = compassHeading;
					  compassHeadingInitialized++;
				  }

			  };
			#endregion

			#region gamma
			Native.window.ondeviceorientation +=
				//e => Native.body.innerText = new { e.alpha, e.beta, e.gamma }.ToString();
				//e => lon = e.gamma;
				e =>
				{
					lat1 = e.gamma;

					// after servicing a running instance would be nice
					// either by patching or just re running the whole iteration in the backgrou
					camera_rotation_z = e.beta * 0.02;
				};
			#endregion



			#region camera rotation
			var old = new { clientX = 0, clientY = 0 };

			Native.document.body.ontouchstart +=
				e =>
				{
					var n = new { e.touches[0].clientX, e.touches[0].clientY };
					old = n;
				};

			Native.document.body.ontouchmove +=
					e =>
					{
						var n = new { e.touches[0].clientX, e.touches[0].clientY };

						e.preventDefault();

						lon0 += (n.clientX - old.clientX) * 0.2;
						lat0 -= (n.clientY - old.clientY) * 0.2;

						old = n;
					};


			Native.document.body.onmousemove +=
				e =>
				{
					e.preventDefault();

					if (Native.document.pointerLockElement == Native.document.body)
					{
						lon0 += e.movementX * 0.1;
						lat0 -= e.movementY * 0.1;

						//Console.WriteLine(new { lon, lat, e.movementX, e.movementY });
					}
				};


			Native.document.body.onmouseup +=
			  e =>
			  {
				  //drag = false;
				  e.preventDefault();
			  };

			Native.document.body.onmousedown +=
				e =>
				{
					//e.CaptureMouse();

					//drag = true;
					e.preventDefault();
					Native.document.body.requestPointerLock();

				};


			Native.document.body.ondblclick +=
				e =>
				{
					e.preventDefault();

					Console.WriteLine("requestPointerLock");
				};

			#endregion

			Native.body.onmousewheel +=
				e =>
				{

					camera_rotation_z += 0.1 * e.WheelDirection; ;

				};
		}
        // Could not connect to the feed specified at 'http://my.jsc-solutions.net/nuget'. P


        public Application(IApp page)
        {
            //{ var ref0 = typeof(dirt_tx); }
            { var ref0 = new dirt_tx { }; }
            //{ var ref0 = typeof(MarineCv2_color); }
            { var ref0 = new MarineCv2_color { }; }

            // http://www.realitymeltdown.com/WebGL3/character-controller.html

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150127
            //Native.css
            Native.body.style.margin = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            //Error CS0246  The type or namespace name 'THREE' could not be found(are you missing a using directive or an assembly reference?)	WebGLSpeedBlendCharacter Application.cs  46
            // used by, for?
            var clock = new THREE.Clock();
            //var keys = new { LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, A = 65, S = 83, D = 68, W = 87 };


            var scene = new THREE.Scene();
            var skyScene = new THREE.Scene();
            scene.fog = new THREE.Fog(0xB0CAE1, 1000, 20000);
            scene.add(new THREE.AmbientLight(0xaaaaaa));

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            var light = new THREE.DirectionalLight(0xffffff, 1.5);
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;
            xlight.shadowDarkness = 0.5;
            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;
            xlight.shadowCameraVisible = true;

            scene.add(light);

            #region renderer
            var renderer = new THREE.WebGLRenderer(new { antialias = true, alpha = false });
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.autoClear = false;
            renderer.shadowMapEnabled = true;
            renderer.shadowMapType = THREE.PCFSoftShadowMap;

            renderer.domElement.AttachToDocument();
            #endregion



            // this will mess up
            // three.OrbitControls.js
            // onMouseMove

            //new IStyle(renderer.domElement)
            //{
            //    position = IStyle.PositionEnum.absolute,
            //    left = "0px",
            //    top = "0px",
            //    right = "0px",
            //    bottom = "0px",
            //};


            //new { }.With(
            //    async delegate
            //    {

            //        await Native.window.async.onresize;

            //        // if the reload were fast, then we could actually do that:D
            //        Native.document.location.reload();

            //    }
            //);





            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            //var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            //var planeMaterial = new THREE.MeshLambertMaterial(
            //    new
            //    {
            //        map = THREE.ImageUtils.loadTexture(new HTML.Images.FromAssets.dirt_tx().src),
            //        color = 0xffffff
            //    }
            //);

            //planeMaterial.map.repeat.x = 300;
            //planeMaterial.map.repeat.y = 300;
            //planeMaterial.map.wrapS = THREE.RepeatWrapping;
            //planeMaterial.map.wrapT = THREE.RepeatWrapping;
            //var plane = new THREE.Mesh(planeGeometry, planeMaterial);
            //plane.castShadow = false;
            //plane.receiveShadow = true;


            //{

            //    var parent = new THREE.Object3D();
            //    parent.add(plane);
            //    parent.rotation.x = -Math.PI / 2;
            //    parent.scale.set(100, 100, 100);

            //    scene.add(parent);
            //}

            var random = new Random();
            var meshArray = new List<THREE.Mesh>();
            //var geometry = new THREE.CubeGeometry(1, 1, 1);
            var geometry = new THREE.BoxGeometry(1, 1, 1);

            for (var i = 1; i < 100; i++)
            {

                var ii = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial(
                    new
                    {
                        color = (Convert.ToInt32(0xffffff * random.NextDouble()))
                    }));
                ii.position.x = i % 2 * 500 - 2.5f;

                // raise it up
                ii.position.y = .5f * 100;
                ii.position.z = -1 * i * 400;
                ii.castShadow = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);

            }
            #endregion





            var blendMesh = new THREE.SpeedBlendCharacter();


            blendMesh.load(
                new Models.marine_anims().Content.src,
                new Action(
                    delegate
                    {
                        // buildScene

                        //blendMesh.rotation.y = Math.PI * -135 / 180;
                        blendMesh.castShadow = true;
                        // we cannot scale down we want our shadows
                        //blendMesh.scale.set(0.1, 0.1, 0.1);

                        scene.add(blendMesh);

                        //var characterController = new THREE.CharacterController(blendMesh);

                        // run
                        blendMesh.setSpeed(1.0);

                        var radius = blendMesh.geometry.boundingSphere.radius;


                        Native.document.title = new { radius }.ToString();


                        var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                        camera.position.set(0.0, radius * 3, radius * 3.5);

                        var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                        skyCamera.position.set(0.0, radius * 3, radius * 3.5);

                        var controls = new THREE.OrbitControls(camera);
                        //controls.noPan = true;


                        var loader = new THREE.JSONLoader();
                        loader.load(new Models.ground().Content.src,
                            new Action<THREE.Geometry, THREE.Material[]>(

                            (xgeometry, materials) =>
                            {
                                // cannot see the ground?
                                var ground = new THREE.Mesh(xgeometry, materials[0]);
                                ground.scale.set(20, 20, 20);
                                ground.receiveShadow = true;
                                ground.castShadow = true;
                                scene.add(ground);

                            }
                            )
                         );

                        #region  createSky
                        // gearvr has photos360 app
                        var urls = new[] {
                            new px().src, new nx().src,
                            new py().src, new ny().src,
                            new pz().src, new nz().src,
                         };

                        var textureCube = THREE.ImageUtils.loadTextureCube(urls);

                        dynamic shader = THREE.ShaderLib["cube"];
                        shader.uniforms["tCube"].value = textureCube;

                        // We're inside the box, so make sure to render the backsides
                        // It will typically be rendered first in the scene and without depth so anything else will be drawn in front
                        var material = new THREE.ShaderMaterial(new
                        {
                            fragmentShader = shader.fragmentShader,
                            vertexShader = shader.vertexShader,
                            uniforms = shader.uniforms,
                            depthWrite = false,
                            side = THREE.BackSide
                        });

                        // THREE.CubeGeometry has been renamed to THREE.BoxGeometry
                        // The box dimension size doesn't matter that much when the camera is in the center.  Experiment with the values.
                        //var skyMesh = new THREE.Mesh(new THREE.CubeGeometry(10000, 10000, 10000, 1, 1, 1), material);
                        var skyMesh = new THREE.Mesh(new THREE.BoxGeometry(10000, 10000, 10000), material);
                        //skyMesh.renderDepth = -10;


                        skyScene.add(skyMesh);
                        #endregion

                        #region onframe
                        Native.window.onframe +=
                            delegate
                            {
                                var scale = 1.0;
                                var delta = clock.getDelta();
                                var stepSize = delta * scale;

                                if (stepSize > 0)
                                {
                                    //characterController.update(stepSize, scale);
                                    //gui.setSpeed(blendMesh.speed);

                                    THREE.AnimationHandler.update(stepSize);
                                    blendMesh.updateSkeletonHelper();
                                }

                                controls.center.copy(blendMesh.position);
                                controls.center.y += radius * 2.0;
                                controls.update();

                                var camOffset = camera.position.clone().sub(controls.center);
                                camOffset.normalize().multiplyScalar(750);
                                camera.position = controls.center.clone().add(camOffset);

                                skyCamera.rotation.copy(camera.rotation);



                                renderer.clear();
                                renderer.render(skyScene, skyCamera);
                                renderer.render(scene, camera);
                            };
                        #endregion


                        #region onresize
                        new { }.With(
                              async delegate
                              {
                                  do
                                  {
                                      camera.aspect = Native.window.aspect;
                                      camera.updateProjectionMatrix();
                                      renderer.setSize(Native.window.Width, Native.window.Height);

                                  } while (await Native.window.async.onresize);
                              }
                          );
                        #endregion


                    }
                )
           );




        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // if we are running in a SYSTEM account
            // the chrome no-sandbox only allows software renderer
            // where we get 1 frame per sec.


            // on older systems we may not get GL_OES_standard_derivatives 
            // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app
            // 			( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
            // or that system is just old as hell


            // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app

            //http://thematicmapping.org/playground/webgl/earth/
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222


            // Earth params
            var radius = 0.5;

            //var segments = 32;
            var segments = 128;
            var rotation = 6;

            var scene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000);
            camera.position.z = 1.5;

            var renderer = new THREE.WebGLRenderer(
                   new
                   {
                       preserveDrawingBuffer = true
                   }
                );
            renderer.setSize();

            scene.add(new THREE.AmbientLight(0x333333));

            var light = new THREE.DirectionalLight(0xffffff, 1);
            light.position.set(5, 3, 5);
            scene.add(light);

            var parent = new THREE.Object3D();
            scene.add(parent);


            #region sphere
            var sphere = new THREE.Mesh(
                new THREE.SphereGeometry(radius, segments, segments),
                new THREE.MeshPhongMaterial(
                        new
                        {
                            map = new THREE.Texture().With(
                                async s =>
                                {
                                    //0:75ms event: _2_no_clouds_4k_low view-source:36543
                                    //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1
                                    //Application Cache Progress event (2 of 2)  192.168.1.72/:1
                                    //Application Cache Cached event 192.168.1.72/:1
                                    //1:1018ms event: _2_no_clouds_4k_low done view-source:36543
                                    //1:1019ms event: _2_no_clouds_4k view-source:36543
                                    //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995
                                    //1:16445ms event: _2_no_clouds_4k done 

                                    // ~ tilde to open css editor?

                                    Console.WriteLine("event: _2_no_clouds_4k_low");
                                    s.image = await new _2_no_clouds_4k_low();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: _2_no_clouds_4k_low done");

                                    await 20000;

                                    Console.WriteLine("event: _2_no_clouds_4k");
                                    s.image = await new _2_no_clouds_4k();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: _2_no_clouds_4k done");
                                }
                            ),

                            bumpMap = THREE.ImageUtils.loadTexture(
                                new elev_bump_4k().src
                                //new elev_bump_4k_low().src
                                ),


                            // applies onyl to shaders to create the shadow
                            bumpScale = 0.001,
                            specularMap = new THREE.Texture().With(
                                async s =>
                                {
                                    Console.WriteLine("event: water_4k_low");
                                    s.image = await new water_4k_low();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: water_4k_low done");

                                    await 20000;

                                    Console.WriteLine("event: water_4k");
                                    s.image = await new water_4k();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: water_4k done");
                                }
                            ),


                            //specular =    new THREE.Color("grey")								
                            specular = new THREE.Color(0xa0a0a0)
                        })
            );
            #endregion

            // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane


            //sphere.rotation.y = rotation;
            parent.rotation.y = rotation;
            //sphere.position.x = 10;
            //sphere.position.y = 10;
            //sphere.position.z = 10;
            //sphere.position.normalize();
            //sphere.position.multiplyScalar(200); 

            parent.add(sphere);
            //scene.add(sphere);


            #region clouds
            var clouds = new THREE.Mesh(
                    new THREE.SphereGeometry(
                        //radius + 0.003,
                        radius + 0.006,
                        segments, segments),
                    new THREE.MeshPhongMaterial(
                        new
                        {
                            //map = THREE.ImageUtils.loadTexture(
                            //    //new fair_clouds_4k().src
                            //    new fair_clouds_4k_low().src
                            //    ),


                            map = new THREE.Texture().With(
                                async s =>
                                {
                                    Console.WriteLine("event: fair_clouds_4k_low");
                                    s.image = await new fair_clouds_4k_low();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: fair_clouds_4k_low done");

                                    await 20000;

                                    Console.WriteLine("event: fair_clouds_4k");
                                    s.image = await new fair_clouds_4k();
                                    s.needsUpdate = true;
                                    Console.WriteLine("event: fair_clouds_4k done");
                                }
                            ),

                            transparent = true
                        })
                );
            //clouds.rotation.y = rotation;
            parent.add(clouds);
            //scene.add(clouds);
            #endregion

            #region Location on sphere

            Action AddCities = async delegate
            {
                var table = await this.GetAllCities();
                Console.WriteLine(table.Rows.Count.ToString());

                for (var r = 0; r < table.Rows.Count; r++)
                {
                    var latitude = (double)table.Rows[r]["Latitude"];
                    var longtitude = (double)table.Rows[r]["Longtitude"];
                    addLocation(latitude, longtitude, radius, 0.001, parent, 6);
                    Console.WriteLine(latitude.ToString());
                    await 100;
                }
            };
            AddCities();


            #endregion

            var stars = new THREE.Mesh(
                    new THREE.SphereGeometry(90, 64, 64),
                    new THREE.MeshBasicMaterial(
                    new
                    {
                        map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src),
                        side = THREE.BackSide
                    })
                );
            scene.add(stars);

            this.canvas = (IHTMLCanvas)renderer.domElement;

            //renderer.domElement.AttachToDocument();
            this.canvas.AttachToDocument();
            this.canvas.style.SetLocation(0, 0);

            // jsc, what pointers do we have in store?
            this.canvas.css.style.cursor = IStyle.CursorEnum.pointer;
            this.canvas.css.active.style.cursor = IStyle.CursorEnum.move;


            var
                old = new
                {
                    parent = new
                    {
                        parent.rotation.x,
                        parent.rotation.y
                    },
                    //sphere = new
                    //{
                    //    //sphere.rotation.x,
                    //    //sphere.rotation.y

                    //},
                    //clouds = new
                    //{
                    //    //clouds.rotation.x,
                    //    //clouds.rotation.y,
                    //},


                    CursorX = 0,
                    CursorY = 0
                };

            #region onmousedown
            this.canvas.onmousedown +=
                e =>
                {
                    var pointerLock = this.canvas == Native.document.pointerLockElement;

                    if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                    {
                        this.canvas.requestFullscreen();
                        this.canvas.requestPointerLock();
                    }
                    else
                    {
                        // movementX no longer works
                        old = new
                        {
                            parent = new
                            {
                                parent.rotation.x,
                                parent.rotation.y
                            },
                            //sphere = new
                            //{
                            //    sphere.rotation.x,
                            //    sphere.rotation.y

                            //},
                            //clouds = new
                            //{
                            //    clouds.rotation.x,
                            //    clouds.rotation.y,
                            //},


                            e.CursorX,
                            e.CursorY
                        };

                        if (pointerLock)
                        {
                            // skip
                        }
                        else
                        {
                            e.CaptureMouse();
                        }
                    }

                };
            #endregion





            var z = camera.position.z;

            var sfx = new WebGLEarthTest.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1
            {
                autobuffer = true,

                // this aint working
                //loop = true 

            };

            sfx.play();

            //sfx.AttachToHead();


            // http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/

            this.canvas.onmousewheel +=
                e =>
                {
                    //camera.position.z = 1.5;

                    // min max. shall adjust speed also!
                    // max 4.0
                    // min 0.6
                    z -= 0.1 * e.WheelDirection;

                    z = z.Max(0.6).Min(4.5);

                    //Native.document.title = new { camera.position.z }.ToString();

                };

            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            this.canvas.onmousemove +=
                e =>
                {
                    var pointerLock = this.canvas == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {
                        if (pointerLock)
                        {
                            parent.rotation.x += 0.01 * e.movementY;
                            parent.rotation.y += 0.01 * e.movementX;

                            //sphere.rotation.x += 0.01 * e.movementY;
                            //sphere.rotation.y += 0.01 * e.movementX;

                            //clouds.rotation.x += 0.01 * e.movementY;
                            //clouds.rotation.y += 0.01 * e.movementX;
                        }
                        else
                        {
                            parent.rotation.x = old.parent.x + 0.01 * (e.CursorY - old.CursorY);
                            parent.rotation.y = old.parent.y + 0.01 * (e.CursorX - old.CursorX);

                            //sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY);
                            //sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX);

                            //clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY);
                            //clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX);
                        }


                        //    Native.document.title = new { e.movementX, e.movementY }.ToString();

                    }

                };
            #endregion


            // could we 
            Native.window.onframe +=
                e =>
                {
                    if (this.canvas.parentNode == null)
                        return;

                    camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                    camera.updateProjectionMatrix();

                    camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                    // the larger the vew the slower the rotation shall be
                    var speed = 0.0001 * e.delay.ElapsedMilliseconds +
                        0.007
                        * 96.0 / canvas.clientHeight
                        * 1.0 / camera.position.z;

                    //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString();
                    //Native.document.title = new { speed }.ToString();


                    //controls.update();
                    //sphere.rotation.y += speed;
                    //clouds.rotation.y += speed;

                    parent.rotation.y += speed;


                    renderer.render(scene, camera);
                };

            Native.window.onresize +=
                delegate
                {


                    //if (canvas.parentNode == Native.document.body)

                    // are we embedded?
                    if (page != null)
                        renderer.setSize();
                };


            //new IStyle(this.canvas.css.before)
            //{
            //    content = "'do a middle click to maximize the earth dashboard'",

            //    left = "1em",
            //    bottom = "1em",

            //    color = "white",

            //    position = IStyle.PositionEnum.absolute
            //};
        }
        // subst a: s:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeGalaxyS6Edge\ChromeGalaxyS6Edge\bin\Debug\staging\ChromeGalaxyS6Edge.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeGalaxyS6Edge\ChromeGalaxyS6Edge\bin\Debug\staging\ChromeGalaxyS6Edge.Application\web

		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{
            FormStyler.AtFormCreated =
            s =>
            {
                s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

                //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
                var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



                s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
                //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            };

			#region += Launched chrome.app.window
			// X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
			dynamic self = Native.self;
			dynamic self_chrome = self.chrome;
			object self_chrome_socket = self_chrome.socket;

			if (self_chrome_socket != null)
			{
				//chrome.Notification.DefaultTitle = "Nexus7";
				//chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text,
                    AtFormCreated: FormStyler.AtFormCreated

                    //AtFormConstructor:
                    //    f =>
                    //    {
                    //        //arg[0] is typeof System.Int32
                    //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                    //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                    //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                    //    }
                );
				return;
			}
			#endregion

			Native.body.Clear();

			var oo = new List<THREE.Object3D>();

			#region scene
			var window = Native.window;

			var camera = new THREE.PerspectiveCamera(
				45,
				window.aspect,
				1,
				2000
				);
			camera.position.z = 400;

			// scene

			var scene = new THREE.Scene();

			var ambient = new THREE.AmbientLight(0x303030);
			scene.add(ambient);

			var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
			directionalLight.position.set(0, 0, 1);
			scene.add(directionalLight);

			// WebGLRenderer preserveDrawingBuffer 
			var renderer = new THREE.WebGLRenderer(

				new
				{
					antialias = true,
					alpha = true,
					preserveDrawingBuffer = true
				}
			);

			// https://github.com/mrdoob/three.js/issues/3836
			//renderer.setClearColor(0xfffff, 1);

			renderer.setSize(window.Width, window.Height);

			renderer.domElement.AttachToDocument();
			renderer.domElement.style.SetLocation(0, 0);

			var canvas = (IHTMLCanvas)renderer.domElement;


			var old = new
			{



				CursorX = 0,
				CursorY = 0
			};


			var mouseX = 0;
			var mouseY = 0;
			var st = new Stopwatch();
			st.Start();


			canvas.css.active.style.cursor = IStyle.CursorEnum.move;

			#region onmousedown
			canvas.onmousedown +=
				e =>
				{

					if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
					{
						canvas.requestFullscreen();
					}
					else
					{
						// movementX no longer works
						old = new
						{


							e.CursorX,
							e.CursorY
						};


						e.CaptureMouse();
					}

				};
			#endregion



			// X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
			#region onmousemove
			canvas.onmousemove +=
				e =>
				{
					var pointerLock = canvas == Native.document.pointerLockElement;


					//Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

					if (e.MouseButton == IEvent.MouseButtonEnum.Left)
					{

						oo.WithEach(
							x =>
							{
								x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
								x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
							}
						);

						old = new
						{


							e.CursorX,
							e.CursorY
						};



					}

				};
			#endregion
			var z = camera.position.z;

			#region onmousewheel
			canvas.onmousewheel +=
				e =>
				{
					//camera.position.z = 1.5;

					// min max. shall adjust speed also!
					// max 4.0
					// min 0.6
					z -= 10.0 * e.WheelDirection;

					//camera.position.z = 400;
					z = z.Max(200).Min(500);

					//Native.document.title = new { z }.ToString();

				};
			#endregion


			Native.window.onframe +=
				e =>
				{
					renderer.clear();

					camera.aspect = canvas.aspect;
					camera.updateProjectionMatrix();

					camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


					camera.lookAt(scene.position);

					renderer.render(scene, camera);


				};

			Native.window.onresize +=
				delegate
				{
					if (canvas.parentNode == Native.document.body)
					{
						renderer.setSize(window.Width, window.Height);
					}

				};
			#endregion

			// THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

			new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
				   dae =>
				   {
					   // 90deg
					   dae.rotation.x = -Math.Cos(Math.PI);

					   //dae.scale.x = 30;
					   //dae.scale.y = 30;
					   //dae.scale.z = 30;
					   dae.position.z = 65;

                       var scale = 0.7;

					   // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;

					   //dae.position.y = -80;

					   scene.add(dae);
					   oo.Add(dae);


				   }
			   );

			Console.WriteLine("do you see it?");
		}
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{
			// view-source:http://alteredqualia.com/three/examples/webgl_postprocessing_ssao.html
			// http://threejs.org/examples/#webgl_materials_cubemap_dynamic

			// X:\jsc.svn\examples\javascript\WebGL\WebGLDepthOfField\WebGLDepthOfField\Application.cs
			// http://threejs.org/examples/#webgl_postprocessing_dof
			// "X:\opensource\github\three.js\examples\webgl_postprocessing_dof.html"

			{ WebGLHZBlendCharacter.HTML.Pages.TexturesImages ref0; }

			Native.body.style.margin = "0px";
			Native.body.style.overflow = IStyle.OverflowEnum.hidden;
			Native.body.Clear();

			var clock = new THREE.Clock();

			var radius = 100;
			var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
			skyCamera.position.set(0.0, radius * 3, radius * 3.5);

			var camera = new THREE.PerspectiveCamera(80, Native.window.aspect, 1, 5000);
			camera.position.z = 200;

			var skyScene = new THREE.Scene();
			var scene = new THREE.Scene();



			//scene.fog = new THREE.Fog(0xA26D41, 1000, 20000);

			//scene.add(new THREE.AmbientLight(0xaaaaaa));
			scene.add(new THREE.AmbientLight(0xffffff));

			var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

			var light = new THREE.DirectionalLight(0xffffff, 1.0);
			//var light = new THREE.DirectionalLight(0xffffff, 2.5);
			//var light = new THREE.DirectionalLight(0xffffff, 1.5);
			light.position.copy(lightOffset);
			light.castShadow = true;

			var xlight = light as dynamic;
			xlight.shadowMapWidth = 4096;
			xlight.shadowMapHeight = 2048;

			xlight.shadowDarkness = 0.3;
			//xlight.shadowDarkness = 0.5;

			xlight.shadowCameraNear = 10;
			xlight.shadowCameraFar = 10000;
			xlight.shadowBias = 0.00001;
			xlight.shadowCameraRight = 4000;
			xlight.shadowCameraLeft = -4000;
			xlight.shadowCameraTop = 4000;
			xlight.shadowCameraBottom = -4000;
			//xlight.shadowCameraVisible = true;

			scene.add(light);


			var renderer = new THREE.WebGLRenderer(new { antialias = false });
			renderer.setSize(Native.window.Width, Native.window.Height);
			renderer.domElement.AttachToDocument();
			renderer.sortObjects = false;
			renderer.autoClear = false;
			renderer.shadowMapEnabled = true;
			renderer.shadowMapType = THREE.PCFSoftShadowMap;

			//var material_depth = new THREE.MeshDepthMaterial();





			#region create field

			// THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
			var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
			var plane = new THREE.Mesh(planeGeometry,
					new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

				);
			plane.castShadow = false;
			plane.receiveShadow = true;


			{

				var parent = new THREE.Object3D();
				parent.add(plane);
				parent.rotation.x = -Math.PI / 2;
				parent.scale.set(100, 100, 100);

				scene.add(parent);
			}

			var random = new Random();
			var meshArray = new List<THREE.Mesh>();
			var geometry = new THREE.CubeGeometry(1, 1, 1);
			var sw = Stopwatch.StartNew();

			for (var i = 1; i < 5; i++)
			{

				//THREE.MeshPhongMaterial
				var ii = new THREE.Mesh(geometry,


					new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

					//new THREE.MeshLambertMaterial(
					//new
					//{
					//    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
					//    specular = 0xffaaaa,
					//    ambient= 0x050505, 
					//})

					);
				ii.position.x = i % 4 * 500 - 2.5f;

				// raise it up
				ii.position.y = .5f * 100;
				ii.position.z = -1 * i * 300;
				ii.castShadow = true;
				ii.receiveShadow = true;
				//ii.scale.set(100, 100, 100 * i);
				ii.scale.set(100, 100 * i, 100);


				meshArray.Add(ii);

				scene.add(ii);

				var _i = i;

				var blendMesh = new THREE.SpeedBlendCharacter();
				blendMesh.load(
					new WebGLHZBlendCharacter.Models.marine_anims().Content.src,
					new Action(
						delegate
						{
							// buildScene
							//blendMesh.rotation.y = Math.PI * -135 / 180;
							blendMesh.castShadow = true;
							// we cannot scale down we want our shadows
							//blendMesh.scale.set(0.1, 0.1, 0.1);

							blendMesh.position.x = (_i + 2) % 4 * 500 - 2.5f;

							// raise it up
							//blendMesh.position.y = .5f * 100;
							blendMesh.position.z = -1 * _i * 300;


							var xtrue = true;
							// run
							blendMesh.setSpeed(1.0);

							// will in turn call THREE.AnimationHandler.play( this );
							blendMesh.run.play();
							// this wont help. bokah does not see the animation it seems.
							blendMesh.run.update(1);

							blendMesh.showSkeleton(!xtrue);

							scene.add(blendMesh);


							Native.window.onframe +=
							 delegate
							 {

								 blendMesh.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;



								 ii.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;

							 };

						}
					)
				);

			}
			#endregion


			// maskpass
			// THREE.EffectComposer relies on THREE.CopyShader
			var composer = new THREE.EffectComposer(renderer);

			var renderPass = new THREE.RenderPass(scene, camera);
			composer.addPass(renderPass);

			// THREE.BokehPass relies on THREE.BokehShader
			var bokehPass = new THREE.BokehPass(scene, camera, new
			{
				focus = 1.0,
				aperture = 0.025,
				maxblur = 1.0,

				width = Native.window.Width,
				height = Native.window.Height
			});

			bokehPass.renderToScreen = true;
			composer.addPass(bokehPass);

			renderer.autoClear = false;

			var controls = new THREE.OrbitControls(camera);


			Native.document.onclick +=
				delegate
				{
					// THREE.AnimationHandler.add() has been deprecated.

					// how to make it work with bokah?
					//THREE.AnimationHandler.update(1);

				};



			#region onframe
			Native.window.onframe +=
				delegate
				{
					controls.update();


					var scale = 1.0;
					var delta = clock.getDelta();
					var stepSize = delta * scale;

					if (stepSize > 0)
					{
						//characterController.update(stepSize, scale);
						//gui.setSpeed(blendMesh.speed);

						//THREE.AnimationHandler.update(stepSize);
					}


					camera.position = controls.center.clone();


					skyCamera.rotation.copy(camera.rotation);

					composer.render(0.1);

				};

			#endregion


			new { }.With(
				  async delegate
				  {
					  //while (true)
					  do
					  {
						  camera.aspect = Native.window.aspect;
						  camera.updateProjectionMatrix();
						  renderer.setSize(Native.window.Width, Native.window.Height);

						  // convert to bool?
					  } while (await Native.window.async.onresize);
					  //} while (await Native.window.async.onresize != null);

				  }
			  );

		}
Example #26
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // "X:\opensource\github\three.js\examples\canvas_camera_orthographic.html"

            // if i type THREE, would jsc be able to add THREE package on rebuild?
            // Error	136	The type or namespace name 'THREE' could not be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs	35	26	WebGLOrthographicCamera



            // X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs

            var camera = new THREE.OrthographicCamera(Native.window.Width / -2, Native.window.Width / 2, Native.window.Height / 2, Native.window.Height / -2, -500, 1000);

            camera.position.x = 200;
            camera.position.y = 100;
            camera.position.z = 200;

            var scene = new THREE.Scene();

            // Grid

            var size = 500;
            var step = 50;


            Func <double> random = new Random().NextDouble;


            {
                var geometry = new THREE.Geometry();

                for (var i = -size; i <= size; i += step)
                {
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(-size, 0, i));
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(size, 0, i));

                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(i, 0, -size));
                    ((IArray <THREE.Vector3>)(object) geometry.vertices).push(new THREE.Vector3(i, 0, size));
                }

                var material = new THREE.LineBasicMaterial(new { color = 0x000000, opacity = 0.2 });

                var line = new THREE.Line(geometry, material);

                line.type = THREE.LinePieces;
                scene.add(line);
            }

            #region Cubes
            {
                var geometry = new THREE.BoxGeometry(50, 50, 50);
                var material = new THREE.MeshLambertMaterial(new { color = 0xffffff, shading = THREE.FlatShading, overdraw = 0.5 });

                for (var i = 0; i < 100; i++)
                {
                    var cube = new THREE.Mesh(geometry, material);

                    cube.scale.y = Math.Floor(random() * 2 + 1);

                    cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
                    cube.position.y = (cube.scale.y * 50) / 2;
                    cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

                    scene.add(cube);
                }
            }
            #endregion


            #region  Lights

            var ambientLight = new THREE.AmbientLight((int)(random() * 0x10));
            scene.add(ambientLight);

            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff));

                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = random() - 0.5;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }

            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff));
                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = random() - 0.5;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }
            #endregion


            //var renderer = new THREE.CanvasRenderer();
            var renderer = new THREE.WebGLRenderer();
            renderer.setClearColor(0xf0f0f0);
            //renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.setSize();

            renderer.domElement.AttachToDocument();

            //window.addEventListener( 'resize', onWindowResize, false );


            var s = Stopwatch.StartNew();

            Native.window.onframe +=
                e =>
            {
                // jsc, when can we have the edit and continue already?
                //var timer = s.ElapsedMilliseconds * 0.1;
                var timer = s.ElapsedMilliseconds * 0.0001;

                camera.position.x = Math.Cos(timer) * 200;
                camera.position.z = Math.Sin(timer) * 200;
                camera.lookAt(scene.position);

                renderer.render(scene, camera);
            };
        }
Example #27
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // view-source:http://alteredqualia.com/three/examples/webgl_postprocessing_ssao.html
            // http://threejs.org/examples/#webgl_materials_cubemap_dynamic

            // X:\jsc.svn\examples\javascript\WebGL\WebGLDepthOfField\WebGLDepthOfField\Application.cs
            // http://threejs.org/examples/#webgl_postprocessing_dof
            // "X:\opensource\github\three.js\examples\webgl_postprocessing_dof.html"

            { WebGLHZBlendCharacter.HTML.Pages.TexturesImages ref0; }

            Native.body.style.margin   = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;
            Native.body.Clear();

            var clock = new THREE.Clock();

            var radius    = 100;
            var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);

            skyCamera.position.set(0.0, radius * 3, radius * 3.5);

            var camera = new THREE.PerspectiveCamera(80, Native.window.aspect, 1, 5000);

            camera.position.z = 200;

            var skyScene = new THREE.Scene();
            var scene    = new THREE.Scene();



            //scene.fog = new THREE.Fog(0xA26D41, 1000, 20000);

            //scene.add(new THREE.AmbientLight(0xaaaaaa));
            scene.add(new THREE.AmbientLight(0xffffff));

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            var light = new THREE.DirectionalLight(0xffffff, 1.0);

            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;

            xlight.shadowMapWidth  = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear   = 10;
            xlight.shadowCameraFar    = 10000;
            xlight.shadowBias         = 0.00001;
            xlight.shadowCameraRight  = 4000;
            xlight.shadowCameraLeft   = -4000;
            xlight.shadowCameraTop    = 4000;
            xlight.shadowCameraBottom = -4000;
            //xlight.shadowCameraVisible = true;

            scene.add(light);


            var renderer = new THREE.WebGLRenderer(new { antialias = false });

            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.domElement.AttachToDocument();
            renderer.sortObjects      = false;
            renderer.autoClear        = false;
            renderer.shadowMapEnabled = true;
            renderer.shadowMapType    = THREE.PCFSoftShadowMap;

            //var material_depth = new THREE.MeshDepthMaterial();



            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            var plane         = new THREE.Mesh(planeGeometry,
                                               new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

                                               );
            plane.castShadow    = false;
            plane.receiveShadow = true;


            {
                var parent = new THREE.Object3D();
                parent.add(plane);
                parent.rotation.x = -Math.PI / 2;
                parent.scale.set(100, 100, 100);

                scene.add(parent);
            }

            var random    = new Random();
            var meshArray = new List <THREE.Mesh>();
            var geometry  = new THREE.CubeGeometry(1, 1, 1);
            var sw        = Stopwatch.StartNew();

            for (var i = 1; i < 5; i++)
            {
                //THREE.MeshPhongMaterial
                var ii = new THREE.Mesh(geometry,


                                        new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

                                        //new THREE.MeshLambertMaterial(
                                        //new
                                        //{
                                        //    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
                                        //    specular = 0xffaaaa,
                                        //    ambient= 0x050505,
                                        //})

                                        );
                ii.position.x = i % 4 * 500 - 2.5f;

                // raise it up
                ii.position.y    = .5f * 100;
                ii.position.z    = -1 * i * 300;
                ii.castShadow    = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);

                var _i = i;

                var blendMesh = new THREE.SpeedBlendCharacter();
                blendMesh.load(
                    new WebGLHZBlendCharacter.Models.marine_anims().Content.src,
                    new Action(
                        delegate
                {
                    // buildScene
                    //blendMesh.rotation.y = Math.PI * -135 / 180;
                    blendMesh.castShadow = true;
                    // we cannot scale down we want our shadows
                    //blendMesh.scale.set(0.1, 0.1, 0.1);

                    blendMesh.position.x = (_i + 2) % 4 * 500 - 2.5f;

                    // raise it up
                    //blendMesh.position.y = .5f * 100;
                    blendMesh.position.z = -1 * _i * 300;


                    var xtrue = true;
                    // run
                    blendMesh.setSpeed(1.0);

                    // will in turn call THREE.AnimationHandler.play( this );
                    blendMesh.run.play();
                    // this wont help. bokah does not see the animation it seems.
                    blendMesh.run.update(1);

                    blendMesh.showSkeleton(!xtrue);

                    scene.add(blendMesh);


                    Native.window.onframe +=
                        delegate
                    {
                        blendMesh.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;



                        ii.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;
                    };
                }
                        )
                    );
            }
            #endregion


            // maskpass
            // THREE.EffectComposer relies on THREE.CopyShader
            var composer = new THREE.EffectComposer(renderer);

            var renderPass = new THREE.RenderPass(scene, camera);
            composer.addPass(renderPass);

            // THREE.BokehPass relies on THREE.BokehShader
            var bokehPass = new THREE.BokehPass(scene, camera, new
            {
                focus    = 1.0,
                aperture = 0.025,
                maxblur  = 1.0,

                width  = Native.window.Width,
                height = Native.window.Height
            });

            bokehPass.renderToScreen = true;
            composer.addPass(bokehPass);

            renderer.autoClear = false;

            var controls = new THREE.OrbitControls(camera);


            Native.document.onclick +=
                delegate
            {
                // THREE.AnimationHandler.add() has been deprecated.

                // how to make it work with bokah?
                //THREE.AnimationHandler.update(1);
            };



            #region onframe
            Native.window.onframe +=
                delegate
            {
                controls.update();


                var scale    = 1.0;
                var delta    = clock.getDelta();
                var stepSize = delta * scale;

                if (stepSize > 0)
                {
                    //characterController.update(stepSize, scale);
                    //gui.setSpeed(blendMesh.speed);

                    //THREE.AnimationHandler.update(stepSize);
                }


                camera.position = controls.center.clone();


                skyCamera.rotation.copy(camera.rotation);

                composer.render(0.1);
            };

            #endregion


            new { }.With(
                async delegate
            {
                //while (true)
                do
                {
                    camera.aspect = Native.window.aspect;
                    camera.updateProjectionMatrix();
                    renderer.setSize(Native.window.Width, Native.window.Height);

                    // convert to bool?
                } while (await Native.window.async.onresize);
                //} while (await Native.window.async.onresize != null);
            }
                );
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            // https://3dwarehouse.sketchup.com/model.html?id=e78dca4863e8572d86ea4fa6bd93bc43
            // https://3dwarehouse.sketchup.com/model.html?id=38d1045b8de1cf12b08e958a32ef3184

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;



            // scene

            var scene = new THREE.Scene();

            //var ambient = new THREE.AmbientLight(0x101030);
            //// addTrace?
            //scene.add(ambient);

            // should jsc package c# source code along here for code lense like peeking?
            new THREE.AmbientLight(0x101030).AttachTo(scene);

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            // why is idl showing 110?
            var light = new THREE.DirectionalLight(0xffffff, 1.0);
            //var light = new THREE.DirectionalLight(0xffffff, 1.0);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            light.position.copy(lightOffset);

            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;

            xlight.shadowCameraVisible = true;

            light.AttachTo(scene);





            {

                var planeGeometry = new THREE.CubeGeometry(512, 512, 1);

                var plane = new THREE.Mesh(
                    planeGeometry,
                    material: new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
                );

                plane.receiveShadow = true;


                var ZeFloor = new THREE.Object3D();
                plane.AttachTo(ZeFloor);

                ZeFloor.rotation.x = -Math.PI / 2;
                ZeFloor.scale.set(10, 10, 10);

                ZeFloor.AttachTo(scene);
            }




            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            renderer.shadowMapEnabled = true;
            renderer.shadowMapType = THREE.PCFSoftShadowMap;

            //var mouseX = 0;
            //var mouseY = 0;
            //var st = new Stopwatch();
            //st.Start();


            //Native.window.document.onmousemove +=
            //    e =>
            //    {
            //        mouseX = e.CursorX - Native.window.Width / 2;
            //        mouseY = e.CursorY - Native.window.Height / 2;
            //    };

            var camera = new THREE.PerspectiveCamera(
                //40,
                20,
                //10,

                Native.window.aspect, 2,

                // how far out do we want to zoom?
                200000
                //9000
                );
            camera.position.set(-1200, 800, -3200);

            camera.AttachTo(scene);

            var controls = new THREE.OrbitControls(camera, renderer.domElement);

            Native.window.onframe +=
                delegate
                {

                    //oo.WithEach(
                    //    x =>
                    //        x.rotation.y = (st.ElapsedMilliseconds + mouseX * 100) * 0.00001
                    //);


                    //camera.position.x += (mouseX - camera.position.x) * .05;
                    //camera.position.y += (-mouseY - camera.position.y) * .05;

                    //camera.lookAt(scene.position);

                    controls.update();
                    camera.position = controls.center.clone();

                    renderer.render(scene, camera);
                };

            Native.window.onresize +=
                delegate
                {
                    camera.aspect = window.aspect;
                    camera.updateProjectionMatrix();

                    renderer.setSize(window.Width, window.Height);

                };
            #endregion

            #region Comanche
            new Comanche().Source.Task.ContinueWithResult(
                Comanche =>
                {

                    Comanche.position.y = 200;

                    //dae.position.z = 280;

                    Comanche.AttachTo(scene);

                    //scene.add(dae);
                    oo.Add(Comanche);

                    // wont do it
                    //dae.castShadow = true;

                    // http://stackoverflow.com/questions/15492857/any-way-to-get-a-bounding-box-from-a-three-js-object3d
                    //var helper = new THREE.BoundingBoxHelper(dae, 0xff0000);
                    //helper.update();
                    //// If you want a visible bounding box
                    //scene.add(helper);

                    Comanche.children[0].children[0].children.WithEach(x => x.castShadow = true);


                    // the rotors?
                    Comanche.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


                    Comanche.scale.set(0.5, 0.5, 0.5);
                    //helper.scale.set(0.5, 0.5, 0.5);

                    var sw = Stopwatch.StartNew();

                    Native.window.onframe += delegate
                    {
                        //dae.children[0].children[0].children.Last().al
                        //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
                        //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
                        //rotation.y = sw.ElapsedMilliseconds * 0.01;

                        Comanche.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.001;

                        //dae.children[0].children[0].children.Last().app
                    };
                }
            );
            #endregion


            //#region ZeProperties
            //var ze = new ZeProperties();

            //ze.Show();
            //ze.treeView1.Nodes.Clear();

            //ze.Add(() => renderer);
            //ze.Add(() => controls);
            //ze.Add(() => scene);
            //ze.Left = 0;
            //#endregion

            //f.treeView1.Nodes.Add("controls : " + typeof(THREE.OrbitControls)).Tag = controls;


        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // X:\jsc.svn\examples\actionscript\synergy\Flare3DMeetsStarlingExperiment\Flare3DMeetsStarlingExperiment\ApplicationSprite.cs
            // X:\jsc.svn\examples\javascript\WebGL\WebGLGalaxyS\WebGLGalaxyS\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140801
            // jsc, when can we have compiled collada asssets?
            // svg we have why not collada..
            // https://3dwarehouse.sketchup.com/model.html?id=b3bdb20081c023accbd2ad75d6ff6a24
            // https://3dwarehouse.sketchup.com/collection.html?id=982aafab70c9aba140c287facf4f3262


            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x303030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer 
            var renderer = new THREE.WebGLRenderer(

                new
            {
                antialias = true,
                alpha = true,
                preserveDrawingBuffer = true
            }
            );

            // https://github.com/mrdoob/three.js/issues/3836
            //renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            var canvas = (IHTMLCanvas)renderer.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();


            #region onmousedown
            canvas.onmousedown +=
                e =>
                {

                    if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                    {
                        canvas.requestFullscreen();
                    }
                    else
                    {
                        // movementX no longer works
                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };


                        e.CaptureMouse();
                    }

                };
            #endregion

            canvas.css.active.style.cursor = IStyle.CursorEnum.move;


            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            canvas.onmousemove +=
                e =>
                {
                    var pointerLock = canvas == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion
            var z = camera.position.z;

            #region onmousewheel
            canvas.onmousewheel +=
                e =>
                {
                    //camera.position.z = 1.5;

                    // min max. shall adjust speed also!
                    // max 4.0
                    // min 0.6
                    z -= 10.0 * e.WheelDirection;

                    //camera.position.z = 400;
                    z = z.Max(200).Min(500);

                    //Native.document.title = new { z }.ToString();

                };
            #endregion


            Native.window.onframe +=
                e =>
            {
                renderer.clear();

                camera.aspect = canvas.aspect;
                camera.updateProjectionMatrix();

                camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                camera.lookAt(scene.position);

                renderer.render(scene, camera);


            };

            Native.window.onresize +=
                delegate
            {
                if (canvas.parentNode == Native.document.body)
                {
                    renderer.setSize(window.Width, window.Height);
                }

            };
            #endregion

            new galaxyS().Source.Task.ContinueWithResult(
                   dae =>
                    {
                        //dae.scale.x = 30;
                        //dae.scale.y = 30;
                        //dae.scale.z = 30;
                        dae.position.z = 65;

                        dae.scale.x = 0.5;
                        dae.scale.y = 0.5;
                        dae.scale.z = 0.5;

                        //dae.position.y = -80;

                        scene.add(dae);
                        oo.Add(dae);


                    }
               );



        }
Example #30
0
        /* Source: http://www.webspaceinvader.com/2011/09/21/first-try-at-webgl/
         */


        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            var SCREEN_WIDTH  = Native.window.Width;
            var SCREEN_HEIGHT = Native.window.Height;

            //var ,stats;


            //var mesh, zmesh, geometry;

            var mouseX = 0;
            var mouseY = 0;

            var windowHalfX = SCREEN_WIDTH / 2;
            var windowHalfY = SCREEN_HEIGHT / 2;
            var lastUpdate  = new IDate().getTime();



            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

            var camera = new THREE.PerspectiveCamera(75, Native.window.aspect, 1, 100000);

            camera.position.z = 50;
            camera.updateMatrix();

            var scene = new THREE.Scene();

            // LIGHTS

            var ambient = new THREE.AmbientLight(0x222222);

            ambient.position.z = -300;
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);

            directionalLight.position.set(-1, 0, 1);
            directionalLight.position.normalize();
            scene.add(directionalLight);

            var dLight = new THREE.DirectionalLight(0xffeedd);

            dLight.position.set(1, 0, 1);
            dLight.position.normalize();
            scene.add(dLight);

            // init the WebGL renderer and append it to the Dom
            var renderer = new THREE.WebGLRenderer();

            renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
            renderer.autoClear = false;

            renderer.domElement.AttachTo(container);

            #region createScene
            Action <object, f, f, f, f> createScene = (geometry, x, y, z, b) =>
            {
                //var zmesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
                var zmesh = new THREE.Mesh(geometry);
                zmesh.position.x = x;
                zmesh.position.z = y;
                zmesh.position.y = z;
                zmesh.scale.x    = 5f;
                zmesh.scale.y    = 5f;
                zmesh.scale.z    = 5f;
                //zmesh.overdraw = true;
                zmesh.updateMatrix();
                scene.add(zmesh);
            };
            #endregion

            // message: "Unexpected token /"
            var loader = new THREE.JSONLoader();

            Action <object> callbackMale = (geometry) => { createScene(geometry, 90, 50, 0, 105); };

            loader.load(
                url: new invade().Content.src,
                callback: IFunction.OfDelegate(callbackMale)
                );

            // postprocessing



            var composer = new THREE.EffectComposer(renderer);

            var renderModel = new THREE.RenderPass(scene, camera);
            composer.addPass(renderModel);


            var effectFilm = new THREE.FilmPass(0.35, 0.50, 2048, false); //( 0.35, 0.75, 2048, false );
            effectFilm.renderToScreen = true;
            composer.addPass(effectFilm);

            #region IsDisposed
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                IsDisposed = true;

                renderer.domElement.Orphanize();
            };
            #endregion


            #region getFrametime
            Func <long> getFrametime = () =>
            {
                var now   = new IDate().getTime();
                var tdiff = (now - lastUpdate) / 1000;
                lastUpdate = now;
                return(tdiff);
            };
            #endregion

            #region render
            Action render = delegate
            {
                var delta = getFrametime();
                camera.position.x += (mouseX - camera.position.x) * .05f;
                camera.position.y += (-mouseY - camera.position.y) * .05f;
                camera.updateMatrix();

                //renderer.render( scene, camera );
                renderer.clear();
                composer.render(delta);
            };
            #endregion

            #region onmousemove
            Native.document.onmousemove +=
                e =>
            {
                mouseX = (e.CursorX - windowHalfX);
                mouseY = (e.CursorY - windowHalfY);
            };
            #endregion

            Native.window.onframe +=
                delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                render();
            };


            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                camera.aspect = Native.window.aspect;
                camera.updateProjectionMatrix();

                renderer.setSize(Native.window.Width, Native.window.Height);
            };

            Native.window.onresize +=
                delegate
            {
                AtResize();
            };

            AtResize();
            #endregion

            #region requestFullscreen
            Native.document.body.ondblclick +=
                delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                Native.document.body.requestFullscreen();
            };
            #endregion
        }
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{

			// https://chrome.google.com/webstore/detail/dglmddjmdpdbijfkoaiadbpmjampfdjh/publish-delayed


			#region ChromeTCPServer
			dynamic self = Native.self;
			dynamic self_chrome = self.chrome;
			object self_chrome_socket = self_chrome.socket;

			if (self_chrome_socket != null)
			{
				#region AtFormCreated
				FormStyler.AtFormCreated =
					 ss =>
				 {
					 ss.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

					 // this is working?
					 var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(ss.Context.GetHTMLTarget());
				 };
				#endregion

				chrome.Notification.DefaultTitle = "Heat Zeeker";
				chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Promotion3D_iso1_tiltshift_128().src;

				ChromeTCPServer.TheServerWithStyledForm.Invoke(
					AppSource.Text,
					AtFormCreated: FormStyler.AtFormCreated
				);

				return;
			}
			#endregion


			Native.body.style.margin = "0px";
			Native.body.style.overflow = IStyle.OverflowEnum.hidden;

			// jsc, add THREE
			// ... ok.

			// X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs



            // this is not isometric.
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151112
			var camera = new THREE.OrthographicCamera(
				Native.window.Width / -2, Native.window.Width / 2,
				Native.window.Height / 2, Native.window.Height / -2
				,
				// if we change these values what will change?
				-1000, 1000
				);
			camera.position.x = 200;
			camera.position.y = 100;
			camera.position.z = 200;

			var scene = new THREE.Scene();

			// Grid

			var size = 600;
			var step = 50;


			Func<double> random = new Random().NextDouble;


			// how do I add a new ground box?
			{
				var geometry = new THREE.BoxGeometry(size * 2, 2, size * 2);
				var material = new THREE.MeshLambertMaterial(new
				{
					color = 0xB27D51
					//                                                     , shading = THREE.FlatShading, overdraw = 0.5
				});

				{
					var cube = new THREE.Mesh(geometry, material);


					// why cant we get the shadows??
					cube.receiveShadow = true;


					cube.scale.y = Math.Floor(random() * 2 + 1);

					cube.position.x = 0;
					//cube.position.y = (cube.scale.y * 50) / 2;
					cube.position.y = -2;
					cube.position.z = 0;

					scene.add(cube);

				}
			}


			{
				var geometry = new THREE.Geometry();

				for (var i = -size; i <= size; i += step)
				{

					((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(-size, 0, i));
					((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(size, 0, i));

					((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(i, 0, -size));
					((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(i, 0, size));

				}

				var material = new THREE.LineBasicMaterial(new { color = 0, opacity = 0.2 });

				var line = new THREE.Line(geometry, material, mode: THREE.LinePieces);
				scene.add(line);
			}



			var interactiveObjects = new List<THREE.Object3D>();

			#region Cubes
			{

				for (var i = 0; i < 8; i++)
				{
					new HZBunker().Source.Task.ContinueWithResult(
						cube =>
								{
									// https://github.com/mrdoob/three.js/issues/1285
									//cube.children.WithEach(c => c.castShadow = true);

									//cube.traverse(
									//    new Action<THREE.Object3D>(
									//        child =>
									//                {
									//                    // does it work? do we need it?
									//                    //if (child is THREE.Mesh)
									//                    child.castShadow = true;
									//                    child.receiveShadow = true;

									//                }
									//    )
									//);

									// um can edit and continue insert code going back in time?
									cube.scale.x = 2.0;
									cube.scale.y = 2.0;
									cube.scale.z = 2.0;

									//cube.castShadow = true;
									//dae.receiveShadow = true;

									cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
									//cube.position.y = (cube.scale.y * 50) / 2;
									cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

									scene.add(cube);
									interactiveObjects.Add(cube);
								}
					);


					new HZWaterTower().Source.Task.ContinueWithResult(
						cube =>
						{
							// https://github.com/mrdoob/three.js/issues/1285
							// https://github.com/mrdoob/three.js/issues/1285
							//cube.children.WithEach(c => c.castShadow = true);
							// http://stackoverflow.com/questions/15906248/three-js-objloader-obj-model-not-casting-shadows


							// http://stackoverflow.com/questions/22895120/imported-3d-objects-are-not-casting-shadows-with-three-js
							//cube.traverse(
							//    new Action<THREE.Object3D>(
							//        child =>
							//        {
							//            // does it work? do we need it?
							//            //if (child is THREE.Mesh)
							//            child.castShadow = true;
							//            child.receiveShadow = true;

							//        }
							//    )
							//);

							// um can edit and continue insert code going back in time?
							cube.scale.x = 2.0;
							cube.scale.y = 2.0;
							cube.scale.z = 2.0;

							//cube.castShadow = true;
							//dae.receiveShadow = true;

							cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
							//cube.position.y = (cube.scale.y * 50) / 2;
							cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

							scene.add(cube);
							interactiveObjects.Add(cube);
						}
					);

					new HZCannon().Source.Task.ContinueWithResult(
						cube =>
						{
							// https://github.com/mrdoob/three.js/issues/1285
							//cube.children.WithEach(c => c.castShadow = true);

							//cube.traverse(
							//    new Action<THREE.Object3D>(
							//        child =>
							//                {
							//                    // does it work? do we need it?
							//                    //if (child is THREE.Mesh)
							//                    child.castShadow = true;
							//                    child.receiveShadow = true;

							//                }
							//    )
							//);

							// um can edit and continue insert code going back in time?
							cube.scale.x = 2.0;
							cube.scale.y = 2.0;
							cube.scale.z = 2.0;



							//cube.castShadow = true;
							//dae.receiveShadow = true;

							cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
							//cube.position.y = (cube.scale.y * 50) / 2;
							cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



							// if i want to rotate, how do I do it?
							//cube.rotation.z = random() + Math.PI;
							//cube.rotation.x = random() + Math.PI;
							cube.rotation.y = random() * Math.PI * 2;


							scene.add(cube);
							interactiveObjects.Add(cube);
						}
					);



				}
			}
			#endregion

			// we need expression evaluator with intellisense for live debugging sessions
			#region  Lights

			var ambientLight = new THREE.AmbientLight((int)(random() * 0x10));
			scene.add(ambientLight);



			// can we get our shadows?
			{
				var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff), 0.5);

				directionalLight.position.x = random() - 0.5;
				directionalLight.position.y = 400;
				directionalLight.position.z = random() - 0.5;
				directionalLight.position.normalize();
				scene.add(directionalLight);
			}

			{
				var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff), 0.5);
				directionalLight.position.x = random() - 0.5;
				directionalLight.position.y = 400;
				directionalLight.position.z = random() - 0.5;
				directionalLight.position.normalize();
				scene.add(directionalLight);
			}
			#endregion


			//var renderer = new THREE.CanvasRenderer();
			var renderer = new THREE.WebGLRenderer();
			renderer.shadowMapEnabled = true;

			// background-color: #B27D51;
			renderer.setClearColor(0xB27D51);
			//renderer.setSize(
			//    Native.window.Width , 
			//    Native.window.Height * 10
			//    );
			renderer.setSize();

			renderer.domElement.AttachToDocument();

			Native.window.onresize +=
				delegate
			{
				camera.left = Native.window.Width / -2;
				camera.right = Native.window.Width / 2;
				camera.top = Native.window.Height / 2;
				camera.bottom = Native.window.Height / -2;

				camera.updateProjectionMatrix();

				renderer.setSize();
			};

			//window.addEventListener( 'resize', onWindowResize, false );


			//#region Comanche
			//new Comanche().Source.Task.ContinueWithResult(
			//    Comanche =>
			//    {

			//        Comanche.position.y = 200;

			//        //dae.position.z = 280;

			//        Comanche.AttachTo(scene);

			//        //scene.add(dae);
			//        //oo.Add(Comanche);

			//        // wont do it
			//        //dae.castShadow = true;

			//        // http://stackoverflow.com/questions/15492857/any-way-to-get-a-bounding-box-from-a-three-js-object3d
			//        //var helper = new THREE.BoundingBoxHelper(dae, 0xff0000);
			//        //helper.update();
			//        //// If you want a visible bounding box
			//        //scene.add(helper);

			//        Comanche.children[0].children[0].children.WithEach(x => x.castShadow = true);


			//        // the rotors?
			//        Comanche.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


			//        Comanche.scale.set(0.5, 0.5, 0.5);
			//        //helper.scale.set(0.5, 0.5, 0.5);

			//        var sw = Stopwatch.StartNew();

			//        Native.window.onframe += delegate
			//        {
			//            //dae.children[0].children[0].children.Last().al
			//            //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
			//            //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
			//            //rotation.y = sw.ElapsedMilliseconds * 0.01;

			//            Comanche.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.001;

			//            //dae.children[0].children[0].children.Last().app
			//        };
			//    }
			//);
			//#endregion


			//#region ee
			//// X:\jsc.svn\examples\javascript\forms\NumericTextBox\NumericTextBox\ApplicationControl.cs
			//// can we restile the window as the pin window in IDE?
			//var ee = new Form { Left = 0, StartPosition = FormStartPosition.Manual };
			//var ee_camera_y = new TextBox { Dock = DockStyle.Fill, Text = camera.position.y + "" }.AttachTo(ee);
			////ee.AutoSize = AutoSizeMode.

			////ee.ClientSize = new System.Drawing.Size(ee_camera_y.Width, ee_camera_y.Height);
			//ee.ClientSize = new System.Drawing.Size(200, 24);

			//ee.Show();

			////ee_camera_y.
			//ee_camera_y.TextChanged += delegate
			//{
			//    camera.position.y = double.Parse(ee_camera_y.Text);
			//};
			//#endregion

			var s = Stopwatch.StartNew();
			var controls = new THREE.OrbitControls(camera, renderer.domElement);

			// http://stackoverflow.com/questions/26497903/nested-webglrendertargets-in-three-js
			//   var effect = new THREE.OculusRiftEffect(
			//renderer, new
			//{
			//    worldScale = 100,

			//           //HMD
			//       }
			//);

			//   effect.setSize(1920, 1080);

			Native.window.onframe +=
				e =>
				{
					// jsc, when can we have the edit and continue already?
					//var timer = s.ElapsedMilliseconds * 0.1;
					//var timer = s.ElapsedMilliseconds * 0.0001;

					//camera.position.x = Math.Cos(timer) * 200;
					//camera.position.z = Math.Sin(timer) * 200;


					// camera.position.z = 200;
					//camera.position.y = 100;
					//camera.position.y = Math.Sin(timer * 0.1) * 200;

					controls.update();
					camera.position = controls.center.clone();

					renderer.render(scene, camera);
					//effect.render(scene, camera);
				};

			//var ze = new ZeProperties();

			//ze.Show();
			//ze.treeView1.Nodes.Clear();

			//ze.Add(() => renderer);
			////ze.Add(() => controls);
			//ze.Add(() => scene);
			//ze.Left = 0;

			// view-source:http://mrdoob.github.io/three.js/examples/webgl_interactive_voxelpainter.html
			//var mouse2D = new THREE.Vector3(0, 10000, 0.5);

			//renderer.domElement.onclick +=
			//    e =>
			//    {
			//        e.preventDefault();

			//        mouse2D.x = (e.CursorX / (double)Native.window.Width) * 2 - 1;
			//        mouse2D.y = -(e.CursorY / (double)Native.window.Height) * 2 + 1;

			//        var vector = new THREE.Vector3(
			//              (e.CursorX / (double)Native.window.Width) * 2 - 1,
			//              -(e.CursorY / (double)Native.window.Height) * 2 + 1,
			//             0.5);


			//        // X:\jsc.svn\examples\javascript\WebGL\WebGLInteractiveCubes\WebGLInteractiveCubes\Application.cs
			//        var projector = new THREE.Projector();
			//        projector.unprojectVector(vector, camera);

			//        // http://stackoverflow.com/questions/18553209/orthographic-camera-and-selecting-objects-with-raycast
			//        // http://stackoverflow.com/questions/20361776/orthographic-camera-and-pickingray
			//        // view-source:http://stemkoski.github.io/Three.js/Mouse-Click.html
			//        // http://stackoverflow.com/questions/11921033/projector-and-ray-with-orthographiccamera

			//        // use picking ray since it's an orthographic camera
			//        // doesnt fkin work ???
			//        //var raycaster = projector.pickingRay(vector, camera);

			//        var raycaster = projector.pickingRay(mouse2D.clone(), camera);

			//        //var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
			//        var intersects = raycaster.intersectObjects(interactiveObjects.ToArray());

			//        // https://github.com/mrdoob/three.js/issues/599
			//        Native.document.title = new { intersects.Length }.ToString();
			//    };
		}
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();

            Native.window.onframe +=
                delegate
                {

                    oo.WithEach(
                        x =>
                            x.rotation.y = st.ElapsedMilliseconds * 0.001
                    );


                    camera.position.x += (mouseX - camera.position.x) * .05;
                    camera.position.y += (-mouseY - camera.position.y) * .05;

                    camera.lookAt(scene.position);

                    renderer.render(scene, camera);


                };

            Native.window.onresize +=
                delegate
                {
                    camera.aspect = window.aspect;
                    camera.updateProjectionMatrix();

                    renderer.setSize(window.Width, window.Height);

                };
            #endregion


            var ref0 = new TexturesImages();

            //var texture = new THREE.Texture(
            //    //new HTML.Images.FromAssets.ash_uvgrid01()
            //    //new HTML.Images.FromAssets.texture_palm()
            //           new TLC200_Side_89pc()
            //      );
            //texture.needsUpdate = true;

            // X:\jsc.svn\examples\javascript\WebGL\WebGLMTLExperiment\WebGLMTLExperiment\Application.cs

            var loader = new THREE.OBJMTLLoader();
            loader.load(
                "assets/WebGLOBJToyota/LX570_2008.obj",
                "assets/WebGLOBJToyota/LX570_2008.mtl",
                     new Action<THREE.Object3D>(
                    o =>
                    {
                        Console.WriteLine("onload " + new { o });

                        // need to use
                        // Toyota Land Cruiser 200 Series aka Lexus LX 570_2008.mtl
                        // http://pages.cs.wisc.edu/~lizy/mrdoob-three.js-ef5f05d/examples/webgl_loader_obj_mtl.html

                        
                        o.scale = new THREE.Vector3(40, 40, 40);

                        o.position.y = -80;
                        scene.add(o);
                        oo.Add(o);
                    }
                ),
                new Action<object>(
                    o =>
                    {
                        Console.WriteLine("progress " + new { o });
                    }
                ),

                 new Action<object>(
                    o =>
                    {
                        Console.WriteLine("error " + new { o });
                    }
                 )
            );


        }
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{
			// http://www.doingbusiness.org/data/exploreeconomies/puerto-rico/starting-a-business
			// http://www.doingbusiness.org/data/exploretopics/starting-a-business

			// X:\jsc.svn\examples\javascript\svg\DEAGELForecast\DEAGELForecast\Application.cs
			// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201410/20141028

			// http://www.thecommonsenseshow.com/2014/10/23/the-target-date-for-americas-depopulation-has-been-set/

			// would ScriptCoreLib be able to 
			// play navigator if we also
			// have the role of AppWindow or Android Widget Service?


			// if we are running in a SYSTEM account
			// the chrome no-sandbox only allows software renderer
			// where we get 1 frame per sec.


			// on older systems we may not get GL_OES_standard_derivatives 
			// http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app
			// 			( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
			// or that system is just old as hell


			// http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app

			//http://thematicmapping.org/playground/webgl/earth/
			// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222


			// Earth params
			var radius = 0.5;

			//var segments = 32;
			var segments = 128;
			var rotation = 6;

			var scene = new THREE.Scene();

			var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000);
			camera.position.z = 1.5;

			var renderer = new THREE.WebGLRenderer(
				   new
				   {
					   // http://stackoverflow.com/questions/20495302/transparent-background-with-three-js
					   alpha = true,
					   preserveDrawingBuffer = true
				   }

				);
			renderer.setSize();
			//renderer.setClearColor(
			scene.add(new THREE.AmbientLight(0x333333));


			var light = new THREE.DirectionalLight(0xffffff, 1);
			light.position.set(5, 3, 5);
			scene.add(light);






			#region sphere
			var sphere = new THREE.Mesh(
					new THREE.SphereGeometry(radius, segments, segments),
					new THREE.MeshPhongMaterial(
							new
							{
								map = new THREE.Texture().With(

									async s =>
									{
										//0:75ms event: _2_no_clouds_4k_low view-source:36543
										//Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1
										//Application Cache Progress event (2 of 2)  192.168.1.72/:1
										//Application Cache Cached event 192.168.1.72/:1
										//1:1018ms event: _2_no_clouds_4k_low done view-source:36543
										//1:1019ms event: _2_no_clouds_4k view-source:36543
										//event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995
										//1:16445ms event: _2_no_clouds_4k done 

										// ~ tilde to open css editor?




										Console.WriteLine("event: _2_no_clouds_4k_low");
										//s.image = await new _2_no_clouds_4k_low();
										s.image = await new _2_no_clouds_DEAGEL_4k_low().async.oncomplete;
										// http://www.deagel.com/
										//s.image = await new _2_no_clouds_DEAGEL_CIMSS_4k_low();
										//s.image = new _2_no_clouds_4k_low();
										//await s.image;

										s.needsUpdate = true;
										Console.WriteLine("event: _2_no_clouds_4k_low done");

                                        //await 20000;

                                        //Console.WriteLine("event: _2_no_clouds_4k");
                                        s.image = await new _2_no_clouds_4k();
                                        s.needsUpdate = true;
                                        //Console.WriteLine("event: _2_no_clouds_4k done");
                                    }
								),


								bumpMap = THREE.ImageUtils.loadTexture(
									new elev_bump_4k().src
								//new elev_bump_4k_low().src
								),


								// applies onyl to shaders to create the shadow
								bumpScale = 0.005,

								specularMap = new THREE.Texture().With(
									async s =>
									{
										Console.WriteLine("event: water_4k_low");
										s.image = await new water_4k_low().async.oncomplete;
										s.needsUpdate = true;
										Console.WriteLine("event: water_4k_low done");

										await Task.Delay(20000);

										Console.WriteLine("event: water_4k");
										s.image = await new water_4k().async.oncomplete;
										s.needsUpdate = true;
										Console.WriteLine("event: water_4k done");
									}
								),


								//specular =    new THREE.Color("grey")								
								specular = new THREE.Color(0xa0a0a0)
							})
				);
			#endregion

			// http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane


			sphere.rotation.y = rotation;
			scene.add(sphere);


			#region clouds
			var clouds = new THREE.Mesh(
					new THREE.SphereGeometry(
						//radius + 0.003,
						radius + 0.006,
						segments, segments),
					new THREE.MeshPhongMaterial(
						new
						{
							//map = THREE.ImageUtils.loadTexture(
							//    //new fair_clouds_4k().src
							//    new fair_clouds_4k_low().src
							//    ),


							map = new THREE.Texture().With(
								async s =>
								{
									Console.WriteLine("event: fair_clouds_4k_low");
									s.image = await new fair_clouds_4k_low().async.oncomplete;
									s.needsUpdate = true;
									Console.WriteLine("event: fair_clouds_4k_low done");

                                    await Task.Delay(20000);

									Console.WriteLine("event: fair_clouds_4k");
									s.image = await new fair_clouds_4k().async.oncomplete;
									s.needsUpdate = true;
									Console.WriteLine("event: fair_clouds_4k done");
								}
							),


							transparent = true
						})
				);
			clouds.rotation.y = rotation;
			scene.add(clouds);
			#endregion



			// X:\jsc.svn\examples\javascript\chrome\apps\ChromeEarth\ChromeEarth\Application.cs
			// X:\jsc.svn\examples\javascript\canvas\ConvertBlackToAlpha\ConvertBlackToAlpha\Application.cs
			// hidden for alpha AppWindows
			//#if FBACKGROUND

			#region galaxy_starfield
			new THREE.Texture().With(
				async s =>
				{
					var i = new HTML.Images.FromAssets.galaxy_starfield();

					var bytes = await i.async.bytes;

					for (int ii = 0; ii < bytes.Length; ii += 4)
					{

						bytes[ii + 3] = (byte)(bytes[ii + 0]);

						bytes[ii + 0] = 0xff;
						bytes[ii + 1] = 0xff;
						bytes[ii + 2] = 0xff;
					}

					var c = new CanvasRenderingContext2D(i.width, i.height);

					c.bytes = bytes;

					s.image = c;
					s.needsUpdate = true;

					var stars_material = new THREE.MeshBasicMaterial(
							new
							{
								//map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src),
								map = s,
								side = THREE.BackSide,
								transparent = true
							});


					var stars = new THREE.Mesh(
							new THREE.SphereGeometry(90, 64, 64),
						   stars_material
						);

					// http://stackoverflow.com/questions/8502150/three-js-how-can-i-dynamically-change-objects-opacity
					//(stars_material as dynamic).opacity = 0.5;


					scene.add(stars);
				}
		   );
			#endregion



			//#endif


			//var controls = new THREE.TrackballControls(camera);
			//Native.document.body.style.margin = "0";
			//Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;

			this.canvas = (IHTMLCanvas)renderer.domElement;

			//renderer.domElement.AttachToDocument();
			this.canvas.AttachToDocument();
			this.canvas.style.SetLocation(0, 0);

			// jsc, what pointers do we have in store?
			this.canvas.css.style.cursor = IStyle.CursorEnum.pointer;
			this.canvas.css.active.style.cursor = IStyle.CursorEnum.move;


			var
				old = new
				{
					sphere = new
					{
						sphere.rotation.x,
						sphere.rotation.y

					},
					clouds = new
					{
						clouds.rotation.x,
						clouds.rotation.y,
					},


					CursorX = 0,
					CursorY = 0
				};




			var z = camera.position.z;


			#region sfx
			var sfx = new WebGLEarthByBjorn.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1
			{
				autobuffer = true,

				// this aint working
				//loop = true 

			};

			sfx.play();
			#endregion


			//sfx.AttachToHead();


			// http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/

			#region onmousewheel
			this.canvas.onmousewheel +=
				e =>
				{
					//camera.position.z = 1.5;

					// min max. shall adjust speed also!
					// max 4.0
					// min 0.6
					z -= 0.1 * e.WheelDirection;

					z = z.Max(0.6).Min(4.5);

					//Native.document.title = new { camera.position.z }.ToString();

				};
			#endregion


			#region onmousedown
			this.canvas.onmousedown +=
				e =>
				{
					var pointerLock = this.canvas == Native.document.pointerLockElement;

					if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
					{
						// F11 ?
						//this.canvas.requestFullscreen();
						this.canvas.requestPointerLock();
					}
					else
					{
						// movementX no longer works
						old = new
						{
							sphere = new
							{
								sphere.rotation.x,
								sphere.rotation.y

							},
							clouds = new
							{
								clouds.rotation.x,
								clouds.rotation.y,
							},


							e.CursorX,
							e.CursorY
						};

						if (pointerLock)
						{
							// skip
						}
						else
						{
							e.CaptureMouse();
						}
					}

				};
			#endregion


			canvas.css.active.style.cursor = IStyle.CursorEnum.move;


			// X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
			#region onmousemove
			this.canvas.onmousemove +=
				e =>
				{
					var pointerLock = this.canvas == Native.document.pointerLockElement;


					//Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

					if (e.MouseButton == IEvent.MouseButtonEnum.Left)
					{
						if (pointerLock)
						{
							sphere.rotation.x += 0.01 * e.movementY;
							sphere.rotation.y += 0.01 * e.movementX;

							clouds.rotation.x += 0.01 * e.movementY;
							clouds.rotation.y += 0.01 * e.movementX;
						}
						else
						{
							sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY);
							sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX);

							clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY);
							clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX);
						}


						//    Native.document.title = new { e.movementX, e.movementY }.ToString();

					}

				};
			#endregion


			// could we 
			#region onframe
			Native.window.onframe +=
				e =>
				{
					if (this.canvas.parentNode == null)
						return;

					camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
					camera.updateProjectionMatrix();

					camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;

					// autorotation should pause while under mouse drag?
					// the larger the vew the slower the rotation shall be
					var speed = 0.0001 * e.delay.ElapsedMilliseconds +
						0.007
						* 96.0 / canvas.clientHeight
						* 1.0 / camera.position.z;

					//Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString();
					//Native.document.title = new { speed }.ToString();


					//controls.update();
					sphere.rotation.y += speed;
					clouds.rotation.y += speed;


					renderer.render(scene, camera);
				};
			#endregion


			Native.window.onresize +=
				delegate
			{


				//if (canvas.parentNode == Native.document.body)

				// are we embedded?
				if (page != null)
					renderer.setSize();
			};

			//var ze = new ZeProperties();

			//ze.Show();
			//ze.treeView1.Nodes.Clear();

			//ze.Add(() => renderer);
			////ze.Add(() => controls);
			//ze.Add(() => scene);
			//ze.Left = 0;
			//new IStyle(this.canvas.css.before)
			//{
			//    content = "'do a middle click to maximize the earth dashboard'",

			//    left = "1em",
			//    bottom = "1em",

			//    color = "white",

			//    position = IStyle.PositionEnum.absolute
			//};
		}
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            // var THREE = { REVISION: '67' };
            Native.document.title = new { THREE.REVISION }.ToString();
            // works on IE11
            //DiagnosticsConsole.ApplicationContent.BindKeyboardToDiagnosticsConsole();


            //var fov = 40;
            var fov = 100;

            #region container
            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.backgroundColor = "#000000";
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            #endregion



            var width = Native.window.Width;
            var height = Native.window.Height;



            var scene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(
                fov,
                Native.window.aspect,
                1,
                1000
            ).AttachTo(scene);

            //camera.AttachTo(scene);
            //scene.add(camera);



            //var ambient = new THREE.AmbientLight( 0xffffff);

            //scene.add( ambient );

            var light = new THREE.DirectionalLight(0xffffff, 0.8);
            light.position.set(1, 1, 1).normalize();
            scene.add(light);

            var light2 = new THREE.DirectionalLight(0xffffff);
            light2.position.set(-1, -1, -1).normalize();
            scene.add(light2);



            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(width, height);
            renderer.domElement.AttachTo(container);

            var md2frames = new md2frames();

            //load converted md2 data

            var material = new THREE.MeshPhongMaterial(
                new
                {
                    map = THREE.ImageUtils.loadTexture(
                        new HTML.Images.FromAssets._1().src
                    ),
                    ambient = 0x999999,
                    color = 0xffffff,
                    specular = 0xffffff,
                    shininess = 25,
                    morphTargets = true
                }
            );



            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);


                renderer.setSize(Native.window.Width, Native.window.Height);

                camera.projectionMatrix.makePerspective(fov, Native.window.aspect, 1, 1100);

                //camera.aspect = Native.Window.Width / Native.Window.Height;
                //camera.updateProjectionMatrix();
            };

            Native.window.onresize +=
                delegate
                {
                    AtResize();
                };

            AtResize();
            #endregion

            new THREE.JSONLoader().load(
                new global::WebGLYomotsuMD2Model.Design.tris_md2().Content.src,
                new Action<object>(
                    geometry =>
                    {
                        var player_mesh = new THREE.MorphAnimMesh(geometry, material);

                        player_mesh.rotation.y = (float)(-Math.PI / 2);
                        player_mesh.scale.set(2, 2, 2);
                        player_mesh.castShadow = true;
                        player_mesh.receiveShadow = false;

                        #region player_motion
                        var player_motion = default(motion);
                        Action<motion> player_changeMotion = motion =>
                        {
                            player_motion = motion;

                            //    player.state = md2frames[motion][3].state;

                            var animMin = motion.min;
                            var animMax = motion.max;
                            var animFps = motion.fps;

                            player_mesh.time = 0;
                            player_mesh.duration = 1000 * ((animMax - animMin) / animFps);

                            //Console.WriteLine(
                            //    "setFrameRange " +
                            //    new
                            //    {
                            //        motion.min,
                            //        motion.max,
                            //        motion.fps
                            //    }
                            //    );

                            player_mesh.setFrameRange(animMin, animMax);
                        };

                        player_changeMotion(md2frames.stand);
                        #endregion


                        //player_mesh.att
                        scene.add(player_mesh);

                        var theta = 0;

                        //var clock = new THREE.Clock();

                        var clock = new Stopwatch();
                        clock.Start();

                        #region loop


                        Native.window.onframe += delegate
                        {
                            var delta = clock.ElapsedMilliseconds * 0.001;
                            clock.Restart();

                            var isEndFleame = (player_motion.max == player_mesh.currentKeyframe);
                            var isAction = player_motion.action;

                            var x = (isAction && !isEndFleame);

                            if (!isAction || x)
                            {

                                player_mesh.updateAnimation(1000 * delta);

                            }
                            else if (player_motion.state == "freeze")
                            {

                                //dead...

                            }
                            else
                            {

                                player_changeMotion(player_motion);

                            }


                            camera.position.x = (float)(150 * Math.Sin(theta / 2 * Math.PI / 360));
                            camera.position.y = (float)(150 * Math.Sin(theta / 2 * Math.PI / 360));
                            camera.position.z = (float)(150 * Math.Cos(theta / 2 * Math.PI / 360));

                            camera.lookAt(scene.position);

                            theta++;



                            renderer.render(scene, camera);


                        };

                        #endregion

                        #region Toolbar
                        var toolbar = new Toolbar();

                        if (page != null)
                        {
                            toolbar.Container.style.Opacity = 0.7;
                            toolbar.Container.AttachToDocument();
                            toolbar.Container.style.position = IStyle.PositionEnum.absolute;
                            toolbar.Container.style.right = "0";
                            toolbar.Container.style.bottom = "0";

                            toolbar.HideButton.onclick +=
                                    delegate
                                    {
                                        // ScriptCoreLib.Extensions
                                        toolbar.HideTarget.ToggleVisible();
                                    };


                            Action<IHTMLButton, motion> bind =
                                (btn, value) => btn.onclick += delegate { player_changeMotion(value); };

                            bind(toolbar.Stand, md2frames.stand);
                            bind(toolbar.Run, md2frames.run);
                            bind(toolbar.Attack, md2frames.attack);
                            bind(toolbar.Pain1, md2frames.pain1);
                            bind(toolbar.Pain2, md2frames.pain2);
                            bind(toolbar.Pain3, md2frames.pain3);
                            bind(toolbar.Jump, md2frames.jump);
                            bind(toolbar.Flip, md2frames.flip);
                            bind(toolbar.Salute, md2frames.salute);
                            bind(toolbar.Taunt, md2frames.taunt);
                            bind(toolbar.Wave, md2frames.wave);
                            bind(toolbar.Point, md2frames.point);
                            bind(toolbar.Crstand, md2frames.crstand);
                            bind(toolbar.Crwalk, md2frames.crwalk);
                            bind(toolbar.Crattack, md2frames.crattack);
                            bind(toolbar.Crpain, md2frames.crpain);
                            bind(toolbar.Crdeath, md2frames.crdeath);
                            bind(toolbar.Death1, md2frames.death1);
                            bind(toolbar.Death2, md2frames.death2);
                            bind(toolbar.Death3, md2frames.death3);
                        }
                        #endregion



                    }
                )
            );


            //var ze = new ZeProperties();

            //ze.Show();
            //ze.treeView1.Nodes.Clear();

            //ze.Add(() => renderer);
            ////ze.Add(() => controls);
            //ze.Add(() => scene);
            //ze.Left = 0;


        }
Example #35
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // why are the trucks black?
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae
            // what will happen if we resync THREE version from 70 to?
            Native.document.title = new { THREE.REVISION }.ToString();

            var oo = new List <THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            //var ambient = new THREE.AmbientLight(0x101030);
            var ambient = new THREE.AmbientLight(0x808080);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd, 0.7);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer
            var renderer = new THREE.WebGLRenderer(

                new
            {
                preserveDrawingBuffer = true
            }
                );

            // https://github.com/mrdoob/three.js/issues/3836
            renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            this.canvas = (IHTMLCanvas)renderer.domElement;


            var mouseX = 0;
            var mouseY = 0;
            var st     = new Stopwatch();
            st.Start();


            var controls = new THREE.OrbitControls(camera, renderer.domElement);

            Native.window.onframe +=
                delegate
            {
                renderer.clear();


                //camera.aspect = window.aspect;
                //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                //camera.aspect = canvas.aspect;


                oo.WithEach(
                    x =>
                    x.rotation.y = st.ElapsedMilliseconds * 0.0001
                    );


                controls.update();
                camera.position = controls.center.clone();

                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                if (canvas.parentNode == Native.document.body)
                {
                    renderer.setSize(window.Width, window.Height);
                }
            };
            #endregion

            new truck().Source.Task.ContinueWithResult(
                dae =>
            {
                //dae.scale.x = 30;
                //dae.scale.y = 30;
                //dae.scale.z = 30;
                dae.position.z = 65;

                dae.scale.x = 10;
                dae.scale.y = 10;
                dae.scale.z = 10;

                dae.position.y = -80;

                scene.add(dae);
                oo.Add(dae);
            }
                );

            //var ref0 = "assets/WebGLColladaExperiment/HZCannon_capture_009_04032013_192834.png";

            //new HZCannon().Source.Task.ContinueWithResult(
            //    dae =>
            //    {
            //        //dae.scale.x = 30;
            //        //dae.scale.y = 30;
            //        //dae.scale.z = 30;

            //        dae.castShadow = true;
            //        dae.receiveShadow = true;

            //        dae.scale.x = 3;
            //        dae.scale.y = 3;
            //        dae.scale.z = 3;

            //        dae.position.y = -80;

            //        scene.add(dae);
            //        oo.Add(dae);


            //    }
            //);
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // why are the trucks black?
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae
            // what will happen if we resync THREE version from 70 to?
            Native.document.title = new { THREE.REVISION }.ToString();

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            //var ambient = new THREE.AmbientLight(0x101030);
            var ambient = new THREE.AmbientLight(0x808080);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd, 0.7);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer 
            var renderer = new THREE.WebGLRenderer(

                new
                {
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836
            renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            this.canvas = (IHTMLCanvas)renderer.domElement;


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();


            var controls = new THREE.OrbitControls(camera, renderer.domElement);

            Native.window.onframe +=
                delegate
                {
                    renderer.clear();


                    //camera.aspect = window.aspect;
                    //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                    //camera.aspect = canvas.aspect;


                    oo.WithEach(
                        x =>
                            x.rotation.y = st.ElapsedMilliseconds * 0.0001
                    );


                    controls.update();
                    camera.position = controls.center.clone();

                    renderer.render(scene, camera);


                };

            Native.window.onresize +=
                delegate
                {
                    if (canvas.parentNode == Native.document.body)
                    {
                        renderer.setSize(window.Width, window.Height);
                    }

                };
            #endregion

            new truck().Source.Task.ContinueWithResult(
                   dae =>
                    {
                        //dae.scale.x = 30;
                        //dae.scale.y = 30;
                        //dae.scale.z = 30;
                        dae.position.z = 65;

                        dae.scale.x = 10;
                        dae.scale.y = 10;
                        dae.scale.z = 10;

                        dae.position.y = -80;

                        scene.add(dae);
                        oo.Add(dae);


                    }
               );

            //var ref0 = "assets/WebGLColladaExperiment/HZCannon_capture_009_04032013_192834.png";

            //new HZCannon().Source.Task.ContinueWithResult(
            //    dae =>
            //    {
            //        //dae.scale.x = 30;
            //        //dae.scale.y = 30;
            //        //dae.scale.z = 30;

            //        dae.castShadow = true;
            //        dae.receiveShadow = true;

            //        dae.scale.x = 3;
            //        dae.scale.y = 3;
            //        dae.scale.z = 3;

            //        dae.position.y = -80;

            //        scene.add(dae);
            //        oo.Add(dae);


            //    }
            //);
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://3dwarehouse.sketchup.com/model.html?id=3afce20492cb901a4fc117e4bba6a423



            // http://blogs.msdn.com/b/dotnet/archive/2014/05/09/the-net-native-tool-chain.aspx

            // http://stackoverflow.com/questions/23771022/plinq-c-net-4-5-1-vs-stream-jdk-java-8-performance
            // http://blogs.msdn.com/b/dotnet/archive/2014/04/21/sharing-code-across-platforms.aspx

            // Uncaught TypeError: Cannot read property 'nodes' of null
            // sketchup creates empty nodes
            // .//dae:scene/dae:instance_visual_scene

            // .dae download missing?
            //<scene>
            //    <instance_visual_scene url="#ID1" />

            // https://3dwarehouse.sketchup.com/model.html?id=7bf6249a031b5095ddd41159baaa3ad5
            // jsc, how to show dae?

            // Uncaught TypeError: Cannot read property 'input' of null
            // geometry: "ID690"
            //<geometry id="ID979">
            //        <mesh />
            //    </geometry>
            //    <geometry id="ID980">
            //        <mesh />
            //    </geometry>

            // X:\jsc.svn\examples\javascript\WebGL\WebGLNexus7\WebGLNexus7\Application.cs

            // X:\jsc.svn\examples\javascript\WebGL\WebGLGalaxyS\WebGLGalaxyS\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140801
            // jsc, when can we have compiled collada asssets?
            // svg we have why not collada..
            // https://3dwarehouse.sketchup.com/model.html?id=b3bdb20081c023accbd2ad75d6ff6a24
            // https://3dwarehouse.sketchup.com/collection.html?id=982aafab70c9aba140c287facf4f3262


            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x303030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer 
            var renderer = new THREE.WebGLRenderer(

                new
            {
                antialias = true,
                alpha = true,
                preserveDrawingBuffer = true
            }
            );

            // https://github.com/mrdoob/three.js/issues/3836
            //renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            var canvas = (IHTMLCanvas)renderer.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();


            canvas.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            canvas.onmousedown +=
                e =>
                {

                    if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                    {
                        canvas.requestFullscreen();
                    }
                    else
                    {
                        // movementX no longer works
                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };


                        e.CaptureMouse();
                    }

                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            canvas.onmousemove +=
                e =>
                {
                    var pointerLock = canvas == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion
            var z = camera.position.z;

            #region onmousewheel
            canvas.onmousewheel +=
                e =>
                {
                    //camera.position.z = 1.5;

                    // min max. shall adjust speed also!
                    // max 4.0
                    // min 0.6
                    z -= 10.0 * e.WheelDirection;

                    //camera.position.z = 400;
                    z = z.Max(200).Min(500);

                    //Native.document.title = new { z }.ToString();

                };
            #endregion


            Native.window.onframe +=
                e =>
                {
                    renderer.clear();

                    camera.aspect = canvas.aspect;
                    camera.updateProjectionMatrix();

                    camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                    camera.lookAt(scene.position);

                    renderer.render(scene, camera);


                };

            Native.window.onresize +=
                delegate
                {
                    if (canvas.parentNode == Native.document.body)
                    {
                        renderer.setSize(window.Width, window.Height);
                    }

                };
            #endregion

            new __AssetsLibrary__.ColladaISS().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = 65;


                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = 1.0;
                       dae.scale.y = 1.0;
                       dae.scale.z = 1.0;

                       //dae.position.y = -80;

                       scene.add(dae);
                       oo.Add(dae);


                   }
               );


            // no! why?
            Console.WriteLine("do you see it?");
            // slow to load
            // then too small!
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // "X:\opensource\github\three.js\examples\canvas_camera_orthographic.html"

            // if i type THREE, would jsc be able to add THREE package on rebuild?
            // Error	136	The type or namespace name 'THREE' could not be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs	35	26	WebGLOrthographicCamera



            // X:\jsc.svn\examples\javascript\WebGL\WebGLOrthographicCamera\WebGLOrthographicCamera\Application.cs

            var camera = new THREE.OrthographicCamera(Native.window.Width / -2, Native.window.Width / 2, Native.window.Height / 2, Native.window.Height / -2, -500, 1000);
            camera.position.x = 200;
            camera.position.y = 100;
            camera.position.z = 200;

            var scene = new THREE.Scene();

            // Grid

            var size = 500;
            var step = 50;


            Func<double> random = new Random().NextDouble;


            {
                var geometry = new THREE.Geometry();

                for (var i = -size; i <= size; i += step)
                {

                    ((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(-size, 0, i));
                    ((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(size, 0, i));

                    ((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(i, 0, -size));
                    ((IArray<THREE.Vector3>)(object)geometry.vertices).push(new THREE.Vector3(i, 0, size));

                }

                var material = new THREE.LineBasicMaterial(new { color = 0x000000, opacity = 0.2 });

                var line = new THREE.Line(geometry, material);

                line.type = THREE.LinePieces;
                scene.add(line);
            }

            #region Cubes
            {
                var geometry = new THREE.BoxGeometry(50, 50, 50);
                var material = new THREE.MeshLambertMaterial(new { color = 0xffffff, shading = THREE.FlatShading, overdraw = 0.5 });

                for (var i = 0; i < 100; i++)
                {
                    var cube = new THREE.Mesh(geometry, material);

                    cube.scale.y = Math.Floor(random() * 2 + 1);

                    cube.position.x = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;
                    cube.position.y = (cube.scale.y * 50) / 2;
                    cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;

                    scene.add(cube);

                }
            }
            #endregion


            #region  Lights

            var ambientLight = new THREE.AmbientLight((int)(random() * 0x10));
            scene.add(ambientLight);

            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff));

                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = random() - 0.5;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }

            {
                var directionalLight = new THREE.DirectionalLight((int)(random() * 0xffffff));
                directionalLight.position.x = random() - 0.5;
                directionalLight.position.y = random() - 0.5;
                directionalLight.position.z = random() - 0.5;
                directionalLight.position.normalize();
                scene.add(directionalLight);
            }
            #endregion


            //var renderer = new THREE.CanvasRenderer();
            var renderer = new THREE.WebGLRenderer();
            renderer.setClearColor(0xf0f0f0);
            //renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.setSize();

            renderer.domElement.AttachToDocument();

            //window.addEventListener( 'resize', onWindowResize, false );


            var s = Stopwatch.StartNew();

            Native.window.onframe +=
                e =>
                {
                    // jsc, when can we have the edit and continue already?
                    //var timer = s.ElapsedMilliseconds * 0.1;
                    var timer = s.ElapsedMilliseconds * 0.0001;

                    camera.position.x = Math.Cos(timer) * 200;
                    camera.position.z = Math.Sin(timer) * 200;
                    camera.lookAt(scene.position);

                    renderer.render(scene, camera);
                };

        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {

            onMouseDownPosition = new THREE.Vector2();

            //camera = new THREE.PerspectiveCamera(
            //   45,
            //   Native.window.aspect,
            //   1,
            //   1000
            //    //2000
            //   );
            //camera.position.z = 400;

            camera = new THREE.PerspectiveCamera(40, Native.window.Width / Native.window.Height, 1, 10000);
            camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
            camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
            camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
            

            scene = new THREE.Scene();
            var ambientLight = new THREE.AmbientLight(0x404040);
            scene.add(ambientLight);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            var obj = new THREE.Object3D();


            var buttomCylinder1 = new THREE.Mesh(
               new THREE.CylinderGeometry(50, 50, 50, 32),
               new THREE.MeshPhongMaterial(
                       new
                       {
                           specular = new THREE.Color(0xa0a0a0),
                           color = new THREE.Color(0xa0a0a0),
                       })
           );
            buttomCylinder1.rotation.x = - 90 * Math.PI / 180;

            //buttomCylinder1.position.x = 0;
            //buttomCylinder1.position.y = 0;
            //buttomCylinder1.position.z = 0;

            obj.add(buttomCylinder1);
            scene.add(obj);
            

            var renderer = new THREE.WebGLRenderer(
                   new
                   {
                       preserveDrawingBuffer = true
                   }

                );
            renderer.setSize(Native.window.Width, Native.window.Height);
            this.canvas = (IHTMLCanvas)renderer.domElement;
            this.canvas.AttachToDocument();
            this.canvas.style.SetLocation(0, 0);

            camera.lookAt(scene.position);
            scene.add(obj);

            //var plane = new THREE.Mesh(new THREE.Plane(1000, 1000));
            //plane.rotation.x = -90 * Math.PI / 180;
            //scene.add(plane);

            #region onmousedown
            this.canvas.onmousedown +=
                e =>
                {
                    e.preventDefault();

                    isMouseDown = true;

                    onMouseDownTheta = theta;
                    onMouseDownPhi = phi;
                    onMouseDownPosition.x = e.CursorX;
                    onMouseDownPosition.y = e.CursorY;

                };
            #endregion


            this.canvas.onmousewheel +=
                e =>
                {
                    radious -= e.WheelDirection;

                    camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                    camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
                    camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                    camera.updateMatrix();
                };

            #region onmousemove
            this.canvas.onmousemove +=
                e =>
                {
                    e.preventDefault();

                    if (isMouseDown)
                    {

                        theta = -((e.CursorX - onMouseDownPosition.x) * 0.5) + onMouseDownTheta;
                        phi = ((e.CursorX - onMouseDownPosition.y) * 0.5) + onMouseDownPhi;

                        phi = Math.Min(360, Math.Max(0, phi));

                        camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                        camera.position.y = radious * Math.Sin(phi * Math.PI / 360);
                        camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360);
                        camera.updateMatrix();

                    }


                };
            #endregion

            this.canvas.onmouseup += e =>
                {
                    e.preventDefault();

                    isMouseDown = false;

                    onMouseDownPosition.x = e.CursorX - onMouseDownPosition.x;
                    onMouseDownPosition.y = e.CursorY - onMouseDownPosition.y;
                };

            


            // could we 
            Native.window.onframe +=
                e =>
                {
                    renderer.clear();
                    camera.updateProjectionMatrix();
                    camera.lookAt(scene.position);
                    renderer.render(scene, camera);
                    
                };

            Native.window.onresize +=
                delegate
                {


                    //if (canvas.parentNode == Native.document.body)

                    // are we embedded?
                    if (page != null)
                        renderer.setSize();
                };
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page = null)
        {
            { THREE.SkinnedMesh ref0; }
            { THREE.SpeedBlendCharacter ref0; }

//			will skip DefineVersionInfoResource
//102c: 02:01:1e RewriteToAssembly error: System.NotSupportedException: Type 'xchrome.BCLImplementation.System.Net.Sockets.__TcpListener' was not completed.


			#region AtFormCreated
			FormStyler.AtFormCreated =
                 s =>
                 {
                     s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

                     // this is working?
                     var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
                 };
			#endregion

#if false
			#region ChromeTCPServer
			dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Preview().src;
                chrome.Notification.DefaultTitle = "WebGLYomotsuTPS";


                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                    AppSource.Text,
                    AtFormCreated: FormStyler.AtFormCreated
                );

                return;
            }
			#endregion
#endif

			var fov = 40;

            #region container
            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.backgroundColor = "#000000";
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            #endregion

            var player_model_objects = new THREE.Object3D();
            var player_position_x = 0.0f;
            var player_position_y = 0.0f;
            var player_position_z = 0.0f;
            var player_position_direction = 0;
            var player_camera_speed = 300;
            var player_camera_distance = 5;
            var player_camera_x = 0.0f;
            var player_camera_y = 0.0f;
            var player_camera_z = 0.0f;
            var player_motion = default(motion);

            //var width = Native.window.Width;
            //var height = Native.window.Height;

            var clock = new Stopwatch();
            clock.Start();
            //var clock = new THREE.Clock();

            var scene = new THREE.Scene();
            scene.fog = new THREE.FogExp2(0x000000, 0.05f);

            scene.add(player_model_objects);

            var camera = new THREE.PerspectiveCamera(fov,
                Native.window.aspect,
                //width / height,
                1, 1000);

            scene.add(camera);

            #region light

            var light = new THREE.DirectionalLight(0xffffff, 1.5);

            light.position.set(1, 1, 1).normalize();

            light.castShadow = true;




            scene.add(light);




            #endregion

            var md2frames = new md2frames();

            var moveState_moving = false;
            var moveState_front = false;
            var moveState_Backwards = false;
            var moveState_left = false;
            var moveState_right = false;
            var moveState_speed = .1;
            var moveState_angle = 0;

            #region move
            Action move = delegate
            {
                //            if(player.model.motion !== 'run' && player.model.state === 'stand'){

                //    changeMotion('run');

                //}

                //if(player.model.motion !== 'crwalk' && player.model.state === 'crstand'){

                //    changeMotion('crwalk');

                //}

                var speed = moveState_speed;

                //if(player.model.state === 'crstand'){speed *= .5;}

                //if(player.model.state === 'freeze') {speed *= 0;}



                var direction = moveState_angle;

                if (moveState_front && !moveState_left && !moveState_Backwards && !moveState_right) { direction += 0; }
                if (moveState_front && moveState_left && !moveState_Backwards && !moveState_right) { direction += 45; }
                if (!moveState_front && moveState_left && !moveState_Backwards && !moveState_right) { direction += 90; }
                if (!moveState_front && moveState_left && moveState_Backwards && !moveState_right) { direction += 135; }
                if (!moveState_front && !moveState_left && moveState_Backwards && !moveState_right) { direction += 180; }
                if (!moveState_front && !moveState_left && moveState_Backwards && moveState_right) { direction += 225; }
                if (!moveState_front && !moveState_left && !moveState_Backwards && moveState_right) { direction += 270; }
                if (moveState_front && !moveState_left && !moveState_Backwards && moveState_right) { direction += 315; }



                player_model_objects.rotation.y = (float)(direction * Math.PI / 180);

                player_position_x -= (float)(Math.Sin(direction * Math.PI / 180) * speed);
                player_position_z -= (float)(Math.Cos(direction * Math.PI / 180) * speed);

            };
            #endregion

            #region camera rotation


            Action rotate = delegate { };

            var pointer_x = 0f;
            var pointer_y = 0f;
            var oldPointerX = 0f;
            var oldPointerY = 0f;

            container.onmousemove +=
                e =>
                {
                    if (Native.document.pointerLockElement == container)
                    {
                        oldPointerX = 0;
                        oldPointerY = 0;
                        pointer_x = e.movementX * 0.01f;
                        pointer_y = -e.movementY * 0.01f;
                        rotate();
                        return;
                    }

                    pointer_x = (e.CursorX / Native.window.Width) * 2 - 1;
                    pointer_y = -(e.CursorY / Native.window.Height) * 2 + 1;
                    rotate();
                };


            container.onmouseup +=
              e =>
              {
                  rotate = delegate { };

                  Native.document.exitPointerLock();
              };

            container.onmousedown +=
                e =>
                {

                    oldPointerX = pointer_x;
                    oldPointerY = pointer_y;

                    rotate = delegate
                    {
                        player_camera_x += (oldPointerX - pointer_x) * player_camera_speed;
                        player_camera_y += (oldPointerY - pointer_y) * player_camera_speed;

                        if (player_camera_y > 150)
                        {
                            player_camera_y = 150;
                        }

                        if (player_camera_y < -150)
                        {
                            player_camera_y = -150;
                        }

                        moveState_angle = Convert.ToInt32(player_camera_x / 2) % 360;

                        oldPointerX = pointer_x;
                        oldPointerY = pointer_y;

                    };

                    Console.WriteLine("requestPointerLock");
                    container.requestPointerLock();
                };

            #endregion

            var renderer = new THREE.WebGLRenderer();
            //renderer.setSize(width, height);
            renderer.setSize();
            renderer.shadowMapEnabled = true;
            renderer.shadowMapSoft = true;
            renderer.domElement.AttachTo(container);




            #region create field


            var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            var planeMaterial = new THREE.MeshLambertMaterial(
                new
                {
                    map = THREE.ImageUtils.loadTexture(new HTML.Images.FromAssets.bg().src),
                    color = 0xffffff
                }
            );

            planeMaterial.map.repeat.x = 300;
            planeMaterial.map.repeat.y = 300;
            planeMaterial.map.wrapS = THREE.RepeatWrapping;
            planeMaterial.map.wrapT = THREE.RepeatWrapping;
            var plane = new THREE.Mesh(planeGeometry, planeMaterial);
            plane.castShadow = false;
            plane.receiveShadow = true;


            {

                var parent = new THREE.Object3D();
                parent.add(plane);
                parent.rotation.x = -Math.PI / 2;

                scene.add(parent);
            }

            var random = new Random();
            var meshArray = new List<THREE.Mesh>();
            var geometry = new THREE.CubeGeometry(1, 1, 1);

            for (var i = 0; i < 100; i++)
            {

                var ii = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial(
                    new
                    {
                        color = (Convert.ToInt32(0xffffff * random.NextDouble()))
                    }));
                ii.position.x = i % 2 * 5 - 2.5f;
                ii.position.y = .5f;
                ii.position.z = -1 * i * 4;
                ii.castShadow = true;
                ii.receiveShadow = true;


                meshArray.Add(ii);

                scene.add(ii);

            }
            #endregion







            //load converted md2 data

            var material = new THREE.MeshPhongMaterial(
                new
                {
                    map = THREE.ImageUtils.loadTexture(
                        new HTML.Images.FromAssets._1().src
                    ),
                    ambient = 0x999999,
                    color = 0xffffff,
                    specular = 0xffffff,
                    shininess = 25,
                    morphTargets = true
                }
            );




            var loader = new THREE.JSONLoader();

            loader.load(
                new global::WebGLYomotsuTPS.Design.droid().Content.src,
                            xgeometry =>
                            {
                                var md2meshBody = new THREE.MorphAnimMesh(xgeometry, material);

                                md2meshBody.rotation.y = (float)(-Math.PI / 2);
                                md2meshBody.scale.set(.02, .02, .02);
                                md2meshBody.position.y = .5f;
                                md2meshBody.castShadow = true;
                                md2meshBody.receiveShadow = false;

                                #region player_motion
                                Action<motion> player_changeMotion = motion =>
                                {
                                    Console.WriteLine(
                                        new { motion, md2frames.run, md2frames.stand });

                                    player_motion = motion;

                                    //    player.state = md2frames[motion][3].state;

                                    var animMin = motion.min;
                                    var animMax = motion.max;
                                    var animFps = motion.fps;

                                    md2meshBody.time = 0;
                                    md2meshBody.duration = (int)(
                                        1000 * ((animMax - animMin) / (double)animFps)
                                    );
                                    Native.document.title = new { animMin, animMax }.ToString();

                                    md2meshBody.setFrameRange(animMin, animMax);
                                };

                                player_changeMotion(md2frames.stand);
                                #endregion

                                player_model_objects.add(md2meshBody);

                                #region onkeydown
                                Native.document.onkeydown +=
                                    e =>
                                    {
                                        if (e.KeyCode == 67)
                                        {
                                            if (player_motion == md2frames.stand)
                                                player_changeMotion(md2frames.crstand);
                                            else if (player_motion == md2frames.crstand)
                                                player_changeMotion(md2frames.stand);

                                        }
                                        else if (e.KeyCode == 87)
                                        {
                                            moveState_front = true;
                                            moveState_Backwards = false;
                                        }
                                        else if (e.KeyCode == 83)
                                        {
                                            moveState_front = false;
                                            moveState_Backwards = true;
                                        }
                                        else if (e.KeyCode == 65)
                                        {
                                            moveState_left = true;
                                            moveState_right = false;
                                        }
                                        else if (e.KeyCode == 68)
                                        {
                                            moveState_left = false;
                                            moveState_right = true;
                                        }

                                        var isStand = player_motion == md2frames.stand;
                                        Console.WriteLine(
                                            new { e.KeyCode, moveState_front, moveState_Backwards, isStand }
                                            );

                                        if (moveState_front || moveState_Backwards || moveState_left || moveState_right)
                                            if (player_motion == md2frames.stand)
                                                player_changeMotion(md2frames.run);
                                            else if (player_motion == md2frames.crstand)
                                                player_changeMotion(md2frames.crwalk);
                                    };
                                #endregion

                                #region onkeyup
                                Native.document.onkeyup +=
                                    e =>
                                    {
                                        if (e.KeyCode == 87)
                                        {
                                            moveState_front = false;
                                        }
                                        else if (e.KeyCode == 83)
                                        {
                                            moveState_Backwards = false;
                                        }
                                        else if (e.KeyCode == 65)
                                        {
                                            moveState_left = false;
                                        }
                                        else if (e.KeyCode == 68)
                                        {
                                            moveState_right = false;
                                        }

                                    };
                                #endregion




                                #region loop


                                Native.window.onframe += delegate
                                {
                                    if (moveState_front || moveState_Backwards || moveState_left || moveState_right)
                                        move();
                                    else
                                        if (player_motion == md2frames.run)
                                        player_changeMotion(md2frames.stand);
                                    else if (player_motion == md2frames.crwalk)
                                        player_changeMotion(md2frames.crstand);



                                    player_model_objects.position.x = player_position_x;
                                    player_model_objects.position.y = player_position_y;
                                    player_model_objects.position.z = player_position_z;

                                    // camera rotate x
                                    camera.position.x = (float)(player_position_x + player_camera_distance * Math.Sin((player_camera_x) * Math.PI / 360.0));
                                    camera.position.z = (float)(player_position_z + player_camera_distance * Math.Cos((player_camera_x) * Math.PI / 360.0));

                                    //camera rotate y
                                    //camera.position.x = player.position.x + player.camera.distance * Math.cos( (player.camera.y) * Math.PI / 360 );
                                    camera.position.y = (float)(player_position_y + player_camera_distance * Math.Sin((player_camera_y) * Math.PI / 360.0));
                                    //camera.position.z = player.position.z + player.camera.distance * Math.cos( (player.camera.y) * Math.PI / 360 );

                                    camera.position.y += 1;
                                    //console.log(camera.position.z)

                                    var vec3 = new THREE.Vector3(player_position_x, player_position_y, player_position_z);

                                    camera.lookAt(vec3);



                                    #region model animation

                                    var delta = clock.ElapsedMilliseconds * 0.001;
                                    clock.Restart();

                                    var isEndFleame = (player_motion.max == md2meshBody.currentKeyframe);
                                    var isAction = player_motion.action;

                                    var x = (isAction && !isEndFleame);

                                    if (!isAction || x)
                                    {
                                        md2meshBody.updateAnimation(1000 * delta);
                                    }
                                    else if (player_motion.state == "freeze")
                                    {
                                        //dead...
                                    }
                                    else
                                    {
                                        player_changeMotion(player_motion);
                                    }
                                    #endregion

                                    renderer.render(scene, camera);


                                };

                                #endregion





                                #region AtResize
                                Action AtResize = delegate
                                {
                                    container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);


                                    renderer.setSize(Native.window.Width, Native.window.Height);

                                    camera.projectionMatrix.makePerspective(fov, Native.window.aspect, 1, 1100);

                                    //camera.aspect = Native.Window.Width / Native.Window.Height;
                                    //camera.updateProjectionMatrix();
                                };

                                Native.window.onresize +=
                                    delegate
                                {
                                    AtResize();
                                };

                                AtResize();
                                #endregion

                                #region requestFullscreen
                                Native.document.body.ondblclick +=
                                    delegate
                                {
                                    if (IsDisposed)
                                        return;

                                    // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                                    Native.document.body.requestFullscreen();

                                    //AtResize();
                                };
                                #endregion


                            }
            );





        }
        // http://youtu.be/Lo1IU8UAutE
        // 60hz 2160 4K!

        // The equirectangular projection was used in map creation since it was invented around 100 A.D. by Marinus of Tyre. 

        //        C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hzsky.png" "/sdcard/oculus/360photos/"
        //1533 KB/s(3865902 bytes in 2.461s)

        //C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hznosky.png" "/sdcard/oculus/360photos/"
        //1556 KB/s(2714294 bytes in 1.703s)

        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hz2048c3840x2160.png" "/sdcard/oculus/360photos/"



        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809/chrome360hz

        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809

        // the eye nor the display will be able to do any stereo
        // until tech is near matrix capability. 2019?

        // cubemap can be used for all long range scenes
        // http://www.imdb.com/title/tt0112111/?ref_=nv_sr_1


        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150808/cubemapcamera
        // subst a: s:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360HZ\Chrome360HZ\bin\Debug\staging\Chrome360HZ.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360HZ\Chrome360HZ\bin\Debug\staging\Chrome360HZ.Application\web

        // ColladaLoader: Empty or non-existing file (assets/Chrome360HZ/S6Edge.dae)

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //FormStyler.AtFormCreated =
            //s =>
            //{
            //    s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

            //    //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            //    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



            //    s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
            //    //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            //};

#if AsWEBSERVER
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                // if we run as a server. we can open up on android.

                //chrome.Notification.DefaultTitle = "Nexus7";
                //chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text
                //, AtFormCreated: FormStyler.AtFormCreated

                //AtFormConstructor:
                //    f =>
                //    {
                //        //arg[0] is typeof System.Int32
                //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                //    }
                );
                return;
            }
            #endregion
#else

            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    //chrome.runtime.UpdateAvailable += delegate
                    //{
                    //    new chrome.Notification(title: "UpdateAvailable");

                    //};

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "Chrome360HZ");

                        // https://developer.chrome.com/apps/app_window#type-CreateWindowOptions
                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: new
                               {
                                   alwaysOnTop = true,
                                   visibleOnAllWorkspaces = true
                               }
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion


#endif

            //const int size = 128;
            //const int size = 256; // 6 faces, 12KB
            //const int size = 512; // 6 faces, ?

            // WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled.

            //const int size = 720; // 6 faces, ?
            //const int size = 1024; // 6 faces, ?
            //const int size = 1024; // 6 faces, ?
            //const int cubefacesize = 2048; // 6 faces, ?
            const int cubefacesize = 512; // 6 faces, ?



            var uizoom = 0.05;

            var far = 0xfffff;

            Native.css.style.backgroundColor = "blue";
            Native.css.style.overflow = IStyle.OverflowEnum.hidden;

            Native.body.Clear();

            new IHTMLPre { "can we stream it into VR, shadertoy, youtube 360, youtube stereo yet?" }.AttachToDocument();


            var sw = Stopwatch.StartNew();

            var pause = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.checkbox, title = "pause" }.AttachToDocument();


            pause.onchange += delegate
            {

                if (pause.@checked)
                    sw.Stop();
                else
                    sw.Start();


            };

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;


            // what about physics and that portal rendering?

            // if we are running as a chrome web server, we may also be opened as android ndk webview app
            //var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: window.aspect, near: 1, far: 2000);
            // once we update source
            // save the source
            // manually recompile 
            //cameraPX.position.z = 400;

            //// the camera should be close enough for the object to float off the FOV of PX
            //cameraPX.position.z = 200;

            // scene
            // can we make the 3D object orbit around us ?
            // and
            // stream it to vr?
            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x303030);
            scene.add(ambient);

            // should we fix jsc to do a more correct IDL?
            //var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
            //directionalLight.position.set(0, 0, 1);
            //scene.add(directionalLight);

            #region light
            //var light = new THREE.DirectionalLight(0xffffff, 1.0);
            var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            //var lightOffset = new THREE.Vector3(0, 1000, 2500.0);
            var lightOffset = new THREE.Vector3(
                2000,
                700,

                // lower makes longer shadows 
                700.0
                );
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.1;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;

            xlight.shadowCameraVisible = true;

            scene.add(light);
            #endregion




            // whats WebGLRenderTargetCube do?

            // WebGLRenderer preserveDrawingBuffer 



            var renderer0 = new THREE.WebGLRenderer(

                new
                {
                    antialias = true,
                    alpha = true,
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836

            // the construct. white bg
            renderer0.setClearColor(0xfffff, 1);

            //renderer.setSize(window.Width, window.Height);
            renderer0.setSize(cubefacesize, cubefacesize);

            //renderer0.domElement.AttachToDocument();
            //rendererPX.domElement.style.SetLocation(0, 0);
            //renderer0.domElement.style.SetLocation(4, 4);


            // top

            // http://stackoverflow.com/questions/27612524/can-multiple-webglrenderers-render-the-same-scene


            // need a place to show the cubemap face to GUI 
            // how does the stereo OTOY do it?
            // https://www.opengl.org/wiki/Sampler_(GLSL)

            // http://www.richardssoftware.net/Home/Post/25

            // [+X, –X, +Y, –Y, +Z, –Z] fa



            // move up
            //camera.position.set(-1200, 800, 1200);
            //var cameraoffset = new THREE.Vector3(0, 15, 0);
            var cameraoffset = new THREE.Vector3(-1200, 800, 1200);

            #region y
            // need to rotate90?
            var cameraNY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraNY.lookAt(new THREE.Vector3(0, -1, 0));
            cameraNY.position.add(cameraoffset);

            //cameraNY.lookAt(new THREE.Vector3(0, 1, 0));
            var canvasNY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNY.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 2);
            canvasNY.canvas.title = "NY";
            canvasNY.canvas.AttachToDocument();
            canvasNY.canvas.style.transformOrigin = "0 0";
            canvasNY.canvas.style.transform = "scale(" + uizoom + ")";

            var cameraPY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraPY.lookAt(new THREE.Vector3(0, 1, 0));
            cameraPY.position.add(cameraoffset);
            //cameraPY.lookAt(new THREE.Vector3(0, -1, 0));
            var canvasPY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPY.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 0);
            canvasPY.canvas.title = "PY";
            canvasPY.canvas.AttachToDocument();
            canvasPY.canvas.style.transformOrigin = "0 0";
            canvasPY.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion

            // transpose xz?

            #region x
            var cameraNX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraNX.lookAt(new THREE.Vector3(0, 0, 1));
            cameraNX.position.add(cameraoffset);
            //cameraNX.lookAt(new THREE.Vector3(0, 0, -1));
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNX.lookAt(new THREE.Vector3(1, 0, 0));
            var canvasNX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNX.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 2, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNX.canvas.title = "NX";
            canvasNX.canvas.AttachToDocument();
            canvasNX.canvas.style.transformOrigin = "0 0";
            canvasNX.canvas.style.transform = "scale(" + uizoom + ")";

            var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraPX.lookAt(new THREE.Vector3(0, 0, -1));
            cameraPX.position.add(cameraoffset);
            //cameraPX.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPX.lookAt(new THREE.Vector3(1, 0, 0));
            //cameraPX.lookAt(new THREE.Vector3(-1, 0, 0));
            var canvasPX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPX.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPX.canvas.title = "PX";
            canvasPX.canvas.AttachToDocument();
            canvasPX.canvas.style.transformOrigin = "0 0";
            canvasPX.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion



            #region z
            var cameraNZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, -1));
            cameraNZ.lookAt(new THREE.Vector3(1, 0, 0));
            cameraNZ.position.add(cameraoffset);
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, 1));
            var canvasNZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNZ.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 3, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNZ.canvas.title = "NZ";
            canvasNZ.canvas.AttachToDocument();
            canvasNZ.canvas.style.transformOrigin = "0 0";
            canvasNZ.canvas.style.transform = "scale(" + uizoom + ")";

            var cameraPZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraPZ.lookAt(new THREE.Vector3(1, 0, 0));
            cameraPZ.lookAt(new THREE.Vector3(-1, 0, 0));
            cameraPZ.position.add(cameraoffset);
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, -1));
            var canvasPZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPZ.canvas.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPZ.canvas.title = "PZ";
            canvasPZ.canvas.AttachToDocument();
            canvasPZ.canvas.style.transformOrigin = "0 0";
            canvasPZ.canvas.style.transform = "scale(" + uizoom + ")";
            #endregion




            // c++ alias locals would be nice..
            var canvas0 = (IHTMLCanvas)renderer0.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var st = new Stopwatch();
            st.Start();

            //canvas0.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            Native.body.onmousedown +=
                async e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                        return;

                    // movementX no longer works
                    old = new
                    {


                        e.CursorX,
                        e.CursorY
                    };


                    //e.CaptureMouse();
                    var release = e.Element.CaptureMouse();
                    await e.Element.async.onmouseup;

                    release();


                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            Native.body.onmousemove +=
                e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                    {
                        Native.body.style.cursor = IStyle.CursorEnum.@default;
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();


                    Native.body.style.cursor = IStyle.CursorEnum.move;

                    var pointerLock = canvas0 == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion

            // THREE.WebGLProgram: gl.getProgramInfoLog() C:\fakepath(78,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll
            // THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

            // http://www.roadtovr.com/youtube-confirms-stereo-3d-360-video-support-coming-soon/
            // https://www.youtube.com/watch?v=D-Wl9jAB45Q



            #region spherical
            var gl = new WebGLRenderingContext(alpha: true, preserveDrawingBuffer: true);
            var c = gl.canvas.AttachToDocument();

            //  3840x2160

            //c.style.SetSize(3840, 2160);

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150722/360-youtube


            c.width = 3840;
            c.height = 2160;


            //c.width = 3840 * 2;
            //c.height = 2160 * 2;


            //c.width = 3840;
            //c.height = 2160;
            // 1,777777777777778

            // https://www.youtube.com/watch?v=fTfJwzRsE-w
            //c.width = 7580;
            //c.height = 3840;
            //1,973958333333333

            //7580
            //    3840

            // wont work
            //c.width = 8192;
            //c.height = 4096;


            // this has the wrong aspect?
            //c.width = 6466;
            //c.height = 3232;

            new IHTMLPre { new { c.width, c.height } }.AttachToDocument();

            //6466x3232

            //var suizoom = 720f / c.height;
            //var suizoom = 360f / c.height;
            var suizoom = 480f / c.width;

            c.style.transformOrigin = "0 0";
            c.style.transform = "scale(" + suizoom + ")";
            c.style.backgroundColor = "yellow";
            c.style.position = IStyle.PositionEnum.absolute;

            c.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 3);

            var pass = new CubeToEquirectangular.Library.ShaderToy.EffectPass(
                       null,
                       gl,
                       precission: CubeToEquirectangular.Library.ShaderToy.DetermineShaderPrecission(gl),
                       supportDerivatives: gl.getExtension("OES_standard_derivatives") != null,
                       callback: null,
                       obj: null,
                       forceMuted: false,
                       forcePaused: false,
                //quadVBO: Library.ShaderToy.createQuadVBO(gl, right: 0, top: 0),
                       outputGainNode: null
                   );

            // how shall we upload our textures?
            // can we reference GLSL.samplerCube yet?
            //pass.mInputs[0] = new samplerCube { };
            pass.mInputs[0] = new CubeToEquirectangular.Library.ShaderToy.samplerCube { };

            pass.MakeHeader_Image();
            var vs = new Shaders.ProgramFragmentShader();
            pass.NewShader_Image(vs);

            #endregion




            //var frame0 = new HTML.Images.FromAssets.tiles_regrid().AttachToDocument();
            var frame0 = new HTML.Images.FromAssets.anvil___spherical_hdri_panorama_skybox_by_macsix_d6vv4hs().AttachToDocument();
            //var xor = new HTML.Images.FromAssets.Orion360_test_image_8192x4096().AttachToDocument();
            //var xor = new HTML.Images.FromAssets._2_no_clouds_4k().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().AttachToDocument();


            // 270px
            //xor.style.height = "";
            frame0.style.height = "270px";
            frame0.style.width = "480px";
            frame0.style.SetLocation(
                8 + (int)(uizoom * cubefacesize + 8) * 0 + 480 + 16, 8 + (int)(uizoom * cubefacesize + 8) * 3);


            var mesh = new THREE.Mesh(new THREE.SphereGeometry(far / 2, 50, 50),
           new THREE.MeshBasicMaterial(new
           {
               map = THREE.ImageUtils.loadTexture(
                   //new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().src
                   //new HTML.Images.FromAssets._4008650304_7f837ccbb7_b().src
                  frame0.src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20130616_222058().src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20121225_210448().src

                   )
           }));
            mesh.scale.x = -1;

            #region fixup rotation

            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI / 2);
            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), -Math.PI / 2);
            mesh.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
            #endregion


            scene.add(mesh);


            //new IHTMLButton { }

            var dir = default(DirectoryEntry);

            new IHTMLButton { "openDirectory" }.AttachToDocument().onclick += async delegate
            {
                dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });
            };

            frame0.onclick += delegate
            {
                // http://paulbourke.net/papers/vsmm2006/vsmm2006.pdf
                //            A method of creating synthetic stereoscopic panoramic images that can be implemented
                //in most rendering packages has been presented. If single panoramic pairs can be created
                //then stereoscopic panoramic movies are equally possible giving rise to the prospect of
                //movies where the viewer can interact with, at least with regard to what they choose to look
                //at.These images can be projected so as to engage the two features of the human visual
                //system that assist is giving us a sense of immersion, the feeling of “being there”. That is,
                //imagery that contains parallax information as captured from two horizontally separated eye
                //positions (stereopsis)and imagery that fills our peripheral vision.The details that define
                //how the two panoramic images should be created in rendering packages are provided, in
                //particular, how to precisely configure the virtual cameras and control the distance to zero
                //parallax.

                // grab a frame


                var f0 = new IHTMLImage { src = gl.canvas.toDataURL() };

                //var f0 = (IHTMLImage)gl.canvas;
                //var f0 = (IHTMLImage)gl.canvas;
                //var base64 = gl.canvas.toDataURL();


                //frame0.src = base64;
                frame0.src = f0.src;

                // 7MB!

                if (dir == null)
                    return;

                //                // ---------------------------
                //IrfanView
                //---------------------------
                //Warning !
                //The file: "X:\vr\tape1\0001.jpg" is a PNG file with incorrect extension !
                //Rename ?
                //---------------------------
                //Yes   No   
                //---------------------------

                // haha this will render the thumbnail.
                //dir.WriteAllBytes("0000.png", frame0);

                dir.WriteAllBytes("0000.png", f0);
                // 3.7MB
                // 3840x2160

            };



            // "Z:\jsc.svn\examples\javascript\WebGL\WebGLColladaExperiment\WebGLColladaExperiment\WebGLColladaExperiment.csproj"

            #region WebGLRah66Comanche
            // why isnt it being found?
            // "Z:\jsc.svn\examples\javascript\WebGL\collada\WebGLRah66Comanche\WebGLRah66Comanche\WebGLRah66Comanche.csproj"
            new global::WebGLRah66Comanche.Comanche(
            ).Source.Task.ContinueWithResult(
                dae =>
                {

                    //dae.position.y = -40;
                    //dae.position.z = 280;
                    scene.add(dae);
                    //oo.Add(dae);

                    // wont do it
                    //dae.castShadow = true;

                    dae.children[0].children[0].children.WithEach(x => x.castShadow = true);


                    // the rotors?
                    dae.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


                    dae.scale.set(0.5, 0.5, 0.5);
                    dae.position.x = -900;
                    dae.position.z = +900;

                    // raise it up
                    dae.position.y = 400;

                    //var sw = Stopwatch.StartNew();

                    //Native.window.onframe += delegate
                    //{
                    //    //dae.children[0].children[0].children.Last().al
                    //    //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
                    //    //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
                    //    dae.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.01;
                    //};
                }
            );
            #endregion



            #region tree
            // "Z:\jsc.svn\examples\javascript\WebGL\WebGLGodRay\WebGLGodRay\WebGLGodRay.csproj"

            var materialScene = new THREE.MeshBasicMaterial(new { color = 0x000000, shading = THREE.FlatShading });
            var tloader = new THREE.JSONLoader();

            // http://stackoverflow.com/questions/16539736/do-not-use-system-runtime-compilerservices-dynamicattribute-use-the-dynamic
            // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.dynamicattribute%28v=vs.110%29.aspx
            //System.Runtime.CompilerServices.DynamicAttribute

            tloader.load(

                new WebGLGodRay.Models.tree().Content.src,

                new Action<THREE.Geometry>(
                xgeometry =>
                {

                    var treeMesh = new THREE.Mesh(xgeometry, materialScene);
                    treeMesh.position.set(0, -150, -150);
                    treeMesh.position.x = -900;
                    treeMesh.position.z = -900;

                    treeMesh.position.y = 25;

                    var tsc = 400;
                    treeMesh.scale.set(tsc, tsc, tsc);

                    treeMesh.matrixAutoUpdate = false;
                    treeMesh.updateMatrix();


                    treeMesh.AttachTo(scene);

                }
                )
                );
            #endregion

            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.

            // could we get some film grain?
            var planeGeometry = new THREE.CubeGeometry(512, 512, 1);
            var plane = new THREE.Mesh(planeGeometry,
                    new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

                );
            //plane.castShadow = false;
            plane.receiveShadow = true;


            {

                var parent = new THREE.Object3D();
                parent.add(plane);
                parent.rotation.x = -Math.PI / 2;
                parent.scale.set(10, 10, 10);

                scene.add(parent);
            }

            var random = new Random();
            var meshArray = new List<THREE.Mesh>();
            var geometry = new THREE.CubeGeometry(1, 1, 1);
            //var sw = Stopwatch.StartNew();

            for (var i = 3; i < 9; i++)
            {

                //THREE.MeshPhongMaterial
                var ii = new THREE.Mesh(geometry,


                    new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

                    //new THREE.MeshLambertMaterial(
                    //new
                    //{
                    //    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
                    //    specular = 0xffaaaa,
                    //    ambient= 0x050505, 
                    //})

                    );
                ii.position.x = i % 7 * 200 - 2.5f;

                // raise it up
                ii.position.y = .5f * 100;
                ii.position.z = -1 * i * 100;
                ii.castShadow = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);

                if (i % 2 == 0)
                {
#if FWebGLHZBlendCharacter
                    #region SpeedBlendCharacter
					var _i = i;
					{ WebGLHZBlendCharacter.HTML.Pages.TexturesImages ref0; }

					var blendMesh = new THREE.SpeedBlendCharacter();
					blendMesh.load(
						new WebGLHZBlendCharacter.Models.marine_anims().Content.src,
						new Action(
							delegate
							{
								// buildScene
								//blendMesh.rotation.y = Math.PI * -135 / 180;
								blendMesh.castShadow = true;
								// we cannot scale down we want our shadows
								//blendMesh.scale.set(0.1, 0.1, 0.1);

								blendMesh.position.x = (_i + 2) % 7 * 200 - 2.5f;

								// raise it up
								//blendMesh.position.y = .5f * 100;
								blendMesh.position.z = -1 * _i * 100;


								var xtrue = true;
								// run
								blendMesh.setSpeed(1.0);

								// will in turn call THREE.AnimationHandler.play( this );
								//blendMesh.run.play();
								// this wont help. bokah does not see the animation it seems.
								//blendMesh.run.update(1);

								blendMesh.showSkeleton(!xtrue);

								scene.add(blendMesh);


								Native.window.onframe +=
								 delegate
								 {

									 blendMesh.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;



									 ii.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;

								 };

							}
						)
					);
                    #endregion
#endif
                }

            }
            #endregion


            #region HZCannon
            // "Z:\jsc.svn\examples\javascript\WebGL\HeatZeekerRTSOrto\HeatZeekerRTSOrto\HeatZeekerRTSOrto.csproj"
            new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
                async cube =>
                {
                    // https://github.com/mrdoob/three.js/issues/1285
                    //cube.children.WithEach(c => c.castShadow = true);

                    //cube.traverse(
                    //    new Action<THREE.Object3D>(
                    //        child =>
                    //        {
                    //            // does it work? do we need it?
                    //            //if (child is THREE.Mesh)

                    //            child.castShadow = true;
                    //            //child.receiveShadow = true;

                    //        }
                    //    )
                    //);

                    // um can edit and continue insert code going back in time?
                    cube.scale.x = 10.0;
                    cube.scale.y = 10.0;
                    cube.scale.z = 10.0;



                    //cube.castShadow = true;
                    //dae.receiveShadow = true;

                    //cube.position.x = -100;

                    ////cube.position.y = (cube.scale.y * 50) / 2;
                    //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                    // if i want to rotate, how do I do it?
                    //cube.rotation.z = random() + Math.PI;
                    //cube.rotation.x = random() + Math.PI;
                    var sw2 = Stopwatch.StartNew();



                    scene.add(cube);
                    //interactiveObjects.Add(cube);

                    // offset is wrong
                    //while (true)
                    //{
                    //    await Native.window.async.onframe;

                    //    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

                    //}
                }
            );
            #endregion


            #region HZCannon
            new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
                async cube =>
                {
                    // https://github.com/mrdoob/three.js/issues/1285
                    //cube.children.WithEach(c => c.castShadow = true);

                    //cube.traverse(
                    //    new Action<THREE.Object3D>(
                    //        child =>
                    //        {
                    //            // does it work? do we need it?
                    //            //if (child is THREE.Mesh)

                    //            child.castShadow = true;
                    //            //child.receiveShadow = true;

                    //        }
                    //    )
                    //);

                    // um can edit and continue insert code going back in time?
                    cube.scale.x = 10.0;
                    cube.scale.y = 10.0;
                    cube.scale.z = 10.0;



                    //cube.castShadow = true;
                    //dae.receiveShadow = true;


                    // jsc shat about out of band code patching?
                    cube.position.z = 600;
                    cube.position.x = -900;
                    //cube.position.y = -400;

                    //cube.position.x = -100;
                    //cube.position.y = -400;

                    ////cube.position.y = (cube.scale.y * 50) / 2;
                    //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                    // if i want to rotate, how do I do it?
                    //cube.rotation.z = random() + Math.PI;
                    //cube.rotation.x = random() + Math.PI;
                    var sw2 = Stopwatch.StartNew();



                    scene.add(cube);
                    //interactiveObjects.Add(cube);

                    // offset is wrong
                    //while (true)
                    //{
                    //    await Native.window.async.onframe;

                    //    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

                    //}
                }
            );
            #endregion


            #region HZBunker
            new HeatZeekerRTSOrto.HZBunker().Source.Task.ContinueWithResult(
                     cube =>
                     {
                         // https://github.com/mrdoob/three.js/issues/1285
                         //cube.children.WithEach(c => c.castShadow = true);
                         cube.castShadow = true;

                         //cube.traverse(
                         //    new Action<THREE.Object3D>(
                         //        child =>
                         //        {
                         //            // does it work? do we need it?
                         //            //if (child is THREE.Mesh)
                         //            child.castShadow = true;
                         //            //child.receiveShadow = true;

                         //        }
                         //    )
                         //);

                         // um can edit and continue insert code going back in time?
                         cube.scale.x = 10.0;
                         cube.scale.y = 10.0;
                         cube.scale.z = 10.0;

                         //cube.castShadow = true;
                         //dae.receiveShadow = true;

                         cube.position.x = -1000;
                         //cube.position.y = (cube.scale.y * 50) / 2;
                         cube.position.z = 0;

                         scene.add(cube);
                     }
                 );
            #endregion


            new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = -(65 - 200);





                       var scale = 0.9;

                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;


                       #region onmousewheel
                       Native.body.onmousewheel +=
                           e =>
                           {
                               e.preventDefault();

                               //camera.position.z = 1.5;

                               // min max. shall adjust speed also!
                               // max 4.0
                               // min 0.6
                               dae.position.z -= 10.0 * e.WheelDirection;

                               //camera.position.z = 400;
                               //dae.position.z = dae.position.z.Max(-200).Min(200);

                               //Native.document.title = new { z }.ToString();

                           };
                       #endregion


                       //dae.position.y = -80;

                       scene.add(dae);
                       oo.Add(dae);




                       // view-source:http://threejs.org/examples/webgl_multiple_canvases_circle.html
                       // https://threejsdoc.appspot.com/doc/three.js/src.source/extras/cameras/CubeCamera.js.html
                       Native.window.onframe +=
                           e =>
                           {
                               //if (pause) return;
                               //if (pause.@checked)
                               //    return;


                               // can we float out of frame?
                               // haha. a bit too flickery.
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.01) * 50.0;
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.001) * 190.0;
                               dae.position.x = Math.Sin(sw.ElapsedMilliseconds * 0.0001) * 190.0;
                               dae.position.y = Math.Cos(sw.ElapsedMilliseconds * 0.0001) * 90.0;
                               // manual rebuild?
                               // red compiler notifies laptop chrome of pending update
                               // app reloads


                               renderer0.clear();
                               //rendererPY.clear();

                               //cameraPX.aspect = canvasPX.aspect;
                               //cameraPX.updateProjectionMatrix();

                               // um what does this do?
                               //cameraPX.position.z += (z - cameraPX.position.z) * e.delay.ElapsedMilliseconds / 200.0;
                               // mousewheel allos the camera to move closer
                               // once we see the frame in vr, can we udp sync vr tracking back to laptop?


                               //this.targetPX.x += 1;
                               //this.targetNX.x -= 1;

                               //this.targetPY.y += 1;
                               //this.targetNY.y -= 1;

                               //this.targetPZ.z += 1;
                               //this.targetNZ.z -= 1;

                               // how does the 360 or shadertoy want our cubemaps?


                               // and then rotate right?

                               // how can we render cubemap?


                               #region x
                               // upside down?
                               renderer0.render(scene, cameraPX);
                               canvasPX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNX);
                               canvasNX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion

                               #region z
                               renderer0.render(scene, cameraPZ);
                               canvasPZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNZ);
                               canvasNZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion



                               #region y
                               renderer0.render(scene, cameraPY);

                               //canvasPY.save();
                               //canvasPY.translate(0, size);
                               //canvasPY.rotate((float)(-Math.PI / 2));
                               canvasPY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasPY.restore();


                               renderer0.render(scene, cameraNY);
                               //canvasNY.save();
                               //canvasNY.translate(size, 0);
                               //canvasNY.rotate((float)(Math.PI / 2));
                               canvasNY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasNY.restore();
                               // ?
                               #endregion


                               //renderer0.render(scene, cameraPX);


                               //rendererPY.render(scene, cameraPY);

                               // at this point we should be able to render the sphere texture

                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_X = 34070;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Y = 34071;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Z = 34073;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074;


                               //var cube0 = new IHTMLImage[] {
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_px(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nx(),

                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_py(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_ny(),


                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_pz(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nz()
                               //};

                               new[] {
                                   canvasPX, canvasNX,
                                   canvasPY, canvasNY,
                                   canvasPZ, canvasNZ
                               }.WithEachIndex(
                                   (img, index) =>
                                   {
                                       gl.bindTexture(gl.TEXTURE_CUBE_MAP, pass.tex);

                                       //gl.pixelStorei(gl.UNPACK_FLIP_X_WEBGL, false);
                                       gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

                                       // http://stackoverflow.com/questions/15364517/pixelstoreigl-unpack-flip-y-webgl-true

                                       // https://msdn.microsoft.com/en-us/library/dn302429(v=vs.85).aspx
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);

                                       gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + (uint)index, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img.canvas);

                                   }
                                );


                               pass.Paint_Image(
                                     0,

                                     0,
                                     0,
                                     0,
                                     0
                                   //,

                                // gl_FragCoord
                                   // cannot be scaled, and can be referenced directly.
                                   // need another way to scale
                                   //zoom: 0.3f
                                );

                               //paintsw.Stop();


                               // what does it do?
                               gl.flush();

                           };


                   }
               );


            #endregion



            Console.WriteLine("do you see it?");
        }
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809

        // the eye nor the display will be able to do any stereo
        // until tech is near matrix capability. 2019?

        // cubemap can be used for all long range scenes
        // http://www.imdb.com/title/tt0112111/?ref_=nv_sr_1


        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150808/cubemapcamera
        // subst a: s:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeEquirectangularCameraExperiment\ChromeEquirectangularCameraExperiment\bin\Debug\staging\ChromeEquirectangularCameraExperiment.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeEquirectangularCameraExperiment\ChromeEquirectangularCameraExperiment\bin\Debug\staging\ChromeEquirectangularCameraExperiment.Application\web

        // ColladaLoader: Empty or non-existing file (assets/ChromeEquirectangularCameraExperiment/S6Edge.dae)

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //FormStyler.AtFormCreated =
            //s =>
            //{
            //    s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

            //    //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            //    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



            //    s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
            //    //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            //};

#if AsWEBSERVER
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                // if we run as a server. we can open up on android.

                //chrome.Notification.DefaultTitle = "Nexus7";
                //chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text
                //, AtFormCreated: FormStyler.AtFormCreated

                //AtFormConstructor:
                //    f =>
                //    {
                //        //arg[0] is typeof System.Int32
                //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                //    }
                );
                return;
            }
            #endregion
#else

            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    //chrome.runtime.UpdateAvailable += delegate
                    //{
                    //    new chrome.Notification(title: "UpdateAvailable");

                    //};

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "ChromeEquirectangularCameraExperiment");

                        // https://developer.chrome.com/apps/app_window#type-CreateWindowOptions
                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: new
                               {
                                   alwaysOnTop = true,
                                   visibleOnAllWorkspaces = true
                               }
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion


#endif


            Native.css.style.backgroundColor = "blue";
            Native.css.style.overflow = IStyle.OverflowEnum.hidden;

            Native.body.Clear();

            new IHTMLPre { "can we stream it into VR, shadertoy, youtube 360, youtube stereo yet?" }.AttachToDocument();


            var sw = Stopwatch.StartNew();

            var pause = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.checkbox, title = "pause" }.AttachToDocument();


            pause.onchange += delegate
            {

                if (pause.@checked)
                    sw.Stop();
                else
                    sw.Start();


            };

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;


            // what about physics and that portal rendering?

            // if we are running as a chrome web server, we may also be opened as android ndk webview app
            //var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: window.aspect, near: 1, far: 2000);
            // once we update source
            // save the source
            // manually recompile 
            //cameraPX.position.z = 400;

            //// the camera should be close enough for the object to float off the FOV of PX
            //cameraPX.position.z = 200;

            // scene
            // can we make the 3D object orbit around us ?
            // and
            // stream it to vr?
            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x303030);
            scene.add(ambient);

            // should we fix jsc to do a more correct IDL?
            var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);



            // whats WebGLRenderTargetCube do?

            // WebGLRenderer preserveDrawingBuffer 

            //const int size = 128;
            //const int size = 256; // 6 faces, 12KB
            //const int size = 512; // 6 faces, ?

            // WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled.

            //const int size = 720; // 6 faces, ?
            const int size = 1024; // 6 faces, ?

            var renderer0 = new THREE.WebGLRenderer(

                new
                {
                    antialias = true,
                    alpha = true,
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836

            // the construct. white bg
            renderer0.setClearColor(0xfffff, 1);

            //renderer.setSize(window.Width, window.Height);
            renderer0.setSize(size, size);

            //renderer0.domElement.AttachToDocument();
            //rendererPX.domElement.style.SetLocation(0, 0);
            //renderer0.domElement.style.SetLocation(4, 4);


            // top

            // http://stackoverflow.com/questions/27612524/can-multiple-webglrenderers-render-the-same-scene


            // need a place to show the cubemap face to GUI 
            // how does the stereo OTOY do it?
            // https://www.opengl.org/wiki/Sampler_(GLSL)

            // http://www.richardssoftware.net/Home/Post/25

            // [+X, –X, +Y, –Y, +Z, –Z] fa

            var uizoom = 0.1;

            var far = 0xffff;

            #region y
            // need to rotate90?
            var cameraNY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraNY.lookAt(new THREE.Vector3(0, -1, 0));
            //cameraNY.lookAt(new THREE.Vector3(0, 1, 0));
            var canvasNY = new CanvasRenderingContext2D(size, size);
            canvasNY.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 2);
            canvasNY.canvas.title = "NY";
            canvasNY.canvas.AttachToDocument();
            canvasNY.canvas.style.transformOrigin = "0 0";
            canvasNY.canvas.style.transform = $"scale({uizoom})";

            var cameraPY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraPY.lookAt(new THREE.Vector3(0, 1, 0));
            //cameraPY.lookAt(new THREE.Vector3(0, -1, 0));
            var canvasPY = new CanvasRenderingContext2D(size, size);
            canvasPY.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 0);
            canvasPY.canvas.title = "PY";
            canvasPY.canvas.AttachToDocument();
            canvasPY.canvas.style.transformOrigin = "0 0";
            canvasPY.canvas.style.transform = $"scale({uizoom})";
            #endregion

            // transpose xz?

            #region x
            var cameraNX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraNX.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraNX.lookAt(new THREE.Vector3(0, 0, -1));
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNX.lookAt(new THREE.Vector3(1, 0, 0));
            var canvasNX = new CanvasRenderingContext2D(size, size);
            canvasNX.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 2, 8 + (int)(uizoom * size + 8) * 1);
            canvasNX.canvas.title = "NX";
            canvasNX.canvas.AttachToDocument();
            canvasNX.canvas.style.transformOrigin = "0 0";
            canvasNX.canvas.style.transform = $"scale({uizoom})";

            var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            cameraPX.lookAt(new THREE.Vector3(0, 0, -1));
            //cameraPX.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPX.lookAt(new THREE.Vector3(1, 0, 0));
            //cameraPX.lookAt(new THREE.Vector3(-1, 0, 0));
            var canvasPX = new CanvasRenderingContext2D(size, size);
            canvasPX.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 0, 8 + (int)(uizoom * size + 8) * 1);
            canvasPX.canvas.title = "PX";
            canvasPX.canvas.AttachToDocument();
            canvasPX.canvas.style.transformOrigin = "0 0";
            canvasPX.canvas.style.transform = $"scale({uizoom})";
            #endregion



            #region z
            var cameraNZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, -1));
            cameraNZ.lookAt(new THREE.Vector3(1, 0, 0));
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, 1));
            var canvasNZ = new CanvasRenderingContext2D(size, size);
            canvasNZ.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 3, 8 + (int)(uizoom * size + 8) * 1);
            canvasNZ.canvas.title = "NZ";
            canvasNZ.canvas.AttachToDocument();
            canvasNZ.canvas.style.transformOrigin = "0 0";
            canvasNZ.canvas.style.transform = $"scale({uizoom})";

            var cameraPZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraPZ.lookAt(new THREE.Vector3(1, 0, 0));
            cameraPZ.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, -1));
            var canvasPZ = new CanvasRenderingContext2D(size, size);
            canvasPZ.canvas.style.SetLocation(8 + (int)(uizoom * size + 8) * 1, 8 + (int)(uizoom * size + 8) * 1);
            canvasPZ.canvas.title = "PZ";
            canvasPZ.canvas.AttachToDocument();
            canvasPZ.canvas.style.transformOrigin = "0 0";
            canvasPZ.canvas.style.transform = $"scale({uizoom})";
            #endregion




            // c++ alias locals would be nice..
            var canvas0 = (IHTMLCanvas)renderer0.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var st = new Stopwatch();
            st.Start();

            //canvas0.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            Native.body.onmousedown +=
                async e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                        return;

                    // movementX no longer works
                    old = new
                    {


                        e.CursorX,
                        e.CursorY
                    };


                    //e.CaptureMouse();
                    var release = e.Element.CaptureMouse();
                    await e.Element.async.onmouseup;

                    release();


                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            Native.body.onmousemove +=
                e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                    {
                        Native.body.style.cursor = IStyle.CursorEnum.@default;
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();


                    Native.body.style.cursor = IStyle.CursorEnum.move;

                    var pointerLock = canvas0 == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion

            // THREE.WebGLProgram: gl.getProgramInfoLog() C:\fakepath(78,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll
            // THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

            // http://www.roadtovr.com/youtube-confirms-stereo-3d-360-video-support-coming-soon/
            // https://www.youtube.com/watch?v=D-Wl9jAB45Q



            #region spherical
            var gl = new WebGLRenderingContext(alpha: true, preserveDrawingBuffer: true);
            var c = gl.canvas.AttachToDocument();

            //  3840x2160

            //c.style.SetSize(3840, 2160);

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150722/360-youtube


            c.width = 3840;
            c.height = 2160;

            // wont work
            //c.width = 8192;
            //c.height = 4096;


            // this has the wrong aspect?
            //c.width = 6466;
            //c.height = 3232;

            new IHTMLPre { new { c.width, c.height } }.AttachToDocument();

            //6466x3232

            //var suizoom = 720f / c.height;
            //var suizoom = 360f / c.height;
            var suizoom = 480f / c.width;

            c.style.transformOrigin = "0 0";
            c.style.transform = $"scale({suizoom})";
            c.style.backgroundColor = "yellow";
            c.style.position = IStyle.PositionEnum.absolute;

            c.style.SetLocation(8 + (int)(uizoom * size + 8) * 0, 8 + (int)(uizoom * size + 8) * 3);

            var pass = new CubeToEquirectangular.Library.ShaderToy.EffectPass(
                       null,
                       gl,
                       precission: CubeToEquirectangular.Library.ShaderToy.DetermineShaderPrecission(gl),
                       supportDerivatives: gl.getExtension("OES_standard_derivatives") != null,
                       callback: null,
                       obj: null,
                       forceMuted: false,
                       forcePaused: false,
                       //quadVBO: Library.ShaderToy.createQuadVBO(gl, right: 0, top: 0),
                       outputGainNode: null
                   );

            // how shall we upload our textures?
            // can we reference GLSL.samplerCube yet?
            //pass.mInputs[0] = new samplerCube { };
            pass.mInputs[0] = new CubeToEquirectangular.Library.ShaderToy.samplerCube { };

            pass.MakeHeader_Image();
            var vs = new Shaders.ProgramFragmentShader();
            pass.NewShader_Image(vs);

            #endregion




            //var xor = new HTML.Images.FromAssets.tiles_regrid().AttachToDocument();
            //var xor = new HTML.Images.FromAssets.Orion360_test_image_8192x4096().AttachToDocument();
            //var xor = new HTML.Images.FromAssets._2_no_clouds_4k().AttachToDocument();
            var frame0 = new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().AttachToDocument();


            // 270px
            //xor.style.height = "";
            frame0.style.height = "270px";
            frame0.style.width = "480px";
            frame0.style.SetLocation(
                8 + (int)(uizoom * size + 8) * 0 + 480 + 16, 8 + (int)(uizoom * size + 8) * 3);


            var mesh = new THREE.Mesh(new THREE.SphereGeometry(0xFFF, 50, 50),
           new THREE.MeshBasicMaterial(new
           {
               map = THREE.ImageUtils.loadTexture(
                  //new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().src
                  //new HTML.Images.FromAssets._4008650304_7f837ccbb7_b().src
                  frame0.src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20130616_222058().src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20121225_210448().src

                   )
           }));
            mesh.scale.x = -1;

            #region fixup rotation

            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI / 2);
            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), -Math.PI / 2);
            mesh.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
            #endregion


            scene.add(mesh);



            frame0.onclick += delegate
            {
                // http://paulbourke.net/papers/vsmm2006/vsmm2006.pdf
                //            A method of creating synthetic stereoscopic panoramic images that can be implemented
                //in most rendering packages has been presented. If single panoramic pairs can be created
                //then stereoscopic panoramic movies are equally possible giving rise to the prospect of
                //movies where the viewer can interact with, at least with regard to what they choose to look
                //at.These images can be projected so as to engage the two features of the human visual
                //system that assist is giving us a sense of immersion, the feeling of “being there”. That is,
                //imagery that contains parallax information as captured from two horizontally separated eye
                //positions (stereopsis)and imagery that fills our peripheral vision.The details that define
                //how the two panoramic images should be created in rendering packages are provided, in
                //particular, how to precisely configure the virtual cameras and control the distance to zero
                //parallax.

                // grab a frame

                var base64 = gl.canvas.toDataURL();

                frame0.src = base64;
                // 7MB!

            };

            new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = -(65 - 200);





                       var scale = 0.9;

                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;


                       #region onmousewheel
                       Native.body.onmousewheel +=
                           e =>
                           {
                               e.preventDefault();

                               //camera.position.z = 1.5;

                               // min max. shall adjust speed also!
                               // max 4.0
                               // min 0.6
                               dae.position.z -= 10.0 * e.WheelDirection;

                               //camera.position.z = 400;
                               //dae.position.z = dae.position.z.Max(-200).Min(200);

                               //Native.document.title = new { z }.ToString();

                           };
                       #endregion


                       //dae.position.y = -80;

                       scene.add(dae);
                       oo.Add(dae);




                       // view-source:http://threejs.org/examples/webgl_multiple_canvases_circle.html
                       // https://threejsdoc.appspot.com/doc/three.js/src.source/extras/cameras/CubeCamera.js.html
                       Native.window.onframe +=
                           e =>
                           {
                               //if (pause) return;
                               //if (pause.@checked)
                               //    return;


                               // can we float out of frame?
                               // haha. a bit too flickery.
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.01) * 50.0;
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.001) * 190.0;
                               dae.position.x = Math.Sin(sw.ElapsedMilliseconds * 0.0001) * 190.0;
                               dae.position.y = Math.Cos(sw.ElapsedMilliseconds * 0.0001) * 90.0;
                               // manual rebuild?
                               // red compiler notifies laptop chrome of pending update
                               // app reloads


                               renderer0.clear();
                               //rendererPY.clear();

                               //cameraPX.aspect = canvasPX.aspect;
                               //cameraPX.updateProjectionMatrix();

                               // um what does this do?
                               //cameraPX.position.z += (z - cameraPX.position.z) * e.delay.ElapsedMilliseconds / 200.0;
                               // mousewheel allos the camera to move closer
                               // once we see the frame in vr, can we udp sync vr tracking back to laptop?


                               //this.targetPX.x += 1;
                               //this.targetNX.x -= 1;

                               //this.targetPY.y += 1;
                               //this.targetNY.y -= 1;

                               //this.targetPZ.z += 1;
                               //this.targetNZ.z -= 1;

                               // how does the 360 or shadertoy want our cubemaps?


                               // and then rotate right?

                               // how can we render cubemap?


                               #region x
                               // upside down?
                               renderer0.render(scene, cameraPX);
                               canvasPX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);

                               renderer0.render(scene, cameraNX);
                               canvasNX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               #endregion

                               #region z
                               renderer0.render(scene, cameraPZ);
                               canvasPZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);

                               renderer0.render(scene, cameraNZ);
                               canvasNZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               #endregion



                               #region y
                               renderer0.render(scene, cameraPY);

                               //canvasPY.save();
                               //canvasPY.translate(0, size);
                               //canvasPY.rotate((float)(-Math.PI / 2));
                               canvasPY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               //canvasPY.restore();


                               renderer0.render(scene, cameraNY);
                               //canvasNY.save();
                               //canvasNY.translate(size, 0);
                               //canvasNY.rotate((float)(Math.PI / 2));
                               canvasNY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, size, size);
                               //canvasNY.restore();
                               // ?
                               #endregion


                               //renderer0.render(scene, cameraPX);


                               //rendererPY.render(scene, cameraPY);

                               // at this point we should be able to render the sphere texture

                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_X = 34070;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Y = 34071;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Z = 34073;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074;


                               //var cube0 = new IHTMLImage[] {
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_px(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nx(),

                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_py(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_ny(),


                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_pz(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nz()
                               //};

                               new[] {
                                   canvasPX, canvasNX,
                                   canvasPY, canvasNY,
                                   canvasPZ, canvasNZ
                               }.WithEachIndex(
                                   (img, index) =>
                                   {
                                       gl.bindTexture(gl.TEXTURE_CUBE_MAP, pass.tex);

                                       //gl.pixelStorei(gl.UNPACK_FLIP_X_WEBGL, false);
                                       gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

                                       // http://stackoverflow.com/questions/15364517/pixelstoreigl-unpack-flip-y-webgl-true

                                       // https://msdn.microsoft.com/en-us/library/dn302429(v=vs.85).aspx
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);

                                       gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + (uint)index, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img.canvas);

                                   }
                                );


                               pass.Paint_Image(
                                     0,

                                     0,
                                     0,
                                     0,
                                     0
                                //,

                                // gl_FragCoord
                                // cannot be scaled, and can be referenced directly.
                                // need another way to scale
                                //zoom: 0.3f
                                );

                               //paintsw.Stop();


                               // what does it do?
                               gl.flush();

                           };


                   }
               );


            #endregion



            Console.WriteLine("do you see it?");
        }
Example #43
0
        protected void MakeLights()
        {
            // lights
            THREE.Light light;

            scene.add(new THREE.AmbientLight(0x666666));

            light = new THREE.DirectionalLight(0xdfebff, 1.75);
            light.position.set(50, 200, 100);
            light.position.multiplyScalar(1.3);

            light.castShadow = true;
            light.shadowCameraVisible = false;

            light.shadowMapWidth = 1024;
            light.shadowMapHeight = 1024;

            double lightBox = 300;

            light.shadowCameraLeft = -lightBox;
            light.shadowCameraRight = lightBox;
            light.shadowCameraTop = lightBox;
            light.shadowCameraBottom = -lightBox;

            light.shadowCameraFar = 1000;

            scene.add(light);
        }
Example #44
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // what are we looking at?

            var scene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 1000);

            camera.position.z = 300;

            var renderer = new THREE.WebGLRenderer(
                new
            {
                preserveDrawingBuffer = true
            }
                );

            renderer.setSize();

            scene.add(new THREE.AmbientLight(0x333333));

            var light = new THREE.DirectionalLight(0xffffff, 1);

            light.position.set(5, 3, 5);
            scene.add(light);

            var cube     = new THREE.CubeGeometry(0.5, 0.5, 0.5);
            var material = new THREE.MeshBasicMaterial(new
            {
                color = new THREE.Color(0xADD8E6),
            });

            var obj = new THREE.Object3D();

            for (var x = 0; x < 100; x++)
            {
                for (var y = 0; y < 100; y++)
                {
                    for (var zz = 0; zz < 15; zz++)
                    {
                        var mesh1 = new THREE.Mesh(cube, material);
                        mesh1.position.x = x;
                        mesh1.position.y = y;
                        mesh1.position.z = zz;
                        obj.add(mesh1);
                    }
                }
            }

            //var mesh1 = new THREE.Mesh(cube, material);
            //mesh1.position.x = 1;
            //mesh1.position.y = 1;
            //mesh1.position.z = 1;
            //obj.add(mesh1);
            scene.add(obj);

            var z = camera.position.z;

            this.canvas = (IHTMLCanvas)renderer.domElement;

            //renderer.domElement.AttachToDocument();
            this.canvas.AttachToDocument();
            this.canvas.style.SetLocation(0, 0);

            Native.window.onframe +=
                e =>
            {
                //if (this.canvas.parentNode == null)
                //    return;

                camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                camera.updateProjectionMatrix();

                camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200;


                // the larger the vew the slower the rotation shall be
                var speed = 0.0001 * e.delay.ElapsedMilliseconds +
                            0.007
                            * 96.0 / canvas.clientHeight
                            * 1.0 / camera.position.z;

                //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString();
                //Native.document.title = new { speed }.ToString();


                //controls.update();
                //sphere.rotation.y += speed;
                obj.rotation.y += speed;


                renderer.render(scene, camera);
            };

            Native.window.onresize +=
                delegate
            {
                //if (canvas.parentNode == Native.document.body)

                // are we embedded?
                if (page != null)
                {
                    renderer.setSize();
                }
            };
        }
Example #45
0
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150812/cssstereo

        //0001 02000178 ScriptCoreLib::ScriptCoreLib.Shared.BCLImplementation.System.Security.Cryptography.__MD5CryptoServiceProvider
        //script: error JSC1000: Java : Opcode not implemented: stind.i1 at ScriptCoreLib.Shared.BCLImplementation.System.Security.Cryptography.__MD5CryptoServiceProviderByMahmood.CreatePaddedBuffer
        //internal compiler error at method

        //       script: error JSC1000: Java :
        //BCL needs another method, please define it.
        //Cannot call type without script attribute :
        //System.Threading.Monitor for Void Enter(System.Object, Boolean ByRef) used at
        //WebGLVRCreativeLeadership.Activities.ApplicationWebServiceActivity+<>c__DisplayClass24.<CreateServer>b__29 at offset 0018.
        //If the use of this method is intended, an implementation should be provided with the attribute[Script(Implements = typeof(...)] set.You may have mistyped it.

        //		I/chromium(13596): [INFO: CONSOLE(97050)] "THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( undefined )", source: http://192.168.1.228:23993/view-source (97050)
        //I/chromium(13596): [INFO: CONSOLE(97050)] "THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( undefined )", source: http://192.168.1.228:23993/view-source (97050)

        public Application(com.abstractatech.apps.vr.HTML.Pages.IApp page)
        {
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self               = Native.self;
            dynamic self_chrome        = self.chrome;
            object  self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                ChromeTCPServer.TheServerWithAppWindow.Invoke(com.abstractatech.apps.vr.HTML.Pages.AppSource.Text);

                return;
            }
            #endregion

            // https://play.google.com/store/apps/details?id=com.abstractatech.vr
            // could we display LAN UDP notifications too. like
            // which youtube video is playing?

            Native.body.Clear();
            Native.body.style.margin          = "0px";
            Native.body.style.backgroundColor = "black";

            // https://vronecontest.zeiss.com/index.php?controller=ideas&view=show&id=652

            //          hResolution: 1920,
            //vResolution: 1080,

            // "X:\jsc.svn\examples\javascript\synergy\webgl\WebGLEquirectangularPanorama\WebGLEquirectangularPanorama.sln"

            // http://oculusstreetview.eu.pn/?lat=44.301987&lng=9.211561999999958&q=3&s=false&heading=0
            // https://github.com/troffmo5/OculusStreetView

            // http://stackoverflow.com/questions/23817633/threejs-using-a-sprite-with-the-oculusrifteffect
            // http://laht.info/dk2-parameters-for-three-oculusrifteffect-js/

            // http://stemkoski.github.io/Three.js/Sprites.html
            // http://stemkoski.github.io/Three.js/Texture-Animation.html
            // http://blog.thematicmapping.org/2013/10/terrain-visualization-with-threejs-and.html

            // http://mrdoob.github.io/three.js/examples/webgl_panorama_equirectangular.html

            var window = Native.window;

            var fov = 70.0;

            var camera = new THREE.PerspectiveCamera(fov,
                                                     window.aspect, 1, 1100);
            var target = new THREE.Vector3(0, 0, 0);

            //(camera as dynamic).target = target;

            var scene = new THREE.Scene();
            //scene.add(new THREE.AmbientLight(0xffffff));
            //scene.add(new THREE.AmbientLight(0xafafaf));

            // http://www.html5canvastutorials.com/three/html5-canvas-webgl-ambient-lighting-with-three-js/

            // http://stackoverflow.com/questions/14717135/three-js-ambient-light-unexpected-effect

            scene.add(new THREE.AmbientLight(0x2f2f2f));


            //var light = new THREE.DirectionalLight(0xffffff, 1.0);
            #region light
            var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            //var lightOffset = new THREE.Vector3(0, 1000, 2500.0);
            var lightOffset = new THREE.Vector3(
                2000,
                700,

                // lower makes longer shadows
                700.0
                );
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth  = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear   = 10;
            xlight.shadowCameraFar    = 10000;
            xlight.shadowBias         = 0.00001;
            xlight.shadowCameraRight  = 4000;
            xlight.shadowCameraLeft   = -4000;
            xlight.shadowCameraTop    = 4000;
            xlight.shadowCameraBottom = -4000;

            xlight.shadowCameraVisible = true;

            scene.add(light);
            #endregion

            var mesh = new THREE.Mesh(new THREE.SphereGeometry(500, 60, 40),
                                      new THREE.MeshBasicMaterial(new
            {
                map = THREE.ImageUtils.loadTexture(
                    new _2294472375_24a3b8ef46_o().src
                    //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20130616_222058().src
                    //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20121225_210448().src

                    )
            }));
            mesh.scale.x = -1;
            scene.add(mesh);

            #region sprite2
            var crateTexture = THREE.ImageUtils.loadTexture(
                new ChromeCreativeLeadership.HTML.Images.FromAssets.Mockup().src

                );

            var crateMaterial = new THREE.SpriteMaterial(
                new
            {
                map = crateTexture,
                useScreenCoordinates = false,
                //color = 0xff0000
                color = 0xffffff
            }
                );



            var sprite2 = new THREE.Sprite(crateMaterial);

            //floor
            //sprite2.position.set(0, -200, 0);

            // left
            //sprite2.position.set(200, 50, 0);

            sprite2.position.set(0, 0, 200);

            //sprite2.position.set(-100, 0, 0);
            sprite2.scale.set(
                _2294472375_24a3b8ef46_o.ImageDefaultWidth * 0.08,
                _2294472375_24a3b8ef46_o.ImageDefaultHeight * 0.08,
                //64, 64,
                1.0);                 // imageWidth, imageHeight
            scene.add(sprite2);
            #endregion


            #region ColladaAudiA4
            new ColladaAudiA4().Source.Task.ContinueWithResult(
                dae =>
            {
                // 90deg
                //dae.rotation.x = -Math.Cos(Math.PI);

                //dae.scale.x = 30;
                //dae.scale.y = 30;
                //dae.scale.z = 30;
                //dae.position.z = 65;

                // right
                dae.position.z = -20;
                dae.position.x = -100;
                dae.position.y = -90;


                // jsc, do we have ILObserver available yet?
                dae.scale.x = 1.0;
                dae.scale.y = 1.0;
                dae.scale.z = 1.0;

                //dae.position.y = -80;

                scene.add(dae);
                //oo.Add(dae);
            }
                );
            #endregion



            #region nexus7
            new nexus7().Source.Task.ContinueWithResult(
                dae =>
            {
                // 90deg
                dae.rotation.x = -Math.Cos(Math.PI);

                //dae.scale.x = 30;
                //dae.scale.y = 30;
                //dae.scale.z = 30;
                //dae.position.z = 65;

                // left
                //dae.position.x = 200;

                dae.position.z = -100;
                dae.position.y = -50;

                //dae.position.z = 100;



                // jsc, do we have ILObserver available yet?
                dae.scale.x = 13.5;
                dae.scale.y = 13.5;
                dae.scale.z = 13.5;

                //dae.position.y = -80;

                scene.add(dae);
                //oo.Add(dae);
            }
                );
            #endregion



            //          // DK2
            //          hResolution: 1920,
            //vResolution: 1080,

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(1920, 1080);


            // broken?
            var distortionK       = new double[] { 1.0, 0.22, 0.24, 0.0 };
            var chromaAbParameter = new double[] { 0.996, -0.004, 1.014, 0.0 };

            var HMD = new OculusRiftEffectOptions
            {
                hResolution = window.Width,
                vResolution = window.Height,

                hScreenSize            = 0.12576,
                vScreenSize            = 0.07074,
                interpupillaryDistance = 0.0635,
                lensSeparationDistance = 0.0635,
                eyeToScreenDistance    = 0.041,

                //  j.distortionK = [0, 1.875, -71.68, 1.595, -3.218644E+26, 1.615, 0, 0];
                //distortionK = new double[] { 1.0, 0.22, 0.24, 0.0 },
                distortionK = distortionK,

                // j.chromaAbParameter = [1.609382E+22, 1.874, -5.189695E+11, -0.939, 4.463059E-29, 1.87675, 0, 0];
                //chromaAbParameter = new double[] { 0.996, -0.004, 1.014, 0.0 }
                chromaAbParameter = chromaAbParameter
            };

            var effect = new THREE.OculusRiftEffect(
                renderer, new
            {
                worldScale = 100,

                //HMD
            }
                );

            effect.setSize(1920, 1080);


            renderer.domElement.AttachToDocument();

            //renderer.domElement.style.position = IStyle.PositionEnum.absolute;
            renderer.domElement.style.SetLocation(0, 0);

            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;

            // x:\jsc.svn\examples\javascript\synergy\comanchebysiorki\comanchebysiorki\application.cs


            #region onresize
            new { }.With(
                async delegate
            {
                retry:

                var s = (double)Native.window.Width / 1920.0;


                Native.document.body.style.transform       = "scale(" + s + ")";
                Native.document.body.style.transformOrigin = "0% 0%";

                await Native.window.async.onresize;
                goto retry;
            }
                );
            #endregion



            //#region onresize
            //Native.window.onresize +=
            //    delegate
            //    {
            //        camera.aspect = Native.window.aspect;
            //        camera.updateProjectionMatrix();

            //        renderer.setSize(window.Width, window.Height);
            //        effect.setSize(window.Width, window.Height);
            //    };
            //#endregion


            //Native.document.body.onmousewheel +=
            //    e =>
            //    {
            //        fov -= e.WheelDirection * 5.0;
            //        camera.projectionMatrix.makePerspective(fov,
            //            (double)window.Width / window.Height, 1, 1100);
            //    };

            var lon0 = -45.0;
            var lon1 = 0.0;

            var lon = new sum(
                () => lon0,
                () => lon1
                );

            var lat0 = 0.0;
            var lat1 = 0.0;

            // or could we do it with byref or pointers?
            var lat = new sum(
                () => lat0,
                () => lat1
                );

            var phi   = 0.0;
            var theta = 0.0;

            var camera_rotation_z = 0.0;


            var labove = new NotificationLayout();

            #region sprite2 above
            {
                labove.Message.innerText       = "VR CREATIVE LEADERSHIP";
                labove.layout.style.background = "";

                new { }.With(
                    async delegate
                {
                    retry:

                    // make it blink. gaze cursor is on it?


                    labove.box.style.background = "rgba(255,255,0,0.7)";
                    labove.box.setAttribute("invoke", "onmutation1");
                    await Task.Delay(1500);

                    // is mutation observer noticing it?
                    labove.box.style.background = "rgba(255,255,255,0.7)";
                    labove.box.setAttribute("invoke", "onmutation2");
                    await Task.Delay(1500);


                    goto retry;
                }
                    );



                var c = labove.AsCanvas();

                var xcrateTexture = new THREE.Texture(c);

                // like video texture
                Native.window.onframe += delegate { xcrateTexture.needsUpdate = true; };

                var xcrateMaterial = new THREE.SpriteMaterial(
                    new
                {
                    map = xcrateTexture,
                    useScreenCoordinates = false,
                    //color = 0xff0000
                    color = 0xffffff
                }
                    );



                var xsprite2 = new THREE.Sprite(xcrateMaterial);

                //floor
                //sprite2.position.set(0, -200, 0);

                // left
                xsprite2.position.set(200, 0, 0);

                //sprite2.position.set(0, 0, 200);

                //sprite2.position.set(-100, 0, 0);
                xsprite2.scale.set(
                    c.width * 0.5,
                    c.height * 0.5,
                    //64, 64,
                    1.0);                     // imageWidth, imageHeight
                scene.add(xsprite2);
            }
            #endregion



            //var lineTo = new List<THREE.Vector3>();
            var others = new
            {
                ui     = default(NotificationLayout),
                canvas = default(IHTMLCanvas),

                map = default(THREE.Texture),

                sprite = default(THREE.Sprite)
            }.ToEmptyList();

            #region add
            Action <NotificationLayout> add = ui =>
            {
                ui.layout.style.background = "";

                var canvas = ui.AsCanvas();
                var index  = others.Count;

                //ui.Message  += new { index };
                //ui.Message.innerText += new { index };

                //lbelow0.Message = new { THREE.REVISION }.ToString();

                // THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( undefined )

                var map = new THREE.Texture(canvas);

                map.minFilter = THREE.LinearFilter;

                // like video texture

                var xcrateMaterial = new THREE.SpriteMaterial(
                    new
                {
                    map,
                    useScreenCoordinates = false,
                    //color = 0xff0000
                    color = 0xffffff
                }
                    );



                var sprite = new THREE.Sprite(xcrateMaterial);

                //floor
                //sprite2.position.set(0, -200, 0);

                // left middle
                //sprite2.position.set(200, 0, 0);
                //sprite.position.set(250, -50, 50);
                //lineTo.Add(sprite.position);



                //sprite2.position.set(0, 0, 200);

                //sprite2.position.set(-100, 0, 0);
                sprite.scale.set(
                    canvas.width * 0.5,
                    canvas.height * 0.5,
                    //64, 64,
                    1.0);                     // imageWidth, imageHeight
                scene.add(sprite);

                others.Add(
                    new
                {
                    ui,
                    canvas,
                    map,
                    sprite
                }
                    );

                var sw = Stopwatch.StartNew();

                Native.window.onframe += delegate
                {
                    // can we get some of the crazy c++ template bitmapbuffer code from the past?
                    map.needsUpdate = true;

                    var offset = Math.PI * 2 * ((double)(index + 1) / others.Count);

                    sprite.position.x = 300;

                    sprite.position.z = Math.Sin(sw.ElapsedMilliseconds * 0.00001 + offset) * 120;
                    sprite.position.y = Math.Cos(sw.ElapsedMilliseconds * 0.00001 + offset) * 120;
                };
            };
            #endregion


            #region NotificationLayout
            add(
                new NotificationLayout
            {
                // keep attributes around?
                // like we do with XElement sync?
                Icon = new _0_10122014_ECAF4B1F638429B44F4B142C2A4F38EE().With(
                    x =>
                {
                    x.style.width  = "96px";
                    x.style.height = "96px";
                }
                    ),
                Message = "Advanced Mechanics by Portugal Design Lab"
            }
                );

            add(
                new NotificationLayout
            {
                // keep attributes around?
                // like we do with XElement sync?
                Icon = new _42_08122014_D2639E0AAA3E54E5F4568760AEE605EE().With(
                    x =>
                {
                    x.style.width  = "96px";
                    x.style.height = "96px";
                }
                    ),
                Message = "Face Value by mshariful"
            }
                );



            add(
                new NotificationLayout
            {
                // keep attributes around?
                // like we do with XElement sync?
                Icon = new _371_28122014_2045510F2F7974319A9F7E9F4B39DF07().With(
                    x =>
                {
                    x.style.width  = "96px";
                    x.style.height = "96px";
                }
                    ),
                Message = "Mind Wall. by Sumit Goski"
            }
                );
            #endregion



            #region lines
            {
                var geometry = new THREE.Geometry
                {
                    // how can we keep streaming verticies data points to gpu?
                    vertices =

                        others.SelectMany(
                            lineTo =>
                            new[]
                    {
                        new THREE.Vector3(200, 0, 0),
                        lineTo.sprite.position
                    }
                            ).ToArray()

                        // https://github.com/mrdoob/three.js/wiki/Updates
                        // http://stackoverflow.com/questions/17842521/adding-geometry-to-a-three-js-mesh-after-render
                        //verticesNeedUpdate = true
                };

                Native.window.onframe += delegate { geometry.verticesNeedUpdate = true; };

                var o = new THREE.Line(geometry, new THREE.LineDashedMaterial(
                                           new { color = 0x00aaff, dashSize = 1, gapSize = 0.5, linewidth = 1 }
                                           ), THREE.LineStrip);

                //objects.Add(o);
                scene.add(o);
            }
            #endregion

            Native.window.onframe +=
                ee =>
            {
                // look we are having html in 3D in VR!



                //if (Native.document.pointerLockElement == Native.document.body)
                //    lon += 0.00;
                //else
                //    lon += 0.01;

                //lat = Math.Max(-85, Math.Min(85, lat));

                //Native.document.title = new { lon, lat }.ToString();


                phi   = THREE.Math.degToRad(90 - lat);
                theta = THREE.Math.degToRad(lon);

                target.x = 500 * Math.Sin(phi) * Math.Cos(theta);
                target.y = 500 * Math.Cos(phi);
                target.z = 500 * Math.Sin(phi) * Math.Sin(theta);

                camera.lookAt(target);
                camera.rotation.z += camera_rotation_z;

                //renderer.render(scene, camera);
                effect.render(scene, camera);
            };



            // http://blog.thematicmapping.org/2013/10/terrain-visualization-with-threejs-and.html

            // http://stackoverflow.com/questions/13278087/determine-vertical-direction-of-a-touchmove



            var compassHeadingOffset      = 0.0;
            var compassHeadingInitialized = 0;

            #region compassHeading
            // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeading\TestCompassHeading\Application.cs
            Native.window.ondeviceorientation +=
                dataValues =>
            {
                // Convert degrees to radians
                var alphaRad = dataValues.alpha * (Math.PI / 180);
                var betaRad  = dataValues.beta * (Math.PI / 180);
                var gammaRad = dataValues.gamma * (Math.PI / 180);

                // Calculate equation components
                var cA = Math.Cos(alphaRad);
                var sA = Math.Sin(alphaRad);
                var cB = Math.Cos(betaRad);
                var sB = Math.Sin(betaRad);
                var cG = Math.Cos(gammaRad);
                var sG = Math.Sin(gammaRad);

                // Calculate A, B, C rotation components
                var rA = -cA * sG - sA * sB * cG;
                var rB = -sA * sG + cA * sB * cG;
                var rC = -cB * cG;

                // Calculate compass heading
                var compassHeading = Math.Atan(rA / rB);

                // Convert from half unit circle to whole unit circle
                if (rB < 0)
                {
                    compassHeading += Math.PI;
                }
                else if (rA < 0)
                {
                    compassHeading += 2 * Math.PI;
                }

                /*
                 * Alternative calculation (replacing lines 99-107 above):
                 *
                 * var compassHeading = Math.atan2(rA, rB);
                 *
                 * if(rA < 0) {
                 * compassHeading += 2 * Math.PI;
                 * }
                 */

                // Convert radians to degrees
                compassHeading *= 180 / Math.PI;

                // Compass heading can only be derived if returned values are 'absolute'

                // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeadingWithReset\TestCompassHeadingWithReset\Application.cs

                //Native.document.body.innerText = new { compassHeading }.ToString();
                if (compassHeadingInitialized > 0)
                {
                    lon1 = compassHeading - compassHeadingOffset;
                }
                else
                {
                    compassHeadingOffset = compassHeading;
                    compassHeadingInitialized++;
                }
            };
            #endregion

            #region gamma
            Native.window.ondeviceorientation +=
                //e => Native.body.innerText = new { e.alpha, e.beta, e.gamma }.ToString();
                //e => lon = e.gamma;
                e =>
            {
                lat1 = e.gamma;

                // after servicing a running instance would be nice
                // either by patching or just re running the whole iteration in the backgrou
                camera_rotation_z = e.beta * 0.02;
            };
            #endregion



            #region camera rotation
            var old = new { clientX = 0, clientY = 0 };

            Native.document.body.ontouchstart +=
                e =>
            {
                var n = new { e.touches[0].clientX, e.touches[0].clientY };
                old = n;
            };

            Native.document.body.ontouchmove +=
                e =>
            {
                var n = new { e.touches[0].clientX, e.touches[0].clientY };

                e.preventDefault();

                lon0 += (n.clientX - old.clientX) * 0.2;
                lat0 -= (n.clientY - old.clientY) * 0.2;

                old = n;
            };


            Native.document.body.onmousemove +=
                e =>
            {
                e.preventDefault();

                if (Native.document.pointerLockElement == Native.document.body)
                {
                    lon0 += e.movementX * 0.1;
                    lat0 -= e.movementY * 0.1;

                    //Console.WriteLine(new { lon, lat, e.movementX, e.movementY });
                }
            };


            Native.document.body.onmouseup +=
                e =>
            {
                //drag = false;
                e.preventDefault();
            };

            Native.document.body.onmousedown +=
                e =>
            {
                //e.CaptureMouse();

                //drag = true;
                e.preventDefault();
                Native.document.body.requestPointerLock();
            };


            Native.document.body.ondblclick +=
                e =>
            {
                e.preventDefault();

                Console.WriteLine("requestPointerLock");
            };

            #endregion

            Native.body.onmousewheel +=
                e =>
            {
                camera_rotation_z += 0.1 * e.WheelDirection;;
            };
            // https://developer.android.com/training/system-ui/immersive.html
        }
Example #46
0
        // http://alteredqualia.com/three/examples/webgl_postprocessing_ssao.html
        // http://alteredqualia.com/three/examples/webgl_cars.html
        // http://alteredqualia.com/xg/examples/animation_physics_terrain.html

        // https://chrome.google.com/webstore/detail/webglhzblendcharacter/cgnjcccfcjhdnbfgjgllglbhfcgndmea

        // Could not connect to the feed specified at 'http://my.jsc-solutions.net/nuget'. P
        // https://github.com/dotnet/roslyn/issues/98


        //Icon image is missing.
        //At least one new-style screenshot or video is required.
        //Small tile image is missing.
        //Please select a Primary Category for your item.
        //Language is not selected.

        // 640x400
        // 128x128
        // 440x280

        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150128

            Console.WriteLine("enter WebGLHZBlendCharacter");

            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self               = Native.self;
            dynamic self_chrome        = self.chrome;
            object  self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                Console.WriteLine("invoke TheServerWithAppWindow.Invoke");
                ChromeTCPServer.TheServerWithAppWindow.Invoke(AppSource.Text);

                return;
            }
            #endregion


            { TexturesImages ref0; }

            // http://www.realitymeltdown.com/WebGL3/character-controller.html

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150127
            //Native.css
            Native.body.style.margin   = "0px";
            Native.body.style.overflow = IStyle.OverflowEnum.hidden;

            //Error CS0246  The type or namespace name 'THREE' could not be found(are you missing a using directive or an assembly reference?)	WebGLHZBlendCharacter Application.cs  46
            // used by, for?
            var clock = new THREE.Clock();
            //var keys = new { LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, A = 65, S = 83, D = 68, W = 87 };


            var scene    = new THREE.Scene();
            var skyScene = new THREE.Scene();

            scene.fog = new THREE.Fog(0xA26D41, 1000, 20000);

            //scene.add(new THREE.AmbientLight(0xaaaaaa));
            scene.add(new THREE.AmbientLight(0xffffff));

            var lightOffset = new THREE.Vector3(0, 1000, 1000.0);

            var light = new THREE.DirectionalLight(0xffffff, 1.0);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth  = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.3;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear   = 10;
            xlight.shadowCameraFar    = 10000;
            xlight.shadowBias         = 0.00001;
            xlight.shadowCameraRight  = 4000;
            xlight.shadowCameraLeft   = -4000;
            xlight.shadowCameraTop    = 4000;
            xlight.shadowCameraBottom = -4000;
            //xlight.shadowCameraVisible = true;

            scene.add(light);

            var renderer = new THREE.WebGLRenderer(new { antialias = true, alpha = false });
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.autoClear        = false;
            renderer.shadowMapEnabled = true;
            renderer.shadowMapType    = THREE.PCFSoftShadowMap;

            renderer.domElement.AttachToDocument();

            // this will mess up
            // three.OrbitControls.js
            // onMouseMove

            //new IStyle(renderer.domElement)
            //{
            //    position = IStyle.PositionEnum.absolute,
            //    left = "0px",
            //    top = "0px",
            //    right = "0px",
            //    bottom = "0px",
            //};


            //new { }.With(
            //    async delegate
            //    {

            //        await Native.window.async.onresize;

            //        // if the reload were fast, then we could actually do that:D
            //        Native.document.location.reload();

            //    }
            //);



            #region create field

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            var planeGeometry = new THREE.PlaneGeometry(1000, 1000);
            var plane         = new THREE.Mesh(planeGeometry,
                                               new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

                                               );
            plane.castShadow    = false;
            plane.receiveShadow = true;


            {
                var parent = new THREE.Object3D();
                parent.add(plane);
                parent.rotation.x = -Math.PI / 2;
                parent.scale.set(100, 100, 100);

                scene.add(parent);
            }

            var random    = new Random();
            var meshArray = new List <THREE.Mesh>();
            var geometry  = new THREE.CubeGeometry(1, 1, 1);

            for (var i = 1; i < 100; i++)
            {
                //THREE.MeshPhongMaterial
                var ii = new THREE.Mesh(geometry,


                                        new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

                                        //new THREE.MeshLambertMaterial(
                                        //new
                                        //{
                                        //    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
                                        //    specular = 0xffaaaa,
                                        //    ambient= 0x050505,
                                        //})

                                        );
                ii.position.x = i % 2 * 500 - 2.5f;

                // raise it up
                ii.position.y    = .5f * 100;
                ii.position.z    = -1 * i * 400;
                ii.castShadow    = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                scene.add(ii);
            }
            #endregion


            #region HZCannon
            new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
                async cube =>
            {
                // https://github.com/mrdoob/three.js/issues/1285
                //cube.children.WithEach(c => c.castShadow = true);

                //cube.traverse(
                //    new Action<THREE.Object3D>(
                //        child =>
                //        {
                //            // does it work? do we need it?
                //            //if (child is THREE.Mesh)

                //            child.castShadow = true;
                //            //child.receiveShadow = true;

                //        }
                //    )
                //);

                // um can edit and continue insert code going back in time?
                cube.scale.x = 10.0;
                cube.scale.y = 10.0;
                cube.scale.z = 10.0;



                //cube.castShadow = true;
                //dae.receiveShadow = true;

                //cube.position.x = -100;

                ////cube.position.y = (cube.scale.y * 50) / 2;
                //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                // if i want to rotate, how do I do it?
                //cube.rotation.z = random() + Math.PI;
                //cube.rotation.x = random() + Math.PI;
                var sw = Stopwatch.StartNew();



                scene.add(cube);
                //interactiveObjects.Add(cube);


                while (true)
                {
                    await Native.window.async.onframe;

                    cube.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;
                }
            }
                );
            #endregion



            var blendMesh = new THREE.SpeedBlendCharacter();
            blendMesh.load(
                new Models.marine_anims().Content.src,
                new Action(
                    delegate
            {
                // buildScene
                //blendMesh.rotation.y = Math.PI * -135 / 180;
                blendMesh.castShadow = true;
                // we cannot scale down we want our shadows
                //blendMesh.scale.set(0.1, 0.1, 0.1);

                scene.add(blendMesh);

                var xtrue = true;
                // run
                blendMesh.setSpeed(1.0);
                blendMesh.showSkeleton(!xtrue);

                var radius = blendMesh.geometry.boundingSphere.radius;


                Native.document.title = new { radius }.ToString();


                var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                camera.position.set(0.0, radius * 3, radius * 3.5);

                var skyCamera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 20000);
                skyCamera.position.set(0.0, radius * 3, radius * 3.5);

                var controls = new THREE.OrbitControls(camera);
                //controls.noPan = true;


                //var loader = new THREE.JSONLoader();
                //loader.load(new Models.ground().Content.src,
                //    new Action<THREE.Geometry, THREE.Material[]>(

                //    (xgeometry, materials) =>
                //    {

                //        var ground = new THREE.Mesh(xgeometry, materials[0]);
                //        ground.scale.set(20, 20, 20);
                //        ground.receiveShadow = true;
                //        ground.castShadow = true;
                //        scene.add(ground);

                //    }
                //    )
                // );

                #region  createSky

                var urls = new[] {
                    new px().src, new nx().src,
                    new py().src, new ny().src,
                    new pz().src, new nz().src,
                };

                var textureCube = THREE.ImageUtils.loadTextureCube(urls);

                dynamic shader = THREE.ShaderLib["cube"];
                shader.uniforms["tCube"].value = textureCube;

                // We're inside the box, so make sure to render the backsides
                // It will typically be rendered first in the scene and without depth so anything else will be drawn in front
                var material = new THREE.ShaderMaterial(new
                {
                    fragmentShader = shader.fragmentShader,
                    vertexShader   = shader.vertexShader,
                    uniforms       = shader.uniforms,
                    depthWrite     = false,
                    side           = THREE.BackSide
                });

                // THREE.CubeGeometry has been renamed to THREE.BoxGeometry
                // The box dimension size doesn't matter that much when the camera is in the center.  Experiment with the values.
                var skyMesh = new THREE.Mesh(new THREE.CubeGeometry(10000, 10000, 10000, 1, 1, 1), material);
                //skyMesh.renderDepth = -10;


                skyScene.add(skyMesh);
                #endregion



                ////var renderTarget = new THREE.WebGLRenderTarget((int)Native.window.Width, (int)Native.window.Height,
                ////    new
                ////    {
                ////        minFilter = THREE.LinearFilter,
                ////        magFilter = THREE.LinearFilter,
                ////        format = THREE.RGBFormat,
                ////        stencilBufer = false
                ////    }
                ////);

                ////var composer = new THREE.EffectComposer(renderer, renderTarget);
                ////composer.addPass(new THREE.RenderPass(skyScene, skyCamera));
                ////composer.addPass(new THREE.RenderPass(scene, camera));

                ////#region vblur
                ////var hblur = new THREE.ShaderPass(THREE.HorizontalTiltShiftShader);
                ////var vblur = new THREE.ShaderPass(THREE.VerticalTiltShiftShader);

                ////var bluriness = 6;

                ////// Show Details	Severity	Code	Description	Project	File	Line
                //////Error CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' WebGLTiltShift Application.cs  183

                ////(hblur.uniforms as dynamic).h.value = bluriness / Native.window.Width;
                ////(vblur.uniforms as dynamic).v.value = bluriness / Native.window.Height;

                ////(hblur.uniforms as dynamic).r.value = 0.5;
                ////(vblur.uniforms as dynamic).r.value = 0.5;
                ////vblur.renderToScreen = true;

                ////composer.addPass(hblur);
                ////composer.addPass(vblur);
                ////#endregion

                //composer.addPass(new THREE.RenderPass(scene, camera));
                //

                #region onframe
                Native.window.onframe +=
                    delegate
                {
                    var scale    = 1.0;
                    var delta    = clock.getDelta();
                    var stepSize = delta * scale;

                    if (stepSize > 0)
                    {
                        //characterController.update(stepSize, scale);
                        //gui.setSpeed(blendMesh.speed);

                        THREE.AnimationHandler.update(stepSize);
                        blendMesh.updateSkeletonHelper();
                    }

                    controls.center.copy(blendMesh.position);
                    controls.center.y += radius * 2.0;
                    controls.update();

                    //var camOffset = camera.position.clone().sub(controls.center);
                    //camOffset.normalize().multiplyScalar(750);
                    camera.position = controls.center.clone();
                    //camera.position = controls.center.clone().add(camOffset);

                    skyCamera.rotation.copy(camera.rotation);


                    //composer.render(0.1);

                    //renderer.clear();
                    renderer.render(skyScene, skyCamera);
                    renderer.render(scene, camera);
                };
                #endregion

                new { }.With(
                    async delegate
                {
                    //while (true)
                    do
                    {
                        camera.aspect = Native.window.aspect;
                        camera.updateProjectionMatrix();
                        renderer.setSize(Native.window.Width, Native.window.Height);

                        // convert to bool?
                    } while (await Native.window.async.onresize);
                    //} while (await Native.window.async.onresize != null);
                }
                    );
            }
                    )
                );
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae

            var oo = new List<THREE.Object3D>();

            #region scene
            var window = Native.window;

            var camera = new THREE.PerspectiveCamera(
                45,
                window.aspect,
                1,
                1000
                //2000
                );
            camera.position.z = 400;

            // scene

            var scene = new THREE.Scene();

            var ambient = new THREE.AmbientLight(0x101030);
            scene.add(ambient);

            var directionalLight = new THREE.DirectionalLight(0xffeedd);
            directionalLight.position.set(0, 0, 1);
            scene.add(directionalLight);

            // WebGLRenderer preserveDrawingBuffer 
            var renderer = new THREE.WebGLRenderer(

                new
                {
                    preserveDrawingBuffer = true
                }
            );

            // https://github.com/mrdoob/three.js/issues/3836
            renderer.setClearColor(0xfffff, 1);

            renderer.setSize(window.Width, window.Height);

            renderer.domElement.AttachToDocument();
            renderer.domElement.style.SetLocation(0, 0);

            this.canvas = (IHTMLCanvas)renderer.domElement;


            var mouseX = 0;
            var mouseY = 0;
            var st = new Stopwatch();
            st.Start();

            Native.window.onframe +=
                delegate
                {
                    renderer.clear();


                    //camera.aspect = window.aspect;
                    //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight;
                    //camera.aspect = canvas.aspect;
                    camera.updateProjectionMatrix();


                    oo.WithEach(
                        x =>
                            x.rotation.y = st.ElapsedMilliseconds * 0.0001
                    );


                    camera.position.x += (mouseX - camera.position.x) * .05;
                    camera.position.y += (-mouseY - camera.position.y) * .05;

                    camera.lookAt(scene.position);

                    renderer.render(scene, camera);


                };

            Native.window.onresize +=
                delegate
                {
                    if (canvas.parentNode == Native.document.body)
                    {
                        renderer.setSize(window.Width, window.Height);
                    }

                };
            #endregion

            new Cisco().Source.Task.ContinueWithResult(
                dae =>
                {
                    //dae.scale.x = 30;
                    //dae.scale.y = 30;
                    //dae.scale.z = 30;

                    //dae.castShadow = true;
                    //dae.receiveShadow = true;

                    dae.scale.x = 5;
                    dae.scale.y = 5;
                    dae.scale.z = 5;

                    dae.position.y = -80;

                    scene.add(dae);
                    oo.Add(dae);


                }
            );
        }
        // http://youtu.be/Lo1IU8UAutE
        // 60hz 2160 4K!

        // The equirectangular projection was used in map creation since it was invented around 100 A.D. by Marinus of Tyre. 

        //        C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hzsky.png" "/sdcard/oculus/360photos/"
        //1533 KB/s(3865902 bytes in 2.461s)

        //C:\Users\Arvo> "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hznosky.png" "/sdcard/oculus/360photos/"
        //1556 KB/s(2714294 bytes in 1.703s)

        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\hz2048c3840x2160.png" "/sdcard/oculus/360photos/"

        // "X:\vr\tape360hzlights\0000.png"
        //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "r:\vr\tape360hzlights\0000.png" "/sdcard/oculus/360photos/hzlights.png"
        // 1421 KB/s (2516443 bytes in 1.729s)



        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809/chrome360hz

        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150809

        // the eye nor the display will be able to do any stereo
        // until tech is near matrix capability. 2019?

        // cubemap can be used for all long range scenes
        // http://www.imdb.com/title/tt0112111/?ref_=nv_sr_1


        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150808/cubemapcamera
        // subst /D a:
        // subst a:  s:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360LightAnimation\Chrome360LightAnimation\bin\Debug\staging\Chrome360LightAnimation.Application\web
        // subst a: z:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360LightAnimation\Chrome360LightAnimation\bin\Debug\staging\Chrome360LightAnimation.Application\web
        // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\Chrome360LightAnimation\Chrome360LightAnimation\bin\Debug\staging\Chrome360LightAnimation.Application\web
        // what if we want to do subst in another winstat or session?

        // ColladaLoader: Empty or non-existing file (assets/Chrome360LightAnimation/S6Edge.dae)

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //FormStyler.AtFormCreated =
            //s =>
            //{
            //    s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

            //    //var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
            //    var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDragWithShadow().AttachTo(s.Context.GetHTMLTarget());



            //    s.Context.GetHTMLTarget().style.backgroundColor = "#efefef";
            //    //s.Context.GetHTMLTarget().style.backgroundColor = "#A26D41";

            //};

#if AsWEBSERVER
            #region += Launched chrome.app.window
            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                // if we run as a server. we can open up on android.

                //chrome.Notification.DefaultTitle = "Nexus7";
                //chrome.Notification.DefaultIconUrl = new x128().src;
                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                     AppSource.Text
                //, AtFormCreated: FormStyler.AtFormCreated

                //AtFormConstructor:
                //    f =>
                //    {
                //        //arg[0] is typeof System.Int32
                //        //script: error JSC1000: No implementation found for this native method, please implement [static System.Drawing.Color.FromArgb(System.Int32)]

                //        // X:\jsc.svn\examples\javascript\forms\Test\TestFromArgb\TestFromArgb\ApplicationControl.cs

                //        f.BackColor = System.Drawing.Color.FromArgb(0xA26D41);
                //    }
                );
                return;
            }
            #endregion
#else

            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    //chrome.runtime.UpdateAvailable += delegate
                    //{
                    //    new chrome.Notification(title: "UpdateAvailable");

                    //};

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "Chrome360LightAnimation");

                        // https://developer.chrome.com/apps/app_window#type-CreateWindowOptions
                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: new
                               {
                                   alwaysOnTop = true,
                                   visibleOnAllWorkspaces = true
                               }
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion


#endif



            //const int size = 128;
            //const int size = 256; // 6 faces, 12KB
            //const int size = 512; // 6 faces, ?

            // WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled.

            //const int size = 720; // 6 faces, ?
            //const int size = 1024; // 6 faces, ?
            //const int cubefacesize = 1024; // 6 faces, ?

            // THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( chrome-extension://aemlnmcokphbneegoefdckonejmknohh/assets/Chrome360LightAnimation/anvil___spherical_hdri_panorama_skybox_by_macsix_d6vv4hs.jpg )
            int cubefacesize = 2048; // 6 faces, ?
                                     // "X:\vr\tape1\0000x2048.png"
                                     // for 60hz render we may want to use float camera percision, not available for ui.
                                     //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\tape1\0000x2048.png" "/sdcard/oculus/360photos/"
                                     //  "x:\util\android-sdk-windows\platform-tools\adb.exe" push "X:\vr\tape1\0000x128.png" "/sdcard/oculus/360photos/"

            //if (Environment.ProcessorCount < 8)
            //    //cubefacesize = 64; // 6 faces, ?
            //    cubefacesize = 128; // 6 faces, ?

            new IHTMLPre { new { Environment.ProcessorCount, cubefacesize } }.AttachToDocument();

            // can we keep fast fps yet highp?

            // can we choose this on runtime? designtime wants fast fps, yet for end product we want highdef on our render farm?
            //const int cubefacesize = 128; // 6 faces, ?

            //var cubecameraoffsetx = 256;
            var cubecameraoffsetx = 400;


            //var uizoom = 0.1;
            //var uizoom = cubefacesize / 128f;
            var uizoom = 128f / cubefacesize;

            var far = 0xffffff;

            Native.css.style.backgroundColor = "blue";
            Native.css.style.overflow = IStyle.OverflowEnum.hidden;

            Native.body.Clear();
            (Native.body.style as dynamic).webkitUserSelect = "text";

            //new IHTMLPre { "can we stream it into VR, shadertoy, youtube 360, youtube stereo yet?" }.AttachToDocument();


            var sw = Stopwatch.StartNew();



            var oo = new List<THREE.Object3D>();

            var window = Native.window;


            // what about physics and that portal rendering?

            // if we are running as a chrome web server, we may also be opened as android ndk webview app
            //var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: window.aspect, near: 1, far: 2000);
            // once we update source
            // save the source
            // manually recompile 
            //cameraPX.position.z = 400;

            //// the camera should be close enough for the object to float off the FOV of PX
            //cameraPX.position.z = 200;

            // scene
            // can we make the 3D object orbit around us ?
            // and
            // stream it to vr?
            var scene = new THREE.Scene();

            // since our cube camera is somewhat a fixed thing
            // would it be easier to move mountains to come to us?
            // once we change code would chrome app be able to let VR know that a new view is available?
            var sceneg = new THREE.Group();
            sceneg.AttachTo(scene);


            // fly up?
            //sceneg.translateZ(-1024);
            // rotate the world, as the skybox then matches what we have on filesystem
            scene.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
            // yet for headtracking we shall rotate camera


            //sceneg.position.set(0, 0, -1024);
            //sceneg.position.set(0, -1024, 0);

            var ambient = new THREE.AmbientLight(0x303030).AttachTo(sceneg);
            //scene.add(ambient);

            // should we fix jsc to do a more correct IDL?
            //var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
            //directionalLight.position.set(0, 0, 1);
            //scene.add(directionalLight);

            #region light
            //var light = new THREE.DirectionalLight(0xffffff, 1.0);
            var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 2.5);
            //var light = new THREE.DirectionalLight(0xffffff, 1.5);
            //var lightOffset = new THREE.Vector3(0, 1000, 2500.0);
            var lightOffset = new THREE.Vector3(
                2000,
                700,

                // lower makes longer shadows 
                700.0
                );
            light.position.copy(lightOffset);
            light.castShadow = true;

            var xlight = light as dynamic;
            xlight.shadowMapWidth = 4096;
            xlight.shadowMapHeight = 2048;

            xlight.shadowDarkness = 0.1;
            //xlight.shadowDarkness = 0.5;

            xlight.shadowCameraNear = 10;
            xlight.shadowCameraFar = 10000;
            xlight.shadowBias = 0.00001;
            xlight.shadowCameraRight = 4000;
            xlight.shadowCameraLeft = -4000;
            xlight.shadowCameraTop = 4000;
            xlight.shadowCameraBottom = -4000;

            // wont show if we add skybox?
            xlight.shadowCameraVisible = true;

            //scene.add(light);
            //light.AttachTo(sceneg);
            #endregion




            // whats WebGLRenderTargetCube do?

            // WebGLRenderer preserveDrawingBuffer 



            var renderer0 = new THREE.WebGLRenderer(

                new
                {
                    antialias = true,
                    alpha = true,
                    preserveDrawingBuffer = true
                }
            );


            // must enable shadows on the renderer 
            renderer0.shadowMapEnabled = true;

            // https://github.com/mrdoob/three.js/issues/3836

            // the construct. white bg
            //renderer0.setClearColor(0xfffff, 1);

            //renderer.setSize(window.Width, window.Height);
            renderer0.setSize(cubefacesize, cubefacesize);

            //renderer0.domElement.AttachToDocument();
            //rendererPX.domElement.style.SetLocation(0, 0);
            //renderer0.domElement.style.SetLocation(4, 4);


            // top

            // http://stackoverflow.com/questions/27612524/can-multiple-webglrenderers-render-the-same-scene


            // need a place to show the cubemap face to GUI 
            // how does the stereo OTOY do it?
            // https://www.opengl.org/wiki/Sampler_(GLSL)

            // http://www.richardssoftware.net/Home/Post/25

            // [+X, –X, +Y, –Y, +Z, –Z] fa



            // move up
            //camera.position.set(-1200, 800, 1200);
            //var cameraoffset = new THREE.Vector3(0, 15, 0);

            // can we aniamte it?
            //var cameraoffset = new THREE.Vector3(0, 800, 1200);
            // can we have linear animation fromcenter of the map to the edge and back?
            // then do the flat earth sun orbit?
            var cameraoffset = new THREE.Vector3(
                // left?
                -512,
                // height?
                //0,
                //1600,
                //1024,

                // if the camera is in the center, would we need to move the scene?
                // we have to move the camera. as we move the scene the lights are messed up
                //2014,
                1024,

                //1200
                0
                // can we hover top of the map?
                );

            // original vieworigin
            //var cameraoffset = new THREE.Vector3(-1200, 800, 1200);



            var camerax = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 0 - 2048, max = 0 + 2048, valueAsNumber = -512, title = "camerax" }.AttachToDocument();
            // up. whats the most high a rocket can go 120km?
            new IHTMLHorizontalRule { }.AttachToDocument();


            // how high is the bunker?
            var cameray = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 64, max = 2048, valueAsNumber = 1024, title = "cameray" }.AttachToDocument();
            new IHTMLBreak { }.AttachToDocument();
            var camerayHigh = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = cameray.max, max = 1024 * 256, valueAsNumber = cameray.max, title = "cameray" }.AttachToDocument();
            new IHTMLHorizontalRule { }.AttachToDocument();
            var cameraz = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 0 - 2048, max = 0 + 2048, valueAsNumber = 0, title = "cameraz" }.AttachToDocument();

            // for render server
            var fcamerax = 0.0;
            var fcameray = 0.0;
            var fcameraz = 0.0;

            //while (await camerax.async.onchange)

            //cameray.onchange += delegate
            //{
            //    if (cameray.valueAsNumber < cameray.max)
            //        camerayHigh.valueAsNumber = camerayHigh.min;
            //};

            camerayHigh.onmousedown += delegate
            {
                //if (camerayHigh.valueAsNumber > camerayHigh.min)
                cameray.valueAsNumber = cameray.max;
            };


            Action applycameraoffset = delegate
            {
                // make sure UI and gpu sync up

                var cy = cameray;

                if (cameray.valueAsNumber < cameray.max)
                    camerayHigh.valueAsNumber = camerayHigh.min;

                if (camerayHigh.valueAsNumber > camerayHigh.min)
                    cameray.valueAsNumber = cameray.max;

                if (cameray.valueAsNumber == cameray.max)
                    cy = camerayHigh;



                cameraoffset = new THREE.Vector3(
                  // left?
                  camerax + fcamerax,
                   // height?
                   //0,
                   //1600,
                   //1024,

                   // if the camera is in the center, would we need to move the scene?
                   // we have to move the camera. as we move the scene the lights are messed up
                   //2014,
                   cy + fcameray,

                   //1200
                   cameraz + fcameraz
                   // can we hover top of the map?
                   );
            };


            #region y
            // need to rotate90?
            var cameraNY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraNY.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNY.lookAt(new THREE.Vector3(0, -1, 0));
                cameraNY.position.add(cameraoffset);
            };

            //cameraNY.lookAt(new THREE.Vector3(0, 1, 0));
            var canvasNY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNY.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 2);
            canvasNY.canvas.title = "NY";
            canvasNY.canvas.AttachToDocument();
            canvasNY.canvas.style.transformOrigin = "0 0";
            canvasNY.canvas.style.transform = $"scale({uizoom})";

            var cameraPY = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraPY.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPY.lookAt(new THREE.Vector3(0, 1, 0));
                cameraPY.position.add(cameraoffset);
            };
            //cameraPY.lookAt(new THREE.Vector3(0, -1, 0));
            var canvasPY = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPY.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 0);
            canvasPY.canvas.title = "PY";
            canvasPY.canvas.AttachToDocument();
            canvasPY.canvas.style.transformOrigin = "0 0";
            canvasPY.canvas.style.transform = $"scale({uizoom})";
            #endregion

            // transpose xz?

            #region x
            var cameraNX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraNX.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNX.lookAt(new THREE.Vector3(0, 0, 1));
                cameraNX.position.add(cameraoffset);
            };
            //cameraNX.lookAt(new THREE.Vector3(0, 0, -1));
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNX.lookAt(new THREE.Vector3(1, 0, 0));
            var canvasNX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNX.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 2, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNX.canvas.title = "NX";
            canvasNX.canvas.AttachToDocument();
            canvasNX.canvas.style.transformOrigin = "0 0";
            canvasNX.canvas.style.transform = $"scale({uizoom})";

            var cameraPX = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            applycameraoffset += delegate
            {
                cameraPX.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPX.lookAt(new THREE.Vector3(0, 0, -1));
                cameraPX.position.add(cameraoffset);
            };
            //cameraPX.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPX.lookAt(new THREE.Vector3(1, 0, 0));
            //cameraPX.lookAt(new THREE.Vector3(-1, 0, 0));
            var canvasPX = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPX.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPX.canvas.title = "PX";
            canvasPX.canvas.AttachToDocument();
            canvasPX.canvas.style.transformOrigin = "0 0";
            canvasPX.canvas.style.transform = $"scale({uizoom})";
            #endregion



            #region z
            var cameraNZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, -1));
            applycameraoffset += delegate
            {
                cameraNZ.position.copy(new THREE.Vector3(0, 0, 0));
                cameraNZ.lookAt(new THREE.Vector3(1, 0, 0));
                cameraNZ.position.add(cameraoffset);
            };
            //cameraNX.lookAt(new THREE.Vector3(-1, 0, 0));
            //cameraNZ.lookAt(new THREE.Vector3(0, 0, 1));
            var canvasNZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasNZ.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 3, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasNZ.canvas.title = "NZ";
            canvasNZ.canvas.AttachToDocument();
            canvasNZ.canvas.style.transformOrigin = "0 0";
            canvasNZ.canvas.style.transform = $"scale({uizoom})";

            var cameraPZ = new THREE.PerspectiveCamera(fov: 90, aspect: 1.0, near: 1, far: far);
            //cameraPZ.lookAt(new THREE.Vector3(1, 0, 0));
            applycameraoffset += delegate
            {
                cameraPZ.position.copy(new THREE.Vector3(0, 0, 0));
                cameraPZ.lookAt(new THREE.Vector3(-1, 0, 0));
                cameraPZ.position.add(cameraoffset);
            };
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, 1));
            //cameraPZ.lookAt(new THREE.Vector3(0, 0, -1));
            var canvasPZ = new CanvasRenderingContext2D(cubefacesize, cubefacesize);
            canvasPZ.canvas.style.SetLocation(cubecameraoffsetx + (int)(uizoom * cubefacesize + 8) * 1, 8 + (int)(uizoom * cubefacesize + 8) * 1);
            canvasPZ.canvas.title = "PZ";
            canvasPZ.canvas.AttachToDocument();
            canvasPZ.canvas.style.transformOrigin = "0 0";
            canvasPZ.canvas.style.transform = $"scale({uizoom})";
            #endregion




            // c++ alias locals would be nice..
            var canvas0 = (IHTMLCanvas)renderer0.domElement;


            var old = new
            {



                CursorX = 0,
                CursorY = 0
            };


            var st = new Stopwatch();
            st.Start();

            //canvas0.css.active.style.cursor = IStyle.CursorEnum.move;

            #region onmousedown
            Native.body.onmousedown +=
                async e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                        return;

                    // movementX no longer works
                    old = new
                    {


                        e.CursorX,
                        e.CursorY
                    };


                    //e.CaptureMouse();
                    var release = e.Element.CaptureMouse();
                    await e.Element.async.onmouseup;

                    release();


                };
            #endregion



            // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs
            #region onmousemove
            Native.body.onmousemove +=
                e =>
                {
                    if (e.Element.nodeName.ToLower() != "canvas")
                    {
                        Native.body.style.cursor = IStyle.CursorEnum.@default;
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();


                    Native.body.style.cursor = IStyle.CursorEnum.move;

                    var pointerLock = canvas0 == Native.document.pointerLockElement;


                    //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX });

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {

                        oo.WithEach(
                            x =>
                            {
                                x.rotation.y += 0.006 * (e.CursorX - old.CursorX);
                                x.rotation.x += 0.006 * (e.CursorY - old.CursorY);
                            }
                        );

                        old = new
                        {


                            e.CursorX,
                            e.CursorY
                        };



                    }

                };
            #endregion

            // THREE.WebGLProgram: gl.getProgramInfoLog() C:\fakepath(78,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll
            // THREE.WebGLProgram: gl.getProgramInfoLog() (79,3-98): warning X3557: loop only executes for 1 iteration(s), forcing loop to unroll

            // http://www.roadtovr.com/youtube-confirms-stereo-3d-360-video-support-coming-soon/
            // https://www.youtube.com/watch?v=D-Wl9jAB45Q



            #region spherical
            var gl = new WebGLRenderingContext(alpha: true, preserveDrawingBuffer: true);
            var c = gl.canvas.AttachToDocument();

            //  3840x2160

            //c.style.SetSize(3840, 2160);

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150722/360-youtube


            c.width = 3840;
            c.height = 2160;


            //c.width = 3840 * 2;
            //c.height = 2160 * 2;


            //c.width = 3840;
            //c.height = 2160;
            // 1,777777777777778

            // https://www.youtube.com/watch?v=fTfJwzRsE-w
            //c.width = 7580;
            //c.height = 3840;
            //1,973958333333333

            //7580
            //    3840

            // wont work
            //c.width = 8192;
            //c.height = 4096;


            // this has the wrong aspect?
            //c.width = 6466;
            //c.height = 3232;

            new IHTMLPre { new { c.width, c.height } }.AttachToDocument();

            //6466x3232

            //var suizoom = 720f / c.height;
            //var suizoom = 360f / c.height;
            var suizoom = 480f / c.width;

            c.style.transformOrigin = "0 0";
            c.style.transform = $"scale({suizoom})";
            //c.style.backgroundColor = "yellow";
            c.style.position = IStyle.PositionEnum.absolute;

            c.style.SetLocation(8 + (int)(uizoom * cubefacesize + 8) * 0, 8 + (int)(uizoom * cubefacesize + 8) * 3);

            var pass = new CubeToEquirectangular.Library.ShaderToy.EffectPass(
                       null,
                       gl,
                       precission: CubeToEquirectangular.Library.ShaderToy.DetermineShaderPrecission(gl),
                       supportDerivatives: gl.getExtension("OES_standard_derivatives") != null,
                       callback: null,
                       obj: null,
                       forceMuted: false,
                       forcePaused: false,
                       //quadVBO: Library.ShaderToy.createQuadVBO(gl, right: 0, top: 0),
                       outputGainNode: null
                   );

            // how shall we upload our textures?
            // can we reference GLSL.samplerCube yet?
            //pass.mInputs[0] = new samplerCube { };
            pass.mInputs[0] = new CubeToEquirectangular.Library.ShaderToy.samplerCube { };

            pass.MakeHeader_Image();
            var vs = new Shaders.ProgramFragmentShader();
            pass.NewShader_Image(vs);

            #endregion




            var frame0 = new HTML.Images.FromAssets.galaxy_starfield().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets.tiles_regrid().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets.anvil___spherical_hdri_panorama_skybox_by_macsix_d6vv4hs().AttachToDocument();
            //var xor = new HTML.Images.FromAssets.Orion360_test_image_8192x4096().AttachToDocument();
            //var xor = new HTML.Images.FromAssets._2_no_clouds_4k().AttachToDocument();
            //var frame0 = new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().AttachToDocument();


            // 270px
            //xor.style.height = "";
            frame0.style.height = "270px";
            frame0.style.width = "480px";
            frame0.style.SetLocation(
                8 + (int)(uizoom * cubefacesize + 8) * 0 + 480 + 16, 8 + (int)(uizoom * cubefacesize + 8) * 3);



            #region  skybox
            // what shall the skybox do if we reach upper altitude?
            // fade into space skybox ?
            var skybox = new THREE.Mesh(new THREE.SphereGeometry(far * 0.9, 50, 50),
           new THREE.MeshBasicMaterial(new
           {
               map = THREE.ImageUtils.loadTexture(
                  //new HTML.Images.FromAssets._2294472375_24a3b8ef46_o().src
                  //new HTML.Images.FromAssets._4008650304_7f837ccbb7_b().src
                  frame0.src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20130616_222058().src
                   //new WebGLEquirectangularPanorama.HTML.Images.FromAssets.PANO_20121225_210448().src

                   )
           }));
            skybox.scale.x = -1;
            skybox.AttachTo(sceneg);
            #endregion



            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI / 2);
            //mesh.rotateOnAxis(new THREE.Vector3(1, 0, 0), -Math.PI / 2);

            // dont need the fixup. unless we want to animate the sky rotate?
            //mesh.rotateOnAxis(new THREE.Vector3(0, 1, 0), -Math.PI / 2);


            // hide the sky to see camera lines?
            //  can we show this as HUD on VR in webview?
            //skybox.visible = false;
            //scene.add(skybox);




            //new IHTMLButton { }

            #region DirectoryEntry
            var dir = default(DirectoryEntry);

            new IHTMLButton { "openDirectory" }.AttachToDocument().onclick += async delegate
            {
                dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });
            };

            frame0.onclick += delegate
            {
                // http://paulbourke.net/papers/vsmm2006/vsmm2006.pdf
                //            A method of creating synthetic stereoscopic panoramic images that can be implemented
                //in most rendering packages has been presented. If single panoramic pairs can be created
                //then stereoscopic panoramic movies are equally possible giving rise to the prospect of
                //movies where the viewer can interact with, at least with regard to what they choose to look
                //at.These images can be projected so as to engage the two features of the human visual
                //system that assist is giving us a sense of immersion, the feeling of “being there”. That is,
                //imagery that contains parallax information as captured from two horizontally separated eye
                //positions (stereopsis)and imagery that fills our peripheral vision.The details that define
                //how the two panoramic images should be created in rendering packages are provided, in
                //particular, how to precisely configure the virtual cameras and control the distance to zero
                //parallax.

                // grab a frame

                if (dir == null)
                {
                    // not exporting to file system?
                    var f0 = new IHTMLImage { src = gl.canvas.toDataURL() };

                    //var f0 = (IHTMLImage)gl.canvas;
                    //var f0 = (IHTMLImage)gl.canvas;
                    //var base64 = gl.canvas.toDataURL();


                    //frame0.src = base64;
                    frame0.src = f0.src;

                    // 7MB!

                    return;
                }

                //                // ---------------------------
                //IrfanView
                //---------------------------
                //Warning !
                //The file: "X:\vr\tape1\0001.jpg" is a PNG file with incorrect extension !
                //Rename ?
                //---------------------------
                //Yes   No   
                //---------------------------

                // haha this will render the thumbnail.
                //dir.WriteAllBytes("0000.png", frame0);

                //dir.WriteAllBytes("0000.png", gl.canvas);

                var glsw = Stopwatch.StartNew();
                dir.WriteAllBytes("0000.png", gl);

                new IHTMLPre { new { glsw.ElapsedMilliseconds } }.AttachToDocument();

                // {{ ElapsedMilliseconds = 1548 }}

                // 3.7MB
                // 3840x2160

            };

            #endregion

            var vsync = default(TaskCompletionSource<object>);

            new IHTMLButton {
                "render 60hz 30sec"
            }.AttachToDocument().onclick += async e =>
            {
                e.Element.disabled = true;


                var total = Stopwatch.StartNew();
                var status = "rendering... " + new { dir };

                new IHTMLPre { () => status }.AttachToDocument();

                if (dir == null)
                {
                    //dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });
                }

                total.Restart();



                vsync = new TaskCompletionSource<object>();
                await vsync.Task;

                status = "rendering... vsync";

                var frameid = -1;

                goto beforeframe;
                //fcamerax = -15.0;

                // parallax offset?

                await_nextframe:


                var filename = frameid.ToString().PadLeft(4, '0') + ".png";
                status = "rendering... " + new { frameid, filename };


                vsync = new TaskCompletionSource<object>();
                await vsync.Task;

                // frame0 has been rendered

                var swcapture = Stopwatch.StartNew();
                status = "WriteAllBytes... " + new { filename };
                //await Native.window.async.onframe;

                if (dir != null)
                    // https://code.google.com/p/chromium/issues/detail?id=404301
                    await dir.WriteAllBytes(filename, gl);

                //await dir.WriteAllBytes(filename, gl.canvas);

                status = "WriteAllBytes... done " + new { fcamerax, filename, swcapture.ElapsedMilliseconds };
                status = "rdy " + new { filename, fcamerax };
                //await Native.window.async.onframe;



                beforeframe:

                // speed? S6 slow motion?
                // this is really slow. if we do x4x2 =x8 
                // https://www.youtube.com/watch?v=r76ULW16Ib8
                //fcamerax += 16 * (1.0 / 60.0);
                fcamerax = 128 * Math.Sin(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f));
                fcameraz = 256 * Math.Cos(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f));


                // up
                fcameray = 16 * Math.Cos(Math.PI * (frameid - (60 * 30 / 2f)) / (60 * 30 / 2f));

                //fcamerax += (1.0 / 60.0);

                //fcamerax += (1.0 / 60.0) * 120;

                if (Environment.ProcessorCount < 8)
                    frameid += 30;
                else
                    frameid++;

                // 60hz 30sec
                if (frameid < 60 * 30)
                {
                    // Blob GC? either this helms or the that we made a Blob static. 
                    await Task.Delay(11);

                    goto await_nextframe;
                }

                total.Stop();
                status = "all done " + new { frameid, total.ElapsedMilliseconds };
                vsync = default(TaskCompletionSource<object>);
                // http://stackoverflow.com/questions/22899333/delete-javascript-blobs

                e.Element.disabled = false;
            };

            // "Z:\jsc.svn\examples\javascript\WebGL\WebGLColladaExperiment\WebGLColladaExperiment\WebGLColladaExperiment.csproj"

            #region WebGLRah66Comanche
            // why isnt it being found?
            // "Z:\jsc.svn\examples\javascript\WebGL\collada\WebGLRah66Comanche\WebGLRah66Comanche\WebGLRah66Comanche.csproj"
            new global::WebGLRah66Comanche.Comanche(
            ).Source.Task.ContinueWithResult(
                dae =>
                {
                    dae.AttachTo(sceneg);
                    //dae.position.y = -40;
                    //dae.position.z = 280;
                    //scene.add(dae);
                    //oo.Add(dae);

                    // wont do it
                    //dae.castShadow = true;

                    dae.children[0].children[0].children.WithEach(x => x.castShadow = true);


                    // the rotors?
                    dae.children[0].children[0].children.Last().children.WithEach(x => x.castShadow = true);


                    dae.scale.set(0.5, 0.5, 0.5);
                    dae.position.x = -900;
                    dae.position.z = +900;

                    // raise it up
                    dae.position.y = 400;

                    //var sw = Stopwatch.StartNew();

                    //Native.window.onframe += delegate
                    //{
                    //    //dae.children[0].children[0].children.Last().al
                    //    //dae.children[0].children[0].children.Last().rotation.z = sw.ElapsedMilliseconds * 0.01;
                    //    //dae.children[0].children[0].children.Last().rotation.x = sw.ElapsedMilliseconds * 0.01;
                    //    dae.children[0].children[0].children.Last().rotation.y = sw.ElapsedMilliseconds * 0.01;
                    //};
                }
            );
            #endregion



            #region tree
            // "Z:\jsc.svn\examples\javascript\WebGL\WebGLGodRay\WebGLGodRay\WebGLGodRay.csproj"

            var materialScene = new THREE.MeshBasicMaterial(new { color = 0x000000, shading = THREE.FlatShading });
            var tloader = new THREE.JSONLoader();

            // http://stackoverflow.com/questions/16539736/do-not-use-system-runtime-compilerservices-dynamicattribute-use-the-dynamic
            // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.dynamicattribute%28v=vs.110%29.aspx
            //System.Runtime.CompilerServices.DynamicAttribute

            tloader.load(

                new WebGLGodRay.Models.tree().Content.src,

                new Action<THREE.Geometry>(
                xgeometry =>
                {

                    var treeMesh = new THREE.Mesh(xgeometry, materialScene);
                    treeMesh.position.set(0, -150, -150);
                    treeMesh.position.x = -900;
                    treeMesh.position.z = -900;

                    treeMesh.position.y = 25;

                    var tsc = 400;
                    treeMesh.scale.set(tsc, tsc, tsc);

                    treeMesh.matrixAutoUpdate = false;
                    treeMesh.updateMatrix();


                    //treeMesh.AttachTo(scene);
                    treeMesh.AttachTo(sceneg);

                }
                )
                );
            #endregion


            // http://learningthreejs.com/blog/2013/09/16/how-to-make-the-earth-in-webgl/

            #region create floor

            // THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.
            // can we have our checkerboard?

            var floorColors = new[] {
                0xA26D41,
                0xA06040,
                0xAF6F4F,
                // marker to detect horizon
                0xAF0000,



                0xA26D41,
                0xA06040,
                0xAF6F4F,
                // marker to detect horizon
                0x006D00,



                0xA26D41,
                0xA06040,
                0xAF6F4F,
                // marker to detect horizon
                0x0000FF
            };


            // human eye can see up to 10miles, then horizion flattens out.
            var planeGeometry = new THREE.CubeGeometry(2048, 1, 2048);
            var planeGeometryMarkerH = new THREE.CubeGeometry(2048, 1, 2048 * 5);


            var planeGeometryMarkerV = new THREE.CubeGeometry(2048 * 5 * 4, 1, 2048 * 4);
            var planeGeometryV = new THREE.CubeGeometry(2048 * 4, 1, 2048 * 4);
            ////var floor0 = new THREE.Mesh(planeGeometry,
            ////        new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })

            ////    );
            //////plane.castShadow = false;
            ////floor0.receiveShadow = true;
            ////floor0.AttachTo(sceneg);

            ////var floor1 = new THREE.Mesh(planeGeometry,
            ////       //new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
            ////       new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

            ////   );
            //////plane.castShadow = false;
            ////floor1.receiveShadow = true;
            ////floor1.position.set(2048, 0, 1024);
            ////floor1.AttachTo(sceneg);

            // can we see horizon?
            for (int i = 0; i < 3 * 256; i++)
            {
                var planeGeometry0 = planeGeometry;

                if (i % 4 == 3)
                {
                    planeGeometry0 = planeGeometryMarkerH;

                    // for high altitude zoom level

                    var i4 = (i / 4);


                    var planeGeometryV0 = planeGeometryV;

                    if (i4 % 4 == 3)
                        planeGeometryV0 = planeGeometryMarkerV;

                    {
                        var floor2 = new THREE.Mesh(planeGeometryV0,
                            //new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
                            new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = floorColors[i4 % floorColors.Length], specular = 0xA26D41, shininess = 1 })

                        );
                        //plane.castShadow = false;
                        floor2.receiveShadow = true;
                        floor2.position.set(1024 * -i, 0, 2048 * i);
                        floor2.AttachTo(scene);
                    }


                    {
                        var floor2 = new THREE.Mesh(planeGeometryV0,
                            //new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
                            new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = floorColors[(i / 4) % floorColors.Length], specular = 0xA26D41, shininess = 1 })

                        );
                        //plane.castShadow = false;
                        floor2.receiveShadow = true;
                        floor2.position.set(-1024 * -i, 0, -2048 * i);
                        floor2.AttachTo(scene);
                    }
                }

                {
                    var floor2 = new THREE.Mesh(planeGeometry0,
                        //new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
                        new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = floorColors[i % floorColors.Length], specular = 0xA26D41, shininess = 1 })

                    );
                    //plane.castShadow = false;
                    floor2.receiveShadow = true;
                    floor2.position.set(2048 * i, 0, 1024 * i);
                    floor2.AttachTo(scene);
                }

                // flipz
                {
                    var floor2 = new THREE.Mesh(planeGeometry0,
                        //new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = 0xA26D41, specular = 0xA26D41, shininess = 1 })
                        new THREE.MeshPhongMaterial(new { ambient = 0x101010, color = floorColors[i % floorColors.Length], specular = 0xA26D41, shininess = 1 })

                    );
                    //plane.castShadow = false;
                    floor2.receiveShadow = true;
                    floor2.position.set(2048 * -i, 0, 1024 * -i);
                    floor2.AttachTo(scene);
                }
            }

            #endregion



            // "shadow cameras" show the light source and direction

            // spotlight #1 -- yellow, dark shadow
            var spotlight = new THREE.SpotLight(0xffff00);
            spotlight.position.set(-60, 150, -30);
            //spotlight.shadowCameraVisible = true;
            spotlight.shadowDarkness = 0.95;
            spotlight.intensity = 2;
            // must enable shadow casting ability for the light
            spotlight.castShadow = true;
            scene.add(spotlight);

            // spotlight #2 -- red, light shadow
            var spotlight2 = new THREE.SpotLight(0xff0000);
            //var spotlight2 = new THREE.SpotLight(0xffff00);
            spotlight2.position.set(60, 150, -60);
            scene.add(spotlight2);
            //spotlight2.shadowCameraVisible = true;
            spotlight2.shadowDarkness = 0.70;
            spotlight2.intensity = 2;
            spotlight2.castShadow = true;


            // THREE.WebGLProgram: gl.getProgramInfoLog() Pixel shader sampler count exceeds MAX_TEXTURE_IMAGE_UNITS (16).
            for (int i = 0; i < 8; i++)
            {

                // spotlight #3 blue
                var spotlight3 = new THREE.SpotLight(0x0000ff);
                //var spotlight3 = new THREE.SpotLight(0x00ffff);
                spotlight3.position.set(150 * i, 80, -100);
                //spotlight3.shadowCameraVisible = true;
                spotlight3.shadowDarkness = 0.95;
                spotlight3.intensity = 2;
                spotlight3.castShadow = true;
                scene.add(spotlight3);
                // change the direction this spotlight is facing
                var lightTarget = new THREE.Object3D();
                lightTarget.position.set(150 * i, 10, -100);
                scene.add(lightTarget);
                spotlight3.target = lightTarget;



            }





            // cube: mesh to cast shadows
            #region castShadow
            var cubeGeometry = new THREE.CubeGeometry(50, 50, 50);
            var cubeMaterial = new THREE.MeshLambertMaterial(new { color = 0x888888 });

            var cube0 = new THREE.Mesh(cubeGeometry, cubeMaterial);
            //cube.position.set(0, 50, 0);
            cube0.position.set(0, 100, 0);
            // Note that the mesh is flagged to cast shadows
            cube0.castShadow = true;
            scene.add(cube0);

            // floor: mesh to receive shadows

            #endregion






            #region create walls

            var random = new Random();
            var meshArray = new List<THREE.Mesh>();
            var geometry = new THREE.CubeGeometry(1, 1, 1);
            //var sw = Stopwatch.StartNew();

            for (var i = 3; i < 9; i++)
            {

                //THREE.MeshPhongMaterial
                var ii = new THREE.Mesh(geometry,


                    new THREE.MeshPhongMaterial(new { ambient = 0x000000, color = 0xA06040, specular = 0xA26D41, shininess = 1 })

                    //new THREE.MeshLambertMaterial(
                    //new
                    //{
                    //    color = (Convert.ToInt32(0xffffff * random.NextDouble())),
                    //    specular = 0xffaaaa,
                    //    ambient= 0x050505, 
                    //})

                    );
                ii.position.x = i % 7 * 200 - 2.5f;

                // raise it up
                ii.position.y = .5f * 100 * i;
                ii.position.z = -1 * i * 100;

                ii.castShadow = true;
                ii.receiveShadow = true;
                //ii.scale.set(100, 100, 100 * i);
                ii.scale.set(100, 100 * i, 100);


                meshArray.Add(ii);

                //scene.add(ii);
                ii.AttachTo(sceneg);

                if (i % 2 == 0)
                {

                    // Z:\jsc.svn\examples\javascript\WebGL\WebGLHZBlendCharacter\WebGLHZBlendCharacter\Application.cs
#if FWebGLHZBlendCharacter
                    #region SpeedBlendCharacter
                    var _i = i;
                    { WebGLHZBlendCharacter.HTML.Pages.TexturesImages ref0; }

                    var blendMesh = new THREE.SpeedBlendCharacter();
                    blendMesh.load(
                        new WebGLHZBlendCharacter.Models.marine_anims().Content.src,
                        new Action(
                            delegate
                            {
                                // buildScene
                                //blendMesh.rotation.y = Math.PI * -135 / 180;
                                blendMesh.castShadow = true;
                                // we cannot scale down we want our shadows
                                //blendMesh.scale.set(0.1, 0.1, 0.1);

                                blendMesh.position.x = (_i + 2) % 7 * 200 - 2.5f;

                                // raise it up
                                //blendMesh.position.y = .5f * 100;
                                blendMesh.position.z = -1 * _i * 100;


                                var xtrue = true;
                                // run
                                blendMesh.setSpeed(1.0);

                                // will in turn call THREE.AnimationHandler.play( this );
                                blendMesh.run.play();
                                // this wont help. bokah does not see the animation it seems.
                                blendMesh.run.update(1);

                                blendMesh.showSkeleton(!xtrue);

                                //scene.add(blendMesh);
                                blendMesh.AttachTo(sceneg);


                                //Native.window.onframe +=
                                // delegate
                                // {

                                //     blendMesh.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;



                                //     ii.rotation.y = Math.PI * 0.0002 * sw.ElapsedMilliseconds;

                                // };

                            }
                        )
                    );
                    #endregion
#endif
                }

            }
            #endregion


            //#region HZCannon
            //// "Z:\jsc.svn\examples\javascript\WebGL\HeatZeekerRTSOrto\HeatZeekerRTSOrto\HeatZeekerRTSOrto.csproj"
            //new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
            //    async cube =>
            //    {
            //        // https://github.com/mrdoob/three.js/issues/1285
            //        //cube.children.WithEach(c => c.castShadow = true);

            //        //cube.traverse(
            //        //    new Action<THREE.Object3D>(
            //        //        child =>
            //        //        {
            //        //            // does it work? do we need it?
            //        //            //if (child is THREE.Mesh)

            //        //            child.castShadow = true;
            //        //            //child.receiveShadow = true;

            //        //        }
            //        //    )
            //        //);

            //        // um can edit and continue insert code going back in time?
            //        cube.scale.x = 10.0;
            //        cube.scale.y = 10.0;
            //        cube.scale.z = 10.0;



            //        //cube.castShadow = true;
            //        //dae.receiveShadow = true;

            //        //cube.position.x = -100;

            //        ////cube.position.y = (cube.scale.y * 50) / 2;
            //        //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



            //        // if i want to rotate, how do I do it?
            //        //cube.rotation.z = random() + Math.PI;
            //        //cube.rotation.x = random() + Math.PI;
            //        //var sw2 = Stopwatch.StartNew();



            //        cube.AttachTo(sceneg);
            //        //scene.add(cube);
            //        //interactiveObjects.Add(cube);

            //        // offset is wrong
            //        //while (true)
            //        //{
            //        //    await Native.window.async.onframe;

            //        //    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

            //        //}
            //    }
            //);
            //#endregion


            #region HZCannon
            new HeatZeekerRTSOrto.HZCannon().Source.Task.ContinueWithResult(
                async cube =>
                {
                    // https://github.com/mrdoob/three.js/issues/1285
                    //cube.children.WithEach(c => c.castShadow = true);

                    //cube.traverse(
                    //    new Action<THREE.Object3D>(
                    //        child =>
                    //        {
                    //            // does it work? do we need it?
                    //            //if (child is THREE.Mesh)

                    //            child.castShadow = true;
                    //            //child.receiveShadow = true;

                    //        }
                    //    )
                    //);

                    // um can edit and continue insert code going back in time?
                    cube.scale.x = 10.0;
                    cube.scale.y = 10.0;
                    cube.scale.z = 10.0;



                    //cube.castShadow = true;
                    //dae.receiveShadow = true;


                    // jsc shat about out of band code patching?
                    cube.position.z = 600;
                    cube.position.x = -900;
                    //cube.position.y = -400;

                    //cube.position.x = -100;
                    //cube.position.y = -400;

                    ////cube.position.y = (cube.scale.y * 50) / 2;
                    //cube.position.z = Math.Floor((random() * 1000 - 500) / 50) * 50 + 25;



                    // if i want to rotate, how do I do it?
                    //cube.rotation.z = random() + Math.PI;
                    //cube.rotation.x = random() + Math.PI;
                    var sw2 = Stopwatch.StartNew();



                    //scene.add(cube);
                    cube.AttachTo(sceneg);
                    //interactiveObjects.Add(cube);

                    // offset is wrong
                    //while (true)
                    //{
                    //    await Native.window.async.onframe;

                    //    cube.rotation.y = Math.PI * 0.0002 * sw2.ElapsedMilliseconds;

                    //}
                }
            );
            #endregion


            #region HZBunker
            new HeatZeekerRTSOrto.HZBunker().Source.Task.ContinueWithResult(
                     cube =>
                     {
                         // https://github.com/mrdoob/three.js/issues/1285
                         //cube.children.WithEach(c => c.castShadow = true);
                         cube.castShadow = true;

                         //cube.traverse(
                         //    new Action<THREE.Object3D>(
                         //        child =>
                         //        {
                         //            // does it work? do we need it?
                         //            //if (child is THREE.Mesh)
                         //            child.castShadow = true;
                         //            //child.receiveShadow = true;

                         //        }
                         //    )
                         //);

                         // um can edit and continue insert code going back in time?
                         cube.scale.x = 10.0;
                         cube.scale.y = 10.0;
                         cube.scale.z = 10.0;

                         //cube.castShadow = true;
                         //dae.receiveShadow = true;

                         cube.position.x = -1000;
                         //cube.position.y = (cube.scale.y * 50) / 2;
                         cube.position.z = 0;

                         cube.AttachTo(sceneg);
                         //scene.add(cube);
                     }
                 );
            #endregion


            new Models.ColladaS6Edge().Source.Task.ContinueWithResult(
                   dae =>
                   {
                       // 90deg
                       dae.rotation.x = -Math.Cos(Math.PI);

                       //dae.scale.x = 30;
                       //dae.scale.y = 30;
                       //dae.scale.z = 30;
                       dae.position.z = -(65 - 200);





                       var scale = 0.9;

                       // jsc, do we have ILObserver available yet?
                       dae.scale.x = scale;
                       dae.scale.y = scale;
                       dae.scale.z = scale;


                       //#region onmousewheel
                       //Native.body.onmousewheel +=
                       //    e =>
                       //    {
                       //        e.preventDefault();

                       //        //camera.position.z = 1.5;

                       //        // min max. shall adjust speed also!
                       //        // max 4.0
                       //        // min 0.6
                       //        dae.position.z -= 10.0 * e.WheelDirection;

                       //        //camera.position.z = 400;
                       //        //dae.position.z = dae.position.z.Max(-200).Min(200);

                       //        //Native.document.title = new { z }.ToString();

                       //    };
                       //#endregion


                       ////dae.position.y = -80;

                       //dae.AttachTo(sceneg);
                       ////scene.add(dae);
                       //oo.Add(dae);




                       // view-source:http://threejs.org/examples/webgl_multiple_canvases_circle.html
                       // https://threejsdoc.appspot.com/doc/three.js/src.source/extras/cameras/CubeCamera.js.html
                       Native.window.onframe +=
                           e =>
                           {
                               // let render man know..
                               if (vsync != null)
                                   if (vsync.Task.IsCompleted)
                                       return;


                               //if (pause) return;
                               //if (pause.@checked)
                               //    return;


                               // can we float out of frame?
                               // haha. a bit too flickery.
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.01) * 50.0;
                               //dae.position.x = Math.Sin(e.delay.ElapsedMilliseconds * 0.001) * 190.0;
                               dae.position.x = Math.Sin(fcamerax * 0.001) * 190.0;
                               dae.position.y = Math.Cos(fcamerax * 0.001) * 90.0;
                               // manual rebuild?
                               // red compiler notifies laptop chrome of pending update
                               // app reloads

                               applycameraoffset();
                               renderer0.clear();
                               //rendererPY.clear();

                               //cameraPX.aspect = canvasPX.aspect;
                               //cameraPX.updateProjectionMatrix();

                               // um what does this do?
                               //cameraPX.position.z += (z - cameraPX.position.z) * e.delay.ElapsedMilliseconds / 200.0;
                               // mousewheel allos the camera to move closer
                               // once we see the frame in vr, can we udp sync vr tracking back to laptop?


                               //this.targetPX.x += 1;
                               //this.targetNX.x -= 1;

                               //this.targetPY.y += 1;
                               //this.targetNY.y -= 1;

                               //this.targetPZ.z += 1;
                               //this.targetNZ.z -= 1;

                               // how does the 360 or shadertoy want our cubemaps?


                               // and then rotate right?

                               // how can we render cubemap?


                               #region x
                               // upside down?
                               renderer0.render(scene, cameraPX);
                               canvasPX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNX);
                               canvasNX.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion

                               #region z
                               renderer0.render(scene, cameraPZ);
                               canvasPZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);

                               renderer0.render(scene, cameraNZ);
                               canvasNZ.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               #endregion



                               #region y
                               renderer0.render(scene, cameraPY);

                               //canvasPY.save();
                               //canvasPY.translate(0, size);
                               //canvasPY.rotate((float)(-Math.PI / 2));
                               canvasPY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasPY.restore();


                               renderer0.render(scene, cameraNY);
                               //canvasNY.save();
                               //canvasNY.translate(size, 0);
                               //canvasNY.rotate((float)(Math.PI / 2));
                               canvasNY.drawImage((IHTMLCanvas)renderer0.domElement, 0, 0, cubefacesize, cubefacesize);
                               //canvasNY.restore();
                               // ?
                               #endregion


                               //renderer0.render(scene, cameraPX);


                               //rendererPY.render(scene, cameraPY);

                               // at this point we should be able to render the sphere texture

                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_X = 34070;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Y = 34071;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072;
                               //public const uint TEXTURE_CUBE_MAP_POSITIVE_Z = 34073;
                               //public const uint TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074;


                               //var cube0 = new IHTMLImage[] {
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_px(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nx(),

                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_py(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_ny(),


                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_pz(),
                               //        new CSS3DPanoramaByHumus.HTML.Images.FromAssets.humus_nz()
                               //};

                               new[] {
                                   canvasPX, canvasNX,
                                   canvasPY, canvasNY,
                                   canvasPZ, canvasNZ
                               }.WithEachIndex(
                                   (img, index) =>
                                   {
                                       gl.bindTexture(gl.TEXTURE_CUBE_MAP, pass.tex);

                                       //gl.pixelStorei(gl.UNPACK_FLIP_X_WEBGL, false);
                                       gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

                                       // http://stackoverflow.com/questions/15364517/pixelstoreigl-unpack-flip-y-webgl-true

                                       // https://msdn.microsoft.com/en-us/library/dn302429(v=vs.85).aspx
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                                       //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);

                                       gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + (uint)index, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img.canvas);

                                   }
                                );

                               // could do dynamic resolution- fog of war or fog of FOV. where up to 150deg field of vision is encouragedm, not 360
                               pass.Paint_Image(
                                     0,

                                     0,
                                     0,
                                     0,
                                     0
                                //,

                                // gl_FragCoord
                                // cannot be scaled, and can be referenced directly.
                                // need another way to scale
                                //zoom: 0.3f
                                );

                               //paintsw.Stop();


                               // what does it do?
                               gl.flush();

                               // let render man know..
                               if (vsync != null)
                                   if (!vsync.Task.IsCompleted)
                                       vsync.SetResult(null);
                           };


                   }
               );





            Console.WriteLine("do you see it?");
        }