Example #1
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)
        {
            // http://threejs.org/examples/#webgl_postprocessing_godrays
            // view-source:file:///X:/opensource/github/three.js/examples/webgl_postprocessing_godrays.html

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


            var sunPosition         = new THREE.Vector3(0, 1000, -1000);
            var screenSpacePosition = new THREE.Vector3();

            var mouseX = 0;
            var mouseY = 0;

            var windowHalfX = Native.window.Width / 2;
            var windowHalfY = Native.window.Height / 2;

            //var postprocessing = { enabled : true };

            var orbitRadius = 200;

            var bgColor  = 0x000511;
            var sunColor = 0xffee00;


            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151112
            var camera = new THREE.PerspectiveCamera(70, Native.window.aspect, 1, 3000);

            camera.position.z = 200;

            var scene = new THREE.Scene();

            //

            var materialDepth = new THREE.MeshDepthMaterial(new { });


            #region tree
            // X:\jsc.svn\examples\javascript\WebGL\WebGLGodRay\WebGLGodRay\Application.cs

            var materialScene = new THREE.MeshBasicMaterial(new { color = 0x000000, shading = THREE.FlatShading });
            var loader        = 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

            loader.load(

                new Models.tree().Content.src,

                new Action <THREE.Geometry>(
                    xgeometry =>
            {
                var treeMesh = new THREE.Mesh(xgeometry, materialScene);
                treeMesh.position.set(0, -150, -150);

                var tsc = 400;
                treeMesh.scale.set(tsc, tsc, tsc);

                treeMesh.matrixAutoUpdate = false;
                treeMesh.updateMatrix();


                treeMesh.AttachTo(scene);
            }
                    )
                );
            #endregion

            // sphere

            var geo = new THREE.SphereGeometry(1, 20, 10);

            var sphereMesh = new THREE.Mesh(geo, materialScene);

            var sc = 20;
            sphereMesh.scale.set(sc, sc, sc);

            scene.add(sphereMesh);

            var renderer = new THREE.WebGLRenderer(new { antialias = false });

            renderer.setClearColor(bgColor);
            //renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.domElement.AttachToDocument();


            renderer.autoClear   = false;
            renderer.sortObjects = false;


            var postprocessing_scene = new THREE.Scene();

            var postprocessing_camera = new THREE.OrthographicCamera(Native.window.Width / -2, Native.window.Width / 2, Native.window.Height / 2, Native.window.Height / -2, -10000, 10000);
            postprocessing_camera.position.z = 100;

            postprocessing_scene.add(postprocessing_camera);

            var pars = new { minFilter = THREE.LinearFilter, magFilter = THREE.LinearFilter, format = THREE.RGBFormat };

            var postprocessing_rtTextureColors = new THREE.WebGLRenderTarget(Native.window.Width, Native.window.Height, pars);

            // Switching the depth formats to luminance from rgb doesn't seem to work. I didn't
            // investigate further for now.
            // pars.format = THREE.LuminanceFormat;

            // I would have this quarter size and use it as one of the ping-pong render
            // targets but the aliasing causes some temporal flickering

            var postprocessing_rtTextureDepth = new THREE.WebGLRenderTarget(Native.window.Width, Native.window.Height, pars);

            // Aggressive downsize god-ray ping-pong render targets to minimize cost

            var w = Native.window.Width / 4;
            var h = Native.window.Height / 4;
            var postprocessing_rtTextureGodRays1 = new THREE.WebGLRenderTarget(w, h, pars);
            var postprocessing_rtTextureGodRays2 = new THREE.WebGLRenderTarget(w, h, pars);

            // god-ray shaders

            // X:\jsc.svn\market\synergy\THREE\THREE\opensource\gihtub\three.js\build\THREE.ShaderGodRays.idl
            // these are special <script src="js/ShaderGodRays.js"></script>
            var godraysGenShader = THREE.ShaderGodRays["godrays_generate"] as dynamic;
            var postprocessing_godrayGenUniforms       = THREE.UniformsUtils.clone(godraysGenShader.uniforms);
            var postprocessing_materialGodraysGenerate = new THREE.ShaderMaterial(new
            {
                uniforms       = postprocessing_godrayGenUniforms,
                vertexShader   = godraysGenShader.vertexShader,
                fragmentShader = godraysGenShader.fragmentShader
            });

            var godraysCombineShader = THREE.ShaderGodRays["godrays_combine"] as dynamic;
            var postprocessing_godrayCombineUniforms  = THREE.UniformsUtils.clone(godraysCombineShader.uniforms);
            var postprocessing_materialGodraysCombine = new THREE.ShaderMaterial(new
            {
                uniforms       = postprocessing_godrayCombineUniforms,
                vertexShader   = godraysCombineShader.vertexShader,
                fragmentShader = godraysCombineShader.fragmentShader
            });

            var godraysFakeSunShader = THREE.ShaderGodRays["godrays_fake_sun"] as dynamic;
            var postprocessing_godraysFakeSunUniforms = THREE.UniformsUtils.clone(godraysFakeSunShader.uniforms);
            var postprocessing_materialGodraysFakeSun = new THREE.ShaderMaterial(new
            {
                uniforms       = postprocessing_godraysFakeSunUniforms,
                vertexShader   = godraysFakeSunShader.vertexShader,
                fragmentShader = godraysFakeSunShader.fragmentShader
            });

            postprocessing_godraysFakeSunUniforms.bgColor.value.setHex(bgColor);
            postprocessing_godraysFakeSunUniforms.sunColor.value.setHex(sunColor);

            postprocessing_godrayCombineUniforms.fGodRayIntensity.value = 0.75;

            var postprocessing_quad = new THREE.Mesh(
                new THREE.PlaneBufferGeometry(Native.window.Width, Native.window.Height),
                postprocessing_materialGodraysGenerate
                );
            postprocessing_quad.position.z = -9900;
            postprocessing_scene.add(postprocessing_quad);


            #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 = 0xA26D41
            //        //color = 0xff0000
            //    }
            //);

            //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,
                                       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.position.y = -.5f * 100;

                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 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 s2w = 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 = s2w.ElapsedMilliseconds * 0.001;

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



            var sw = Stopwatch.StartNew();

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

            // Show Details	Severity	Code	Description	Project	File	Line
            //Error CS0229  Ambiguity between 'THREE.Math' and 'Math'   WebGLGodRay Application.cs  238

            Native.window.onframe +=
                delegate
            {
                //var time = IDate.now() / 4000;
                var time = sw.ElapsedMilliseconds / 4000.0;

                sphereMesh.position.x = orbitRadius * Math.Cos(time);
                sphereMesh.position.z = orbitRadius * Math.Sin(time) - 100;



                //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.x += (mouseX - camera.position.x) * 0.036;
                //camera.position.y += (-(mouseY) - camera.position.y) * 0.036;

                //camera.lookAt(scene.position);


                // Find the screenspace position of the sun

                screenSpacePosition.copy(sunPosition).project(camera);

                screenSpacePosition.x = (screenSpacePosition.x + 1) / 2;
                screenSpacePosition.y = (screenSpacePosition.y + 1) / 2;

                // Give it to the god-ray and sun shaders

                postprocessing_godrayGenUniforms["vSunPositionScreenSpace"].value.x = screenSpacePosition.x;
                postprocessing_godrayGenUniforms["vSunPositionScreenSpace"].value.y = screenSpacePosition.y;

                postprocessing_godraysFakeSunUniforms["vSunPositionScreenSpace"].value.x = screenSpacePosition.x;
                postprocessing_godraysFakeSunUniforms["vSunPositionScreenSpace"].value.y = screenSpacePosition.y;

                // -- Draw sky and sun --

                // Clear colors and depths, will clear to sky color

                renderer.clearTarget(postprocessing_rtTextureColors, true, true, false);

                // Sun render. Runs a shader that gives a brightness based on the screen
                // space distance to the sun. Not very efficient, so i make a scissor
                // rectangle around the suns position to avoid rendering surrounding pixels.

                var sunsqH = 0.74 * Native.window.Height;     // 0.74 depends on extent of sun from shader
                var sunsqW = 0.74 * Native.window.Height;     // both depend on height because sun is aspect-corrected

                screenSpacePosition.x *= Native.window.Width;
                screenSpacePosition.y *= Native.window.Height;

                renderer.setScissor(screenSpacePosition.x - sunsqW / 2, screenSpacePosition.y - sunsqH / 2, sunsqW, sunsqH);
                renderer.enableScissorTest(true);

                postprocessing_godraysFakeSunUniforms["fAspect"].value = Native.window.aspect;

                postprocessing_scene.overrideMaterial = postprocessing_materialGodraysFakeSun;
                renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureColors);

                renderer.enableScissorTest(false);

                // -- Draw scene objects --

                // Colors

                scene.overrideMaterial = null;
                renderer.render(scene, camera, postprocessing_rtTextureColors);

                // Depth

                scene.overrideMaterial = materialDepth;
                renderer.render(scene, camera, postprocessing_rtTextureDepth, true);

                // -- Render god-rays --

                // Maximum length of god-rays (in texture space [0,1]X[0,1])

                var filterLen = 1.0;

                // Samples taken by filter

                var TAPS_PER_PASS = 6.0;

                // Pass order could equivalently be 3,2,1 (instead of 1,2,3), which
                // would start with a small filter support and grow to large. however
                // the large-to-small order produces less objectionable aliasing artifacts that
                // appear as a glimmer along the length of the beams

                // pass 1 - render into first ping-pong target

                var pass    = 1.0;
                var stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                postprocessing_godrayGenUniforms["tInput"].value    = postprocessing_rtTextureDepth;

                postprocessing_scene.overrideMaterial = postprocessing_materialGodraysGenerate;

                renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays2);

                // pass 2 - render into second ping-pong target

                pass    = 2.0;
                stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                postprocessing_godrayGenUniforms["tInput"].value    = postprocessing_rtTextureGodRays2;

                renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays1);

                // pass 3 - 1st RT

                pass    = 3.0;
                stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                postprocessing_godrayGenUniforms["tInput"].value    = postprocessing_rtTextureGodRays1;

                renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays2);

                // final pass - composite god-rays onto colors

                postprocessing_godrayCombineUniforms["tColors"].value  = postprocessing_rtTextureColors;
                postprocessing_godrayCombineUniforms["tGodRays"].value = postprocessing_rtTextureGodRays2;

                postprocessing_scene.overrideMaterial = postprocessing_materialGodraysCombine;

                renderer.render(postprocessing_scene, postprocessing_camera);
                postprocessing_scene.overrideMaterial = null;
            };



            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);
            }
                );

            //var ze = new ZeProperties();

            //ze.Show();

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

            //ze.Add(() => renderer);
            //ze.Add(() => controls);
            //ze.Add(() => scene);
            //ze.Left = 0;
        }
        // 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; ;

				};
		}
        /// <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://threejs.org/examples/#webgl_postprocessing_godrays
            // view-source:file:///X:/opensource/github/three.js/examples/webgl_postprocessing_godrays.html

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


            var sunPosition = new THREE.Vector3(0, 1000, -1000);
            var screenSpacePosition = new THREE.Vector3();

            var mouseX = 0;
            var mouseY = 0;

            var windowHalfX = Native.window.Width / 2;
            var windowHalfY = Native.window.Height / 2;

            //var postprocessing = { enabled : true };

            var orbitRadius = 200;

            var bgColor = 0x000511;
            var sunColor = 0xffee00;


            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151112
            var camera = new THREE.PerspectiveCamera(70, Native.window.aspect, 1, 3000);
            camera.position.z = 200;

            var scene = new THREE.Scene();

            //

            var materialDepth = new THREE.MeshDepthMaterial(new { });


            #region tree
            // X:\jsc.svn\examples\javascript\WebGL\WebGLGodRay\WebGLGodRay\Application.cs

            var materialScene = new THREE.MeshBasicMaterial(new { color = 0x000000, shading = THREE.FlatShading });
            var loader = 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

            loader.load(

                new Models.tree().Content.src,

                new Action<THREE.Geometry>(
                xgeometry =>
                {

                    var treeMesh = new THREE.Mesh(xgeometry, materialScene);
                    treeMesh.position.set(0, -150, -150);

                    var tsc = 400;
                    treeMesh.scale.set(tsc, tsc, tsc);

                    treeMesh.matrixAutoUpdate = false;
                    treeMesh.updateMatrix();


                    treeMesh.AttachTo(scene);

                }
                )
                );
            #endregion

            // sphere

            var geo = new THREE.SphereGeometry(1, 20, 10);

            var sphereMesh = new THREE.Mesh(geo, materialScene);

            var sc = 20;
            sphereMesh.scale.set(sc, sc, sc);

            scene.add(sphereMesh);

            var renderer = new THREE.WebGLRenderer(new { antialias = false });

            renderer.setClearColor(bgColor);
            //renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.domElement.AttachToDocument();


            renderer.autoClear = false;
            renderer.sortObjects = false;


            var postprocessing_scene = new THREE.Scene();

            var postprocessing_camera = new THREE.OrthographicCamera(Native.window.Width / -2, Native.window.Width / 2, Native.window.Height / 2, Native.window.Height / -2, -10000, 10000);
            postprocessing_camera.position.z = 100;

            postprocessing_scene.add(postprocessing_camera);

            var pars = new { minFilter = THREE.LinearFilter, magFilter = THREE.LinearFilter, format = THREE.RGBFormat };

            var postprocessing_rtTextureColors = new THREE.WebGLRenderTarget(Native.window.Width, Native.window.Height, pars);

            // Switching the depth formats to luminance from rgb doesn't seem to work. I didn't
            // investigate further for now.
            // pars.format = THREE.LuminanceFormat;

            // I would have this quarter size and use it as one of the ping-pong render
            // targets but the aliasing causes some temporal flickering

            var postprocessing_rtTextureDepth = new THREE.WebGLRenderTarget(Native.window.Width, Native.window.Height, pars);

            // Aggressive downsize god-ray ping-pong render targets to minimize cost

            var w = Native.window.Width / 4;
            var h = Native.window.Height / 4;
            var postprocessing_rtTextureGodRays1 = new THREE.WebGLRenderTarget(w, h, pars);
            var postprocessing_rtTextureGodRays2 = new THREE.WebGLRenderTarget(w, h, pars);

            // god-ray shaders

            // X:\jsc.svn\market\synergy\THREE\THREE\opensource\gihtub\three.js\build\THREE.ShaderGodRays.idl
            // these are special <script src="js/ShaderGodRays.js"></script>
            var godraysGenShader = THREE.ShaderGodRays["godrays_generate"] as dynamic;
            var postprocessing_godrayGenUniforms = THREE.UniformsUtils.clone(godraysGenShader.uniforms);
            var postprocessing_materialGodraysGenerate = new THREE.ShaderMaterial(new
            {

                uniforms = postprocessing_godrayGenUniforms,
                vertexShader = godraysGenShader.vertexShader,
                fragmentShader = godraysGenShader.fragmentShader

            });

            var godraysCombineShader = THREE.ShaderGodRays["godrays_combine"] as dynamic;
            var postprocessing_godrayCombineUniforms = THREE.UniformsUtils.clone(godraysCombineShader.uniforms);
            var postprocessing_materialGodraysCombine = new THREE.ShaderMaterial(new
            {

                uniforms = postprocessing_godrayCombineUniforms,
                vertexShader = godraysCombineShader.vertexShader,
                fragmentShader = godraysCombineShader.fragmentShader

            });

            var godraysFakeSunShader = THREE.ShaderGodRays["godrays_fake_sun"] as dynamic;
            var postprocessing_godraysFakeSunUniforms = THREE.UniformsUtils.clone(godraysFakeSunShader.uniforms);
            var postprocessing_materialGodraysFakeSun = new THREE.ShaderMaterial(new
            {

                uniforms = postprocessing_godraysFakeSunUniforms,
                vertexShader = godraysFakeSunShader.vertexShader,
                fragmentShader = godraysFakeSunShader.fragmentShader

            });

            postprocessing_godraysFakeSunUniforms.bgColor.value.setHex(bgColor);
            postprocessing_godraysFakeSunUniforms.sunColor.value.setHex(sunColor);

            postprocessing_godrayCombineUniforms.fGodRayIntensity.value = 0.75;

            var postprocessing_quad = new THREE.Mesh(
                new THREE.PlaneBufferGeometry(Native.window.Width, Native.window.Height),
                postprocessing_materialGodraysGenerate
            );
            postprocessing_quad.position.z = -9900;
            postprocessing_scene.add(postprocessing_quad);


            #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 = 0xA26D41
            //        //color = 0xff0000
            //    }
            //);

            //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,
                    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.position.y = -.5f * 100;

                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 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 s2w = 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 = s2w.ElapsedMilliseconds * 0.001;

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




            var sw = Stopwatch.StartNew();

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

            // Show Details	Severity	Code	Description	Project	File	Line
            //Error CS0229  Ambiguity between 'THREE.Math' and 'Math'   WebGLGodRay Application.cs  238

            Native.window.onframe +=
                delegate
                {
                    //var time = IDate.now() / 4000;
                    var time = sw.ElapsedMilliseconds / 4000.0;

                    sphereMesh.position.x = orbitRadius * Math.Cos(time);
                    sphereMesh.position.z = orbitRadius * Math.Sin(time) - 100;



                    //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.x += (mouseX - camera.position.x) * 0.036;
                    //camera.position.y += (-(mouseY) - camera.position.y) * 0.036;

                    //camera.lookAt(scene.position);


                    // Find the screenspace position of the sun

                    screenSpacePosition.copy(sunPosition).project(camera);

                    screenSpacePosition.x = (screenSpacePosition.x + 1) / 2;
                    screenSpacePosition.y = (screenSpacePosition.y + 1) / 2;

                    // Give it to the god-ray and sun shaders

                    postprocessing_godrayGenUniforms["vSunPositionScreenSpace"].value.x = screenSpacePosition.x;
                    postprocessing_godrayGenUniforms["vSunPositionScreenSpace"].value.y = screenSpacePosition.y;

                    postprocessing_godraysFakeSunUniforms["vSunPositionScreenSpace"].value.x = screenSpacePosition.x;
                    postprocessing_godraysFakeSunUniforms["vSunPositionScreenSpace"].value.y = screenSpacePosition.y;

                    // -- Draw sky and sun --

                    // Clear colors and depths, will clear to sky color

                    renderer.clearTarget(postprocessing_rtTextureColors, true, true, false);

                    // Sun render. Runs a shader that gives a brightness based on the screen
                    // space distance to the sun. Not very efficient, so i make a scissor
                    // rectangle around the suns position to avoid rendering surrounding pixels.

                    var sunsqH = 0.74 * Native.window.Height; // 0.74 depends on extent of sun from shader
                    var sunsqW = 0.74 * Native.window.Height; // both depend on height because sun is aspect-corrected

                    screenSpacePosition.x *= Native.window.Width;
                    screenSpacePosition.y *= Native.window.Height;

                    renderer.setScissor(screenSpacePosition.x - sunsqW / 2, screenSpacePosition.y - sunsqH / 2, sunsqW, sunsqH);
                    renderer.enableScissorTest(true);

                    postprocessing_godraysFakeSunUniforms["fAspect"].value = Native.window.aspect;

                    postprocessing_scene.overrideMaterial = postprocessing_materialGodraysFakeSun;
                    renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureColors);

                    renderer.enableScissorTest(false);

                    // -- Draw scene objects --

                    // Colors

                    scene.overrideMaterial = null;
                    renderer.render(scene, camera, postprocessing_rtTextureColors);

                    // Depth

                    scene.overrideMaterial = materialDepth;
                    renderer.render(scene, camera, postprocessing_rtTextureDepth, true);

                    // -- Render god-rays --

                    // Maximum length of god-rays (in texture space [0,1]X[0,1])

                    var filterLen = 1.0;

                    // Samples taken by filter

                    var TAPS_PER_PASS = 6.0;

                    // Pass order could equivalently be 3,2,1 (instead of 1,2,3), which
                    // would start with a small filter support and grow to large. however
                    // the large-to-small order produces less objectionable aliasing artifacts that
                    // appear as a glimmer along the length of the beams

                    // pass 1 - render into first ping-pong target

                    var pass = 1.0;
                    var stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                    postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                    postprocessing_godrayGenUniforms["tInput"].value = postprocessing_rtTextureDepth;

                    postprocessing_scene.overrideMaterial = postprocessing_materialGodraysGenerate;

                    renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays2);

                    // pass 2 - render into second ping-pong target

                    pass = 2.0;
                    stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                    postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                    postprocessing_godrayGenUniforms["tInput"].value = postprocessing_rtTextureGodRays2;

                    renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays1);

                    // pass 3 - 1st RT

                    pass = 3.0;
                    stepLen = filterLen * Math.Pow(TAPS_PER_PASS, -pass);

                    postprocessing_godrayGenUniforms["fStepSize"].value = stepLen;
                    postprocessing_godrayGenUniforms["tInput"].value = postprocessing_rtTextureGodRays1;

                    renderer.render(postprocessing_scene, postprocessing_camera, postprocessing_rtTextureGodRays2);

                    // final pass - composite god-rays onto colors

                    postprocessing_godrayCombineUniforms["tColors"].value = postprocessing_rtTextureColors;
                    postprocessing_godrayCombineUniforms["tGodRays"].value = postprocessing_rtTextureGodRays2;

                    postprocessing_scene.overrideMaterial = postprocessing_materialGodraysCombine;

                    renderer.render(postprocessing_scene, postprocessing_camera);
                    postprocessing_scene.overrideMaterial = null;


                };



            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);

                }
            );

            //var ze = new ZeProperties();

            //ze.Show();

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

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


        }