public FlashPlasmaDocument()
        {
            Plasma.generatePlasma(DefaultWidth, DefaultHeight);

            var shift = 0;

            var canvas = new IHTMLCanvas();

            canvas.width  = DefaultWidth;
            canvas.height = DefaultHeight;

            var context = (CanvasRenderingContext2D)canvas.getContext("2d");

            var xx = context.getImageData(0, 0, DefaultWidth, DefaultHeight);
            var x  = (ImageData)(object)xx;

            Action AtTick = null;

            AtTick = delegate
            {
                var buffer = Plasma.shiftPlasma(shift);

                //var x = context.createImageData(DefaultWidth, DefaultHeight);


                var k = 0;
                for (int i = 0; i < DefaultWidth; i++)
                {
                    for (int j = 0; j < DefaultHeight; j++)
                    {
                        var i4 = i * 4;
                        var j4 = j * 4;


                        x.data[i4 + j4 * DefaultWidth + 2] = (byte)((buffer[k] >> (0 * 8)) & 0xff);
                        x.data[i4 + j4 * DefaultWidth + 1] = (byte)((buffer[k] >> (1 * 8)) & 0xff);
                        x.data[i4 + j4 * DefaultWidth + 0] = (byte)((buffer[k] >> (2 * 8)) & 0xff);
                        x.data[i4 + j4 * DefaultWidth + 3] = 0xff;

                        k++;
                    }
                }

                context.putImageData(xx, 0, 0, 0, 0, DefaultWidth, DefaultHeight);
                shift++;
                Native.Window.requestAnimationFrame += AtTick;
            };

            Native.Window.requestAnimationFrame += AtTick;


            canvas.AttachToDocument();
        }
Example #2
0
        static WebGL2RenderingContext InternalConstructor(

            )
        {
            // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs
            // X:\jsc.svn\examples\javascript\WebGL\Test\TestWebGL2RenderingContext\TestWebGL2RenderingContext\Application.cs

            var canvas  = new IHTMLCanvas();
            var context = (WebGL2RenderingContext)canvas.getContext("experimental-webgl2");

            return(context);
        }
        static CanvasRenderingContext2D InternalConstructor(int w, int h)
        {
            // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs

            var canvas = new IHTMLCanvas { width = w, height = h };
            var context = (CanvasRenderingContext2D)canvas.getContext("2d");




            return context;
        }
		public FlashPlasmaDocument()
		{
			Plasma.generatePlasma(DefaultWidth, DefaultHeight);

			var shift = 0;

			var canvas = new IHTMLCanvas();

			canvas.width = DefaultWidth;
			canvas.height = DefaultHeight;

			var context = (CanvasRenderingContext2D)canvas.getContext("2d");

            var xx = context.getImageData(0, 0, DefaultWidth, DefaultHeight);
            var x = (ImageData)(object)xx;

            Action AtTick = null;

            AtTick = delegate
			{
				var buffer = Plasma.shiftPlasma(shift);
					
				//var x = context.createImageData(DefaultWidth, DefaultHeight);


				var k = 0;
				for (int i = 0; i < DefaultWidth; i++)
					for (int j = 0; j < DefaultHeight; j++)
					{
						var i4 = i * 4;
						var j4 = j * 4;


						x.data[i4 + j4 * DefaultWidth + 2] = (byte)((buffer[k] >> (0 * 8)) & 0xff);
						x.data[i4 + j4 * DefaultWidth + 1] = (byte)((buffer[k] >> (1 * 8)) & 0xff);
						x.data[i4 + j4 * DefaultWidth + 0] = (byte)((buffer[k] >> (2 * 8)) & 0xff);
						x.data[i4 + j4 * DefaultWidth + 3] = 0xff;

						k++;
					}

				context.putImageData(xx, 0, 0, 0, 0, DefaultWidth, DefaultHeight);
				shift++;
                Native.Window.requestAnimationFrame += AtTick;
            };

            Native.Window.requestAnimationFrame += AtTick;


			canvas.AttachToDocument();
		}
        /// <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)
        {
            var c = new IHTMLCanvas();
            c.style.border = "1px solid red";

            //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html
            c.width = w;
            c.height = h;

            page.Content.Clear();
            c.AttachTo(page.Content);

            var gl = c.getContext("experimental-webgl");

            if (gl != null)
                Initialize(c, (ScriptCoreLib.JavaScript.WebGL.WebGLRenderingContext)gl, page);
        }
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(IDefault page)
        {
            var c = new IHTMLCanvas();

            c.style.border = "1px solid red";

            //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html
            c.width  = w;
            c.height = h;

            page.Content.Clear();
            c.AttachTo(page.Content);

            var gl = c.getContext("experimental-webgl");

            if (gl != null)
            {
                Initialize(c, (ScriptCoreLib.JavaScript.WebGL.WebGLRenderingContext)gl, page);
            }
        }
Example #7
0
        private void InitializeContent(IDefault page = null)
        {
            #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: "ChromeUDPSendAsync");

                        var xappwindow = await chrome.app.window.create(
                            Native.document.location.pathname, options : null
                            );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

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


                    return;
                }
            }
            #endregion


            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;

            canvas.style.SetLocation(0, 0);


            //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html


            var gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");

            #region Dispose
            var IsDisposed = false;

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

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion


            var s = new PulsSurface(this);

            this.onsurface(gl);

            #region AtResize
            Action AtResize = delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                canvas.width  = Native.window.Width;
                canvas.height = Native.window.Height;

                this.onresize(Native.window.Width, Native.window.Height);

                Console.WriteLine("onresize");
            };

            AtResize();

            Native.window.onresize += delegate
            {
                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



            #region loop
            Action loop = null;

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

                this.onframe();

                Native.window.requestAnimationFrame += loop;
            };

            Native.window.requestAnimationFrame += loop;
            #endregion
        }
        void InitializeContent(IDefaultPage page)
        {
            page.PageContainer.style.color = Color.Blue;

            var size = 600;

            #region canvas
            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, size, size);

            canvas.width = size;
            canvas.height = size;
            #endregion

            #region gl - Initialise WebGL


            var gl = default(WebGLRenderingContext);

            try
            {

                gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");

            }
            catch { }

            if (gl == null)
            {
                Native.Window.alert("WebGL not supported");
                throw new InvalidOperationException("cannot create webgl context");
            }
            #endregion


            var gl_viewportWidth = size;
            var gl_viewportHeight = size;



            var shaderProgram = gl.createProgram();


            #region createShader
            Func<ScriptCoreLib.GLSL.Shader, WebGLShader> createShader = (src) =>
            {
                var shader = gl.createShader(src);

                // verify
                if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) == null)
                {
                    Native.Window.alert("error in SHADER:\n" + gl.getShaderInfoLog(shader));

                    return null;
                }

                return shader;
            };
            #endregion

            var vs = createShader(new GeometryVertexShader());
            var fs = createShader(new GeometryFragmentShader());

            if (vs == null || fs == null) throw new InvalidOperationException("shader failed");

            gl.attachShader(shaderProgram, vs);
            gl.attachShader(shaderProgram, fs);


            gl.linkProgram(shaderProgram);
            gl.useProgram(shaderProgram);

            var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");

            gl.enableVertexAttribArray((ulong)shaderProgram_vertexPositionAttribute);

            // new in lesson 02
            var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
            gl.enableVertexAttribArray((ulong)shaderProgram_vertexColorAttribute);

            var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
            var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");



            var mvMatrix = __glMatrix.mat4.create();
            var mvMatrixStack = new Stack<Float32Array>();

            var pMatrix = __glMatrix.mat4.create();


            #region mvMatrixScope
            Action mvPushMatrix = delegate
            {
                var copy = __glMatrix.mat4.create();
                __glMatrix.mat4.set(mvMatrix, copy);
                mvMatrixStack.Push(copy);
            };

            Action mvPopMatrix = delegate
            {
                mvMatrix = mvMatrixStack.Pop();
            };

            Action<Action> mvMatrixScope =
                h =>
                {
                    mvPushMatrix();
                    h();
                    mvPopMatrix();
                };
            #endregion

            #region setMatrixUniforms
            Action setMatrixUniforms =
                delegate
                {
                    gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, pMatrix);
                    gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, mvMatrix);
                };
            #endregion




            #region init buffers


            #region cube
            var cubeVertexPositionBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
            var cubesize = 0.005f;
            var vertices = new[]{
                // Front face
                -cubesize, -cubesize,  cubesize,
                 cubesize, -cubesize,  cubesize,
                 cubesize,  cubesize,  cubesize,
                -cubesize,  cubesize,  cubesize,

                // Back face
                -cubesize, -cubesize, -cubesize,
                -cubesize,  cubesize, -cubesize,
                 cubesize,  cubesize, -cubesize,
                 cubesize, -cubesize, -cubesize,

                // Top face
                -cubesize,  cubesize, -cubesize,
                -cubesize,  cubesize,  cubesize,
                 cubesize,  cubesize,  cubesize,
                 cubesize,  cubesize, -cubesize,

                // Bottom face
                -cubesize, -cubesize, -cubesize,
                 cubesize, -cubesize, -cubesize,
                 cubesize, -cubesize,  cubesize,
                -cubesize, -cubesize,  cubesize,

                // Right face
                 cubesize, -cubesize, -cubesize,
                 cubesize,  cubesize, -cubesize,
                 cubesize,  cubesize,  cubesize,
                 cubesize, -cubesize,  cubesize,

                // Left face
                -cubesize, -cubesize, -cubesize,
                -cubesize, -cubesize,  cubesize,
                -cubesize,  cubesize,  cubesize,
                -cubesize,  cubesize, -cubesize
            };
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

            var cubeVertexPositionBuffer_itemSize = 3;
            var cubeVertexPositionBuffer_numItems = 36;


            // 216, 191, 18
            #region colors1
            var colors_orange = new[]{
                1.0f, 0.6f, 0.0f, 1.0f, // Front face
                1.0f, 0.6f, 0.0f, 1.0f, // Front face
                1.0f, 0.6f, 0.0f, 1.0f, // Front face
                1.0f, 0.6f, 0.0f, 1.0f, // Front face

                0.8f, 0.4f, 0.0f, 1.0f, // Back face
                0.8f, 0.4f, 0.0f, 1.0f, // Back face
                0.8f, 0.4f, 0.0f, 1.0f, // Back face
                0.8f, 0.4f, 0.0f, 1.0f, // Back face

                0.9f, 0.5f, 0.0f, 1.0f, // Top face
                0.9f, 0.5f, 0.0f, 1.0f, // Top face
                0.9f, 0.5f, 0.0f, 1.0f, // Top face
                0.9f, 0.5f, 0.0f, 1.0f, // Top face

                1.0f, 0.5f, 0.0f, 1.0f, // Bottom face
                1.0f, 0.5f, 0.0f, 1.0f, // Bottom face
                1.0f, 0.5f, 0.0f, 1.0f, // Bottom face
                1.0f, 0.5f, 0.0f, 1.0f, // Bottom face

                
                1.0f, 0.8f, 0.0f, 1.0f, // Right face
                1.0f, 0.8f, 0.0f, 1.0f, // Right face
                1.0f, 0.8f, 0.0f, 1.0f, // Right face
                1.0f, 0.8f, 0.0f, 1.0f, // Right face

                1.0f, 0.8f, 0.0f, 1.0f,  // Left face
                1.0f, 0.8f, 0.0f, 1.0f,  // Left face
                1.0f, 0.8f, 0.0f, 1.0f,  // Left face
                1.0f, 0.8f, 0.0f, 1.0f  // Left face
            };


            var cubeVertexColorBuffer_orange = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_orange), gl.STATIC_DRAW);
            #endregion

            #region colors2
            var colors2 = new[]{
                0.0f, 0.6f, 1.0f, 1.0f, // Front face
                0.0f, 0.6f, 1.0f, 1.0f, // Front face
                0.0f, 0.6f, 1.0f, 1.0f, // Front face
                0.0f, 0.6f, 1.0f, 1.0f, // Front face

                0.0f, 0.4f, 0.8f, 1.0f, // Back face
                0.0f, 0.4f, 0.8f, 1.0f, // Back face
                0.0f, 0.4f, 0.8f, 1.0f, // Back face
                0.0f, 0.4f, 0.8f, 1.0f, // Back face

                0.0f, 0.5f, 0.9f, 1.0f, // Top face
                0.0f, 0.5f, 0.9f, 1.0f, // Top face
                0.0f, 0.5f, 0.9f, 1.0f, // Top face
                0.0f, 0.5f, 0.9f, 1.0f, // Top face

                0.0f, 0.5f, 1.0f, 1.0f, // Bottom face
                0.0f, 0.5f, 1.0f, 1.0f, // Bottom face
                0.0f, 0.5f, 1.0f, 1.0f, // Bottom face
                0.0f, 0.5f, 1.0f, 1.0f, // Bottom face

                
                0.0f, 0.8f, 1.0f, 1.0f, // Right face
                0.0f, 0.8f, 1.0f, 1.0f, // Right face
                0.0f, 0.8f, 1.0f, 1.0f, // Right face
                0.0f, 0.8f, 1.0f, 1.0f, // Right face

                0.0f, 0.8f, 1.0f, 1.0f,  // Left face
                0.0f, 0.8f, 1.0f, 1.0f,  // Left face
                0.0f, 0.8f, 1.0f, 1.0f,  // Left face
                0.0f, 0.8f, 1.0f, 1.0f  // Left face
            };


            var cubeVertexColorBuffer2 = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors2), gl.STATIC_DRAW);
            #endregion

            #region colors3
            var colors_green = new[]{
                0.0f, 1.0f, 0.0f, 1.0f, // Front face
                0.0f, 1.0f, 0.0f, 1.0f, // Front face
                0.0f, 1.0f, 0.0f, 1.0f, // Front face
                0.0f, 1.0f, 0.0f, 1.0f, // Front face

                0.0f, 0.4f, 0.0f, 1.0f, // Back face
                0.0f, 0.4f, 0.0f, 1.0f, // Back face
                0.0f, 0.4f, 0.0f, 1.0f, // Back face
                0.0f, 0.4f, 0.0f, 1.0f, // Back face

                0.0f, 0.5f, 0.0f, 1.0f, // Top face
                0.0f, 0.5f, 0.0f, 1.0f, // Top face
                0.0f, 0.5f, 0.0f, 1.0f, // Top face
                0.0f, 0.5f, 0.0f, 1.0f, // Top face

                0.0f, 0.7f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.7f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.7f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.7f, 0.0f, 1.0f, // Bottom face

                
                0.0f, 0.8f, 0.0f, 1.0f, // Right face
                0.0f, 0.8f, 0.0f, 1.0f, // Right face
                0.0f, 0.8f, 0.0f, 1.0f, // Right face
                0.0f, 0.8f, 0.0f, 1.0f, // Right face

                0.0f, 0.9f, 0.0f, 1.0f,  // Left face
                0.0f, 0.9f, 0.0f, 1.0f,  // Left face
                0.0f, 0.9f, 0.0f, 1.0f,  // Left face
                0.0f, 0.9f, 0.0f, 1.0f  // Left face
            };


            var cubeVertexColorBuffer_green = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_green);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_green), gl.STATIC_DRAW);
            #endregion

            #region colors_black
            var colors_black = new[]{
                0.0f, 0.0f, 0.0f, 1.0f, // Front face
                0.0f, 0.0f, 0.0f, 1.0f, // Front face
                0.0f, 0.0f, 0.0f, 1.0f, // Front face
                0.0f, 0.0f, 0.0f, 1.0f, // Front face
                0.0f, 0.0f, 0.0f, 1.0f, // Back face
                0.0f, 0.0f, 0.0f, 1.0f, // Back face
                0.0f, 0.0f, 0.0f, 1.0f, // Back face
                0.0f, 0.0f, 0.0f, 1.0f, // Back face
                0.0f, 0.0f, 0.0f, 1.0f, // Top face
                0.0f, 0.0f, 0.0f, 1.0f, // Top face
                0.0f, 0.0f, 0.0f, 1.0f, // Top face
                0.0f, 0.0f, 0.0f, 1.0f, // Top face
                0.0f, 0.0f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.0f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.0f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.0f, 0.0f, 1.0f, // Bottom face
                0.0f, 0.0f, 0.0f, 1.0f, // Right face
                0.0f, 0.0f, 0.0f, 1.0f, // Right face
                0.0f, 0.0f, 0.0f, 1.0f, // Right face
                0.0f, 0.0f, 0.0f, 1.0f, // Right face
                0.0f, 0.0f, 0.0f, 1.0f,  // Left face
                0.0f, 0.0f, 0.0f, 1.0f,  // Left face
                0.0f, 0.0f, 0.0f, 1.0f,  // Left face
                0.0f, 0.0f, 0.0f, 1.0f  // Left face
            };


            var cubeVertexColorBuffer_black = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_black);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_black), gl.STATIC_DRAW);
            #endregion


            var cubeVertexColorBuffer_itemSize = 4;
            var cubeVertexColorBuffer_numItems = 24;

            var cubeVertexIndexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
            var cubeVertexIndices = new UInt16[]{
                0, 1, 2,      0, 2, 3,    // Front face
                4, 5, 6,      4, 6, 7,    // Back face
                8, 9, 10,     8, 10, 11,  // Top face
                12, 13, 14,   12, 14, 15, // Bottom face
                16, 17, 18,   16, 18, 19, // Right face
                20, 21, 22,   20, 22, 23  // Left face
            };

            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
            var cubeVertexIndexBuffer_itemSize = 1;
            var cubeVertexIndexBuffer_numItems = 36;

            #endregion

            #endregion




            gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f);
            gl.enable(gl.DEPTH_TEST);

            var IsWalking = false;
            var WalkMultiplier = 0.0f;


            var ego_x = 0f;
            var ego_y = 0f;
            var ego_z = 0f;
            var ego_za = 0f;

            var rCube = 0f;
            var raCube = 0f;

            var lastTime = 0L;
            Action animate = delegate
            {
                var timeNow = new IDate().getTime();
                if (lastTime != 0)
                {
                    var elapsed = timeNow - lastTime;

                    var u = ego_z + ego_za * (elapsed) / 1000.0f;

                    // script: error JSC1000: No implementation found for this native method, please implement [static System.Math.Min(System.Single, System.Single)]

                    if (u < 0)
                        ego_z = (float)Math.Min((double)ego_z, (double)0);
                    else
                        ego_z = u;


                    ego_za -= 3.2f * (elapsed) / 1000.0f;


                    raCube += (75 * elapsed) / 1000.0f;
                }
                lastTime = timeNow;
            };

            Func<float, float> degToRad = (degrees) =>
            {
                return degrees * (f)Math.PI / 180f;
            };


            var c = 0;

            #region drawScene
            Action drawScene = delegate
            {
                if (ego_x < 0)
                    ego_x = 0;

                if (ego_y > 0)
                    ego_y = 0;

                gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


                __glMatrix.mat4.perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f, pMatrix);

                __glMatrix.mat4.identity(mvMatrix);




                #region vertex
                gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
                gl.vertexAttribPointer((ulong)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0);
                #endregion


                //__glMatrix.mat4.rotate(mvMatrix, degToRad(-33), new float[] { 0f, 1f, 0f });
                //__glMatrix.mat4.rotate(mvMatrix, rCube, new float[] { 1f, 0f, 0f });



                #region OriginalCubeAt
                Action<float, float, float> OriginalCubeAt =
                    (x, y, z) =>
                    {
                        mvMatrixScope(
                            delegate
                            {
                                __glMatrix.mat4.translate(mvMatrix, new float[] { x, y, z });
                                __glMatrix.mat4.rotate(mvMatrix, degToRad(raCube), new float[] { 1f, 1f, 1f });

                                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                                setMatrixUniforms();
                                gl.drawElements(gl.TRIANGLES, cubeVertexPositionBuffer_numItems, gl.UNSIGNED_SHORT, 0);
                            }
                        );
                    };
                #endregion

                mvMatrixScope(
                    delegate
                    {
                        __glMatrix.mat4.translate(mvMatrix, new float[] { 
                            - 1.5f, 
                            0, 
                             - 7f});
                        __glMatrix.mat4.rotate(mvMatrix, degToRad(-80), new float[] { 1f, 0f, 0f });


                        #region grid

                        #region color
                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_green);
                        gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);
                        #endregion



                        var GridZoom = 0.3f;

                        Action<float> WriteYLine =
                            x =>
                            {
                                for (int i = -12; i < -1; i++)
                                {
                                    OriginalCubeAt(x * GridZoom, (i) * GridZoom, 0);


                                }
                            };

                        for (int i = 1; i < 12; i++)
                            WriteYLine(i);


                        #region color
                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange);
                        gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);
                        #endregion

                        for (int i = 1; i < 12; i++)
                            OriginalCubeAt(i * GridZoom, 0, 0);

                        for (int i = -12; i < 0; i++)
                            OriginalCubeAt(0, (i) * GridZoom, 0);


                        #endregion

                        #region color
                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2);
                        gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);
                        #endregion

                        {
                            var _y = (float)Math.Cos(raCube * 0.05f) * 0.1f;
                            var _x = (float)Math.Sin(raCube * 0.05f) * 0.1f;

                            OriginalCubeAt(_x, _y, 0);
                        }

                        {
                            var _y = (float)Math.Sin(rCube) * 0.2f;
                            var _x = (float)Math.Cos(rCube) * 0.2f;

                            OriginalCubeAt(_x, _y, 0);
                        }


                        mvMatrixScope(
                          delegate
                          {
                              // where are we
                              __glMatrix.mat4.translate(mvMatrix, new float[] { ego_x, ego_y, ego_z });


                              // rotate all of it
                              //__glMatrix.mat4.rotate(mvMatrix, degToRad(-45), new float[] { 1f, 0f, 0f });

                              // which way are we looking at?
                              __glMatrix.mat4.rotate(mvMatrix, rCube, new float[] { 0f, 0f, 1f });


                              #region cube
                              Action<float, float, float> cube =
                                  (x, y, z) =>
                                  {
                                      mvPushMatrix();
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * x, 
                                        2 * cubesize * y, 
                                        2 * cubesize  * z});

                                      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                                      setMatrixUniforms();
                                      gl.drawElements(gl.TRIANGLES, cubeVertexPositionBuffer_numItems, gl.UNSIGNED_SHORT, 0);
                                      mvPopMatrix();
                                  };
                              #endregion cube

                              #region draw

                              Action<int, int, int> rect =
                                  (ix, iy, z) =>
                                  {
                                      for (int y = 0; y < ix; y++)
                                      {
                                          for (int x = 0; x < iy; x++)
                                          {
                                              cube(x, y, z);
                                          }
                                      }
                                  };
                              #endregion draw

                              #region leg
                              Action<int, float, float> leg =
                                  (y, hiprotation, kneerotation) =>
                                  {
                                      mvPushMatrix();

                                      #region hiprotation
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * 2, 
                                        2 * cubesize * 0, 
                                        2 * cubesize * 11});

                                      __glMatrix.mat4.rotate(mvMatrix, degToRad(hiprotation), new float[] { 0f, 1f, 0f });
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * -2, 
                                        2 * cubesize * 0, 
                                        2 * cubesize * -11});
                                      #endregion



                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * 1, 
                                        2 * cubesize * y, 
                                        2 * cubesize  * 0});


                                      mvPushMatrix();

                                      #region kneerotation
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * 1, 
                                        2 * cubesize * 0, 
                                        2 * cubesize * 6f});

                                      __glMatrix.mat4.rotate(mvMatrix, degToRad(kneerotation), new float[] { 0f, 1f, 0f });
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * -1, 
                                        2 * cubesize * 0, 
                                        2 * cubesize * -6f});
                                      #endregion

                                      #region color
                                      gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange);
                                      gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);
                                      #endregion


                                      #region lower leg
                                      rect(3, 5, 0);
                                      rect(3, 5, 1);
                                      rect(3, 5, 2);
                                      rect(3, 3, 3);
                                      #endregion



                                      #region color
                                      gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2);
                                      gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);
                                      #endregion

                                      rect(3, 3, 4);
                                      rect(3, 3, 5);
                                      rect(3, 3, 6);

                                      mvPopMatrix();


                                      #region upper leg
                                      mvPushMatrix();
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * 1, 
                                        2 * cubesize * 0, 
                                        2 * cubesize  * 0});

                                      rect(3, 3, 7);
                                      rect(3, 3, 8);
                                      rect(3, 3, 9);


                                      mvPopMatrix();
                                      #endregion

                                      #region hips
                                      rect(3, 4, 10);
                                      //rect(3, 4, 11);
                                      #endregion

                                      mvPopMatrix();



                                  };
                              #endregion

                              var seed = (raCube * WalkMultiplier * 16);

                              #region animated_leg
                              Action<int, int> animated_leg = (seed_offset, x) =>
                              {
                                  var seed_180 = (float)((seed + seed_offset) % 180f);

                                  var left_hip = 30f;
                                  var left_knee = 0f;


                                  if (ego_z < 0)
                                  {
                                      // crouch
                                      left_hip = -66;
                                      left_knee = left_hip * -2;
                                  }
                                  else if (ego_z > 0)
                                  {
                                      // crouch
                                      left_hip = 10;
                                      left_knee = 10;
                                  }
                                  else if (!IsWalking)
                                  {
                                      left_hip = 0;
                                      left_knee = 0;
                                  }
                                  else
                                  {
                                      left_hip = seed_180;

                                      if (left_hip > 90)
                                      {
                                          left_hip = 180 - left_hip;
                                          // -60 should be 0 -  front
                                          // 0 should be 60
                                          // 30 should be 0 - back


                                          var v = (90 - left_hip) - 70;



                                          if (v < 0)
                                              left_knee = 70 + v;
                                          else if (v == 0)
                                              left_knee = 70;
                                          else if (v > 0)
                                              left_knee = (20 - v) * (70 / 20);



                                          //page.Data1.innerText = "" + new { left_hip, v, left_knee };
                                      }
                                      else
                                      {
                                      }

                                      left_hip -= 45;
                                  }

                                  leg(x, left_hip, left_knee);
                              };
                              #endregion

                              animated_leg(0, -2);
                              animated_leg(90, 128 - 5);





                              #region body
                              mvMatrixScope(
                                  delegate
                                  {
                                      __glMatrix.mat4.translate(mvMatrix, new float[] { 
                                        2 * cubesize * 1, 
                                        2 * cubesize * -2, 
                                        2 * cubesize  * 11});

                                      rect(128, 128, 0);

                                    


                                  }
                              );
                              #endregion



                          }
                      );
                    }
                );

            };
            drawScene();
            #endregion

            #region requestAnimFrame
            var requestAnimFrame = (IFunction)new IFunction(
                @"return window.requestAnimationFrame ||
         window.webkitRequestAnimationFrame ||
         window.mozRequestAnimationFrame ||
         window.oRequestAnimationFrame ||
         window.msRequestAnimationFrame ||
         function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
           window.setTimeout(callback, 1000/60);
         };"
            ).apply(null);
            #endregion





            #region tick - new in lesson 03
            var tick = default(Action);

            tick = delegate
            {
                c++;


                Native.Document.title = "" + c + " " + (rCube) + " " + ego_z + " " + ego_za;

                drawScene();
                animate();

                requestAnimFrame.apply(null, IFunction.OfDelegate(tick));
            };

            tick();
            #endregion


            #region onkeyup
            Native.Document.body.onkeyup +=
                (e) =>
                {
                    //Native.Document.title = "" + new { e.KeyCode };

                    if (e.KeyCode == 17)
                    {
                        ego_z = 0;
                    }

                    if (e.KeyCode == 32)
                    {
                        ego_z = 0;
                        ego_za = 2;
                    }

                    if (e.KeyCode == 38)
                    {
                        IsWalking = false;




                    }



                    if (e.KeyCode == 40)
                    {
                        IsWalking = false;
                    }
                };
            #endregion

            #region onkeydown
            Native.Document.body.onkeydown +=
                (e) =>
                {
                    // see also: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

                    e.PreventDefault();

                    #region turnspeed
                    var turnspeed = 0.05f;

                    if (e.KeyCode == 37)
                    {
                        // left
                        rCube += turnspeed;
                    }

                    if (e.KeyCode == 65)
                    {
                        // left
                        rCube += turnspeed;
                    }


                    if (e.KeyCode == 39)
                    {
                        rCube -= turnspeed;

                        // right
                    }

                    if (e.KeyCode == 68)
                    {
                        rCube -= turnspeed;

                        // right
                    }
                    #endregion

                    if (e.KeyCode == 17)
                    {
                        ego_z = -cubesize * 6;
                    }

                    if (e.KeyCode == 32)
                    {
                        ego_z = -cubesize * 6;
                    }

                    if (ego_z > 0)
                    {
                        // not on ground. cant walk :)
                    }
                    else
                    {
                        if (e.KeyCode == 38)
                        {
                            IsWalking = true;

                            // mat aint working ..


                            if (!e.shiftKey)
                            {
                                WalkMultiplier = 0.04f;
                            }
                            else
                            {
                                WalkMultiplier = 0.02f;



                            }

                            ego_y += (float)Math.Sin(rCube) * WalkMultiplier;
                            ego_x += (float)Math.Cos(rCube) * WalkMultiplier;
                        }



                        if (e.KeyCode == 40)
                        {
                            IsWalking = true;
                            WalkMultiplier = 0.02f;

                            ego_y -= (float)Math.Sin(rCube) * WalkMultiplier;
                            ego_x -= (float)Math.Cos(rCube) * WalkMultiplier;

                        }

                    }
                };
            #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)
        {
            var toolbar = new
            {
                createItem = new IFunction("y", "return opera.contexts.toolbar.createItem(y);"),
                addItem = new IFunction("y", "opera.contexts.toolbar.addItem(y);")
            };

            var windows = new
            {
                // http://dev.opera.com/articles/view/extensions-api-windows-create/
                create = new IFunction("", "return opera.extension.windows.create();"),

                // http://dev.opera.com/articles/view/extensions-api-window-update/
                update = new IFunction("y", "this.update(y);"),
            };

            try
            {
                // can only create one button?
                toolbar.createItem.apply(null,
                       new Opera_UIItemProperties
                       {
                           title = "OperaExtensionExperiment",
                           popup = new OperaToolbarPopupArguments { href = "index.html" }
                       }
                   ).With(
                       theButton =>
                       {

                           toolbar.addItem.apply(null, theButton);
                       }
                   );

            }
            catch
            {
                // not running as extension?
            }

            // will only work on toolbar
            //page.NewBrowser.style.color = JSColor.Green;
            //page.NewBrowser.onclick +=
            //    delegate
            //    {
            //        var w = windows.create.apply(null);

            //        windows.update.apply(w,
            //            new Opera_BrowserWindowProperties
            //            {

            //                width = 400
            //            }
            //        );
            //    };

            page.IAmAPopup.style.color = JSColor.Green;

            page.IAmAPopup.onclick +=
                delegate
                {
                    page.IAmAPopup.style.color = JSColor.Red;

                    var getScreenshot = new IFunction("y", "opera.extension.getScreenshot(y);");

                    Action<ImageData> applyScreenshot =
                        imageData =>
                        {
                            // Create a blank canvas
                            var canvas = new IHTMLCanvas();
                            canvas.width = (int)imageData.width;
                            canvas.height = (int)imageData.height;

                            // Write the screenshot image data to the canvas context
                            var ctx = (CanvasRenderingContext2D)canvas.getContext("2d");
                            ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);

                            canvas.style.border = "1px solid blue";
                            canvas.AttachToDocument();
                            page.IAmAPopup.style.color = JSColor.Blue;
                        };

                    // http://dev.opera.com/articles/view/extensions-api-screenshot/

                    getScreenshot.apply(null, IFunction.OfDelegate(applyScreenshot));

                };

            page.foooex.ondragstart +=

                e =>
                {
                    // http://ajaxian.com/archives/how-to-drag-out-files-like-gmail

                    e.dataTransfer.setData("DownloadURL",
                         "application/octet-stream:foo.oex:" + page.foooex.href);

                };
        }
        static WebGL2RenderingContext InternalConstructor(

            )
        {
            // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs
            // X:\jsc.svn\examples\javascript\WebGL\Test\TestWebGL2RenderingContext\TestWebGL2RenderingContext\Application.cs

            //  ['webgl2', 'experimental-webgl2']
            // X:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeWebGLExtensions\ChromeWebGLExtensions\Application.cs

            var canvas = new IHTMLCanvas();
            //var context = (WebGL2RenderingContext)canvas.getContext("experimental-webgl2");
            var context = (WebGL2RenderingContext)canvas.getContext("webgl2");

            return context;
        }
Example #11
0
        void InitializeContent(IDefault page = null)
        {
            var gl_viewportWidth  = 800;
            var gl_viewportHeight = 640;


            #region canvas
            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight);

            canvas.width  = gl_viewportWidth;
            canvas.height = gl_viewportHeight;
            #endregion

            #region gl - Initialise WebGL


            var gl = default(gl);

            try
            {
                gl = (gl)canvas.getContext("experimental-webgl");
            }
            catch { }

            if (gl == null)
            {
                Native.window.alert("WebGL not supported");
                throw new InvalidOperationException("cannot create webgl context");
            }
            #endregion



            #region Dispose
            var IsDisposed = false;

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

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion



            #region initShaders
            var shaderProgram = gl.createProgram(
                new GeometryVertexShader(),
                new GeometryFragmentShader()
                );


            gl.linkProgram(shaderProgram);
            gl.useProgram(shaderProgram);


            var vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            gl.enableVertexAttribArray((uint)vertexPositionAttribute);

            var vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
            gl.enableVertexAttribArray((uint)vertexNormalAttribute);

            var vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
            gl.enableVertexAttribArray((uint)vertexColorAttribute);
            #endregion


            gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f);
            gl.clearDepth(1.0f);
            gl.enable(gl.DEPTH_TEST);

            // missing from WebGL IDL?
            //gl.enable(gl.POLYGON_SMOOTH);

            // Enable point size
            gl.enable(0x8642);
            gl.depthFunc(gl.LEQUAL);

            #region initBuffers
            var vertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

            var planet     = new Planet(129);
            var planetData = planet.generate();

            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.vertices), gl.STATIC_DRAW);
            var vertexBuffer_itemSize = 3;
            var vertexBuffer_numItems = planetData.vertices.Length / 3;

            var colorBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.colors), gl.STATIC_DRAW);
            var colorBuffer_itemSize = 4;
            var colorBuffer_numItems = planetData.colors.Length / 4;

            var normalBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.normals), gl.STATIC_DRAW);
            var normalBuffer_itemSize = 3;
            var normalBuffer_numItems = planetData.normals.Length / 3;

            var indexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(planetData.indices), gl.STATIC_DRAW);
            var indexBuffer_itemSize = 1;
            var indexBuffer_numItems = planetData.indices.Length;
            #endregion


            var lastTime = 0L;
            var yRot     = -180.0f;
            var ySpeed   = -50.0f;

            #region glCore
            var mvMatrix      = default(Matrix);
            var mvMatrixStack = new Stack <Matrix>();
            var pMatrix       = default(Matrix);

            Action loadIdentity = delegate
            {
                mvMatrix = __sylvester.Matrix.I(4);
            };

            Action <float, float, float, float> perspective = (fovy, aspect, znear, zfar) =>
            {
                pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar);
            };

            Action <Matrix> multMatrix = (m) =>
            {
                mvMatrix = mvMatrix.x(m);
            };

            // http://prototypejs.org/api/array/flatten
            Action setMatrixUniforms =
                delegate
            {
                var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
                gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten()));

                var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
                gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));

                var normalMatrix = mvMatrix.inverse();
                normalMatrix = normalMatrix.transpose();

                var nUniform = gl.getUniformLocation(shaderProgram, "uNMatrix");
                gl.uniformMatrix4fv(nUniform, false, new Float32Array(mvMatrix.flatten()));
            };

            Action <float, float[]> mvRotate = (ang, v) =>
            {
                var arad = ang * Math.PI / 180.0;
                var m    = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };

            Action <f, f, f, f, f, f, f, f, f> lookAt = (ex, ey, ez, cx, cy, cz, ux, uy, uz) =>
            {
                mvMatrix = mvMatrix.x(__glUtils.globals.makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz));
            };
            #endregion


            #region drawScene
            Action drawScene =
                delegate
            {
                gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

                //perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f);
                perspective(60f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 1000.0f);
                //perspective(60f, 800 / 640, 0.1f, 1000.0f);

                loadIdentity();

                lookAt(0, 0, 500, 0, 0, 0, 0, 1, 0);

                mvRotate(yRot, new[] { 0f, 1f, 0f });

                gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
                gl.vertexAttribPointer((uint)vertexPositionAttribute, vertexBuffer_itemSize, gl.FLOAT, false, 0, 0);

                gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
                gl.vertexAttribPointer((uint)vertexNormalAttribute, normalBuffer_itemSize, gl.FLOAT, false, 0, 0);

                gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
                gl.vertexAttribPointer((uint)vertexColorAttribute, colorBuffer_itemSize, gl.FLOAT, false, 0, 0);

                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
                setMatrixUniforms();
                gl.drawElements(gl.TRIANGLES, indexBuffer_numItems, gl.UNSIGNED_SHORT, 0);
                //gl.drawArrays(gl.POINTS, 0, vertexBuffer.numItems);
            };
            #endregion

            #region animate
            Action animate = () =>
            {
                var timeNow = new IDate().getTime();
                if (lastTime != 0)
                {
                    var elapsed = timeNow - lastTime;
                    yRot += (ySpeed * elapsed) / 1000.0f;
                }
                lastTime = timeNow;
            };
            #endregion


            #region tick
            Action tick = null;

            tick = () =>
            {
                drawScene();
                animate();

                Native.window.requestAnimationFrame += tick;
            };

            Native.window.requestAnimationFrame += tick;
            #endregion

            #region AtResize
            Action AtResize = delegate
            {
                gl_viewportWidth  = Native.window.Width;
                gl_viewportHeight = Native.window.Height;

                canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                canvas.width  = Native.window.Width;
                canvas.height = Native.window.Height;
            };

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

            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
        }
Example #12
0
        void InitializeContent(IDefault page = null)
        {
            var vertices = new List <float>();
            var indices  = new List <ushort>();
            var colors   = new List <float>();
            var uvs      = new List <float>();

            var radius        = 7;
            var currentRadius = radius;
            var segments      = (ushort)24;
            var spacing       = 2;
            var numRings      = 18;
            var index         = (ushort)0;
            var currentTime   = 0.0f;



            #region generateGeometry
            Action generateGeometry = delegate
            {
                for (var ring = 0; ring < numRings; ring++)
                {
                    for (var segment = 0; segment < segments; segment++)
                    {
                        var degrees = (360 / segments) * segment;
                        var radians = (Math.PI / 180) * degrees;
                        var x       = (float)Math.Cos(radians) * currentRadius;
                        var y       = (float)Math.Sin(radians) * currentRadius;
                        var z       = ring * -spacing;

                        vertices.Add(x, y, z);

                        if (segment < (segments - 1) / 2)
                        {
                            uvs.Add((1.0f / (segments)) * segment * 2, (1.0f / 4) * ring);
                        }
                        else
                        {
                            uvs.Add(2.0f - ((1.0f / (segments)) * segment * 2), (1.0f / 4) * ring);
                        }

                        var color = 1.0f - ((1.0f / (numRings - 1)) * ring);
                        colors.Add(color, color, color, 1.0f);

                        if (ring < numRings - 1)
                        {
                            if (segment < segments - 1)
                            {
                                indices.Add(index, (ushort)(index + segments + 1), (ushort)(index + segments));
                                indices.Add(index, (ushort)(index + 1), (ushort)(index + segments + 1));
                            }
                            else
                            {
                                indices.Add(index, (ushort)(index + 1), (ushort)(index + segments));
                                indices.Add(index, (ushort)(index - segments + 1), (ushort)(index + 1));
                            }
                        }

                        index++;
                    }
                    currentRadius -= radius / numRings;
                }
            };


            generateGeometry();
            #endregion


            var size = 500;

            var gl_viewportWidth  = size;
            var gl_viewportHeight = size;


            #region canvas
            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, size, size);

            canvas.width  = size;
            canvas.height = size;
            #endregion

            #region gl - Initialise WebGL


            var gl = default(WebGLRenderingContext);

            try
            {
                gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");
            }
            catch { }

            if (gl == null)
            {
                Native.window.alert("WebGL not supported");
                throw new InvalidOperationException("cannot create webgl context");
            }
            #endregion

            #region drawingMode
            var drawingMode = gl.TRIANGLES;

            page.With(
                delegate
            {
                page.triangles.onchange +=
                    delegate
                {
                    if (drawingMode == gl.TRIANGLES)
                    {
                        drawingMode = gl.LINE_STRIP;
                    }
                    else
                    {
                        drawingMode = gl.TRIANGLES;
                    }
                };
            }
                );
            #endregion

            var shaderProgram = gl.createProgram(
                new TunnelVertexShader(),
                new TunnelFragmentShader()
                );

            // "WebGL: INVALID_OPERATION: drawElements: attribs not setup correctly", source: http://192.168.43.252:16876/ (0)
            // I/chromium( 3770): [INFO:CONSOLE(0)] "WebGL: INVALID_OPERATION: useProgram: program not valid", source: http://192.168.43.252:16876/ (0)



            gl.linkProgram(shaderProgram);
            gl.useProgram(shaderProgram);

            var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute);

            var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
            gl.enableVertexAttribArray((uint)shaderProgram_vertexColorAttribute);

            var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
            gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute);

            var shaderProgram_pMatrixUniform  = gl.getUniformLocation(shaderProgram, "uPMatrix");
            var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
            var shaderProgram_fTimeUniform    = gl.getUniformLocation(shaderProgram, "fTime");
            var shaderProgram_samplerUniform  = gl.getUniformLocation(shaderProgram, "uSampler");



            var mvMatrix      = default(Matrix);
            var mvMatrixStack = new Stack <Matrix>();
            var pMatrix       = default(Matrix);

            Action mvPopMatrix = delegate
            {
                mvMatrix = mvMatrixStack.Pop();
            };

            // http://prototypejs.org/api/array/flatten
            Action setMatrixUniforms =
                delegate
            {
                gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten()));
                gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));
            };


            Action mvPushMatrix = delegate
            {
                mvMatrixStack.Push(mvMatrix.dup());
            };



            Action loadIdentity = delegate
            {
                mvMatrix = __sylvester.Matrix.I(4);
            };


            Action <Matrix> multMatrix = (m) =>
            {
                mvMatrix = mvMatrix.x(m);
            };

            Action <float[]> mvTranslate = (v) =>
            {
                var m = __sylvester.Matrix.Translation(__sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };


            Action <float, float[]> mvRotate = (ang, v) =>
            {
                var arad = ang * Math.PI / 180.0;
                var m    = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };

            Action <float, float, float, float> perspective = (fovy, aspect, znear, zfar) =>
            {
                pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar);
            };



            #region IsDisposed
            var IsDisposed = false;

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

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion


            new HTML.Images.FromAssets.texture().InvokeOnComplete(
                (texture_image) =>
            {
                #region initTexture
                var texture = gl.createTexture();

                gl.bindTexture(gl.TEXTURE_2D, texture);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture_image);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST);
                gl.bindTexture(gl.TEXTURE_2D, null);
                #endregion


                #region initBuffers
                var cubeVertexPositionBuffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
                gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices.ToArray()), gl.STATIC_DRAW);
                var cubeVertexPositionBuffer_itemSize = 3;
                var cubeVertexPositionBuffer_numItems = vertices.Count / 3;

                var cubeVertexColorBuffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);

                gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors.ToArray()), gl.STATIC_DRAW);
                var cubeVertexColorBuffer_itemSize = 4;
                var cubeVertexColorBuffer_numItems = colors.Count / 4;

                var cubeVertexIndexBuffer = gl.createBuffer();
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices.ToArray()), gl.STATIC_DRAW);
                var cubeVertexIndexBuffer_itemSize = 1;
                var cubeVertexIndexBuffer_numItems = indices.Count;

                var cubeVertexTextureCoordBuffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
                gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uvs.ToArray()), gl.STATIC_DRAW);
                var cubeVertexTextureCoordBuffer_itemSize = 2;
                var cubeVertexTextureCoordBuffer_numItems = uvs.Count / 2;
                #endregion


                gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f);

                gl.clearDepth(1.0f);

                gl.enable(gl.DEPTH_TEST);
                gl.depthFunc(gl.LEQUAL);



                Action AtResize = delegate
                {
                    gl_viewportWidth  = Convert.ToInt32(Native.window.Width * zoom);
                    gl_viewportHeight = Convert.ToInt32(Native.window.Height * zoom);

                    canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                    canvas.width  = Convert.ToInt32(Native.window.Width * zoom);
                    canvas.height = Convert.ToInt32(Native.window.Height * zoom);
                };

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

                AtResize();


                var rCube = 0;

                #region drawScene

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

                    gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight);
                    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

                    perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f);
                    loadIdentity();

                    mvTranslate(new[] { 0.0f, 0.0f, -8.0f });

                    mvPushMatrix();
                    mvRotate(rCube, new[] { 1f, 1f, 1f });

                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
                    gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
                    gl.vertexAttribPointer((uint)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
                    gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.activeTexture(gl.TEXTURE0);
                    gl.bindTexture(gl.TEXTURE_2D, texture);
                    gl.uniform1i(shaderProgram_samplerUniform, 0);

                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                    setMatrixUniforms();

                    // ?
                    //  a[0].CS___8__locals19.currentTime = (((a[0].CS___8__locals19.currentTime + 0.01)) >>> 0);
                    // haha. wtf jsc. :)
                    currentTime = (currentTime + 0.01f);

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

                    gl.uniform1f(shaderProgram_fTimeUniform, currentTime);
                    gl.drawElements(drawingMode, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0);

                    mvPopMatrix();
                };

                #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
            }
                );
        }
        void InitializeContent(IDefault  page = null)
        {


            var gl_viewportWidth = 800;
            var gl_viewportHeight = 640;


            #region canvas
            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight);

            canvas.width = gl_viewportWidth;
            canvas.height = gl_viewportHeight;
            #endregion

            #region gl - Initialise WebGL


            var gl = default(gl);

            try
            {

                gl = (gl)canvas.getContext("experimental-webgl");

            }
            catch { }

            if (gl == null)
            {
                Native.window.alert("WebGL not supported");
                throw new InvalidOperationException("cannot create webgl context");
            }
            #endregion



            #region Dispose
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion




            #region initShaders
            var shaderProgram = gl.createProgram(
                new GeometryVertexShader(),
                new GeometryFragmentShader()
            );
       

            gl.linkProgram(shaderProgram);
            gl.useProgram(shaderProgram);


            var vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            gl.enableVertexAttribArray((uint)vertexPositionAttribute);

            var vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
            gl.enableVertexAttribArray((uint)vertexNormalAttribute);

            var vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
            gl.enableVertexAttribArray((uint)vertexColorAttribute);
            #endregion

     
            gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f);
            gl.clearDepth(1.0f);
            gl.enable(gl.DEPTH_TEST);

            // missing from WebGL IDL?
            //gl.enable(gl.POLYGON_SMOOTH);

            // Enable point size
            gl.enable(0x8642);
            gl.depthFunc(gl.LEQUAL);

            #region initBuffers
            var vertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

            var planet = new Planet(129);
            var planetData = planet.generate();

            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.vertices), gl.STATIC_DRAW);
            var vertexBuffer_itemSize = 3;
            var vertexBuffer_numItems = planetData.vertices.Length / 3;

            var colorBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.colors), gl.STATIC_DRAW);
            var colorBuffer_itemSize = 4;
            var colorBuffer_numItems = planetData.colors.Length / 4;

            var normalBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.normals), gl.STATIC_DRAW);
            var normalBuffer_itemSize = 3;
            var normalBuffer_numItems = planetData.normals.Length / 3;

            var indexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(planetData.indices), gl.STATIC_DRAW);
            var indexBuffer_itemSize = 1;
            var indexBuffer_numItems = planetData.indices.Length;
            #endregion


            var lastTime = 0L;
            var yRot = -180.0f;
            var ySpeed = -50.0f;

            #region glCore
            var mvMatrix = default(Matrix);
            var mvMatrixStack = new Stack<Matrix>();
            var pMatrix = default(Matrix);

            Action loadIdentity = delegate
             {
                 mvMatrix = __sylvester.Matrix.I(4);
             };

            Action<float, float, float, float> perspective = (fovy, aspect, znear, zfar) =>
             {
                 pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar);
             };

            Action<Matrix> multMatrix = (m) =>
            {
                mvMatrix = mvMatrix.x(m);
            };

            // http://prototypejs.org/api/array/flatten
            Action setMatrixUniforms =
                delegate
                {
                    var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
                    gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten()));
                    
                    var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
                    gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));

                    var normalMatrix = mvMatrix.inverse();
                    normalMatrix = normalMatrix.transpose();

                    var nUniform = gl.getUniformLocation(shaderProgram, "uNMatrix");
                    gl.uniformMatrix4fv(nUniform, false, new Float32Array(mvMatrix.flatten()));

                };

            Action<float, float[]> mvRotate = (ang, v) =>
            {
                var arad = ang * Math.PI / 180.0;
                var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };

            Action<f, f, f, f, f, f, f, f, f> lookAt = (ex, ey, ez, cx, cy, cz, ux, uy, uz) =>
            {
                mvMatrix = mvMatrix.x(__glUtils.globals.makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz));
            };
            #endregion


            #region drawScene
            Action drawScene =
                delegate
                {
                    gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight);
                    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

                    //perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f);
                    perspective(60f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 1000.0f);
                    //perspective(60f, 800 / 640, 0.1f, 1000.0f);

                    loadIdentity();

                    lookAt(0, 0, 500, 0, 0, 0, 0, 1, 0);

                    mvRotate(yRot, new[] { 0f, 1f, 0f });

                    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
                    gl.vertexAttribPointer((uint)vertexPositionAttribute, vertexBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
                    gl.vertexAttribPointer((uint)vertexNormalAttribute, normalBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
                    gl.vertexAttribPointer((uint)vertexColorAttribute, colorBuffer_itemSize, gl.FLOAT, false, 0, 0);

                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
                    setMatrixUniforms();
                    gl.drawElements(gl.TRIANGLES, indexBuffer_numItems, gl.UNSIGNED_SHORT, 0);
                    //gl.drawArrays(gl.POINTS, 0, vertexBuffer.numItems);
                };
            #endregion

            #region animate
            Action animate = () =>
            {
                var timeNow = new IDate().getTime();
                if (lastTime != 0)
                {
                    var elapsed = timeNow - lastTime;
                    yRot += (ySpeed * elapsed) / 1000.0f;
                }
                lastTime = timeNow;
            };
            #endregion


            #region tick
            Action tick = null;
            
            tick = () =>
            {
                drawScene();
                animate();

                Native.window.requestAnimationFrame += tick;
            };

            Native.window.requestAnimationFrame += tick;
            #endregion

            #region AtResize
            Action AtResize = delegate
            {
                gl_viewportWidth = Native.window.Width;
                gl_viewportHeight = Native.window.Height;

                canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                canvas.width = Native.window.Width;
                canvas.height = Native.window.Height;
            };

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

            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

        }
        void InitializeContent(IDefault page = null)
        {
            var vertices = new List<float>();
            var indices = new List<ushort>();
            var colors = new List<float>();
            var uvs = new List<float>();

            var radius = 7;
            var currentRadius = radius;
            var segments = (ushort)24;
            var spacing = 2;
            var numRings = 18;
            var index = (ushort)0;
            var currentTime = 0.0f;




            #region generateGeometry
            Action generateGeometry = delegate
            {
                for (var ring = 0; ring < numRings; ring++)
                {
                    for (var segment = 0; segment < segments; segment++)
                    {
                        var degrees = (360 / segments) * segment;
                        var radians = (Math.PI / 180) * degrees;
                        var x = (float)Math.Cos(radians) * currentRadius;
                        var y = (float)Math.Sin(radians) * currentRadius;
                        var z = ring * -spacing;

                        vertices.Add(x, y, z);

                        if (segment < (segments - 1) / 2)
                        {
                            uvs.Add((1.0f / (segments)) * segment * 2, (1.0f / 4) * ring);
                        }
                        else
                        {
                            uvs.Add(2.0f - ((1.0f / (segments)) * segment * 2), (1.0f / 4) * ring);
                        }

                        var color = 1.0f - ((1.0f / (numRings - 1)) * ring);
                        colors.Add(color, color, color, 1.0f);

                        if (ring < numRings - 1)
                        {
                            if (segment < segments - 1)
                            {
                                indices.Add(index, (ushort)(index + segments + 1), (ushort)(index + segments));
                                indices.Add(index, (ushort)(index + 1), (ushort)(index + segments + 1));
                            }
                            else
                            {
                                indices.Add(index, (ushort)(index + 1), (ushort)(index + segments));
                                indices.Add(index, (ushort)(index - segments + 1), (ushort)(index + 1));
                            }
                        }

                        index++;
                    }
                    currentRadius -= radius / numRings;
                }
            };


            generateGeometry();
            #endregion


            var size = 500;

            var gl_viewportWidth = size;
            var gl_viewportHeight = size;


            #region canvas
            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, size, size);

            canvas.width = size;
            canvas.height = size;
            #endregion

            #region gl - Initialise WebGL


            var gl = default(WebGLRenderingContext);

            try
            {

                gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");

            }
            catch { }

            if (gl == null)
            {
                Native.window.alert("WebGL not supported");
                throw new InvalidOperationException("cannot create webgl context");
            }
            #endregion

            #region drawingMode
            var drawingMode = gl.TRIANGLES;

            page.With(
                delegate
                {
                    page.triangles.onchange +=
                        delegate
                        {
                            if (drawingMode == gl.TRIANGLES)
                                drawingMode = gl.LINE_STRIP;
                            else
                                drawingMode = gl.TRIANGLES;
                        };
                }
            );
            #endregion

            var shaderProgram = gl.createProgram(
                new TunnelVertexShader(),
                new TunnelFragmentShader()
                );

            // "WebGL: INVALID_OPERATION: drawElements: attribs not setup correctly", source: http://192.168.43.252:16876/ (0)
            // I/chromium( 3770): [INFO:CONSOLE(0)] "WebGL: INVALID_OPERATION: useProgram: program not valid", source: http://192.168.43.252:16876/ (0)





            gl.linkProgram(shaderProgram);
            gl.useProgram(shaderProgram);

            var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute);

            var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
            gl.enableVertexAttribArray((uint)shaderProgram_vertexColorAttribute);

            var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
            gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute);

            var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
            var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
            var shaderProgram_fTimeUniform = gl.getUniformLocation(shaderProgram, "fTime");
            var shaderProgram_samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");



            var mvMatrix = default(Matrix);
            var mvMatrixStack = new Stack<Matrix>();
            var pMatrix = default(Matrix);

            Action mvPopMatrix = delegate
           {
               mvMatrix = mvMatrixStack.Pop();
           };

            // http://prototypejs.org/api/array/flatten
            Action setMatrixUniforms =
                delegate
                {
                    gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten()));
                    gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));
                };


            Action mvPushMatrix = delegate
            {
                mvMatrixStack.Push(mvMatrix.dup());
            };



            Action loadIdentity = delegate
            {
                mvMatrix = __sylvester.Matrix.I(4);
            };


            Action<Matrix> multMatrix = (m) =>
            {
                mvMatrix = mvMatrix.x(m);
            };

            Action<float[]> mvTranslate = (v) =>
            {
                var m = __sylvester.Matrix.Translation(__sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };


            Action<float, float[]> mvRotate = (ang, v) =>
            {
                var arad = ang * Math.PI / 180.0;
                var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4();
                multMatrix(m);
            };

            Action<float, float, float, float> perspective = (fovy, aspect, znear, zfar) =>
            {
                pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar);
            };



            #region IsDisposed
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion


            new HTML.Images.FromAssets.texture().InvokeOnComplete(
                (texture_image) =>
                {
                    #region initTexture
                    var texture = gl.createTexture();

                    gl.bindTexture(gl.TEXTURE_2D, texture);
                    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture_image);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST);
                    gl.bindTexture(gl.TEXTURE_2D, null);
                    #endregion


                    #region initBuffers
                    var cubeVertexPositionBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
                    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices.ToArray()), gl.STATIC_DRAW);
                    var cubeVertexPositionBuffer_itemSize = 3;
                    var cubeVertexPositionBuffer_numItems = vertices.Count / 3;

                    var cubeVertexColorBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);

                    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors.ToArray()), gl.STATIC_DRAW);
                    var cubeVertexColorBuffer_itemSize = 4;
                    var cubeVertexColorBuffer_numItems = colors.Count / 4;

                    var cubeVertexIndexBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices.ToArray()), gl.STATIC_DRAW);
                    var cubeVertexIndexBuffer_itemSize = 1;
                    var cubeVertexIndexBuffer_numItems = indices.Count;

                    var cubeVertexTextureCoordBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
                    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uvs.ToArray()), gl.STATIC_DRAW);
                    var cubeVertexTextureCoordBuffer_itemSize = 2;
                    var cubeVertexTextureCoordBuffer_numItems = uvs.Count / 2;
                    #endregion


                    gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f);

                    gl.clearDepth(1.0f);

                    gl.enable(gl.DEPTH_TEST);
                    gl.depthFunc(gl.LEQUAL);




                    Action AtResize = delegate
                    {

                        gl_viewportWidth = Convert.ToInt32(Native.window.Width * zoom);
                        gl_viewportHeight = Convert.ToInt32(Native.window.Height * zoom);

                        canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                        canvas.width = Convert.ToInt32(Native.window.Width * zoom);
                        canvas.height = Convert.ToInt32(Native.window.Height * zoom);
                    };

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

                    AtResize();


                    var rCube = 0;

                    #region drawScene

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

                        gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight);
                        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

                        perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f);
                        loadIdentity();

                        mvTranslate(new[] { 0.0f, 0.0f, -8.0f });

                        mvPushMatrix();
                        mvRotate(rCube, new[] { 1f, 1f, 1f });

                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
                        gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0);

                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
                        gl.vertexAttribPointer((uint)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0);

                        gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
                        gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0);

                        gl.activeTexture(gl.TEXTURE0);
                        gl.bindTexture(gl.TEXTURE_2D, texture);
                        gl.uniform1i(shaderProgram_samplerUniform, 0);

                        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
                        setMatrixUniforms();

                        // ?
                        //  a[0].CS___8__locals19.currentTime = (((a[0].CS___8__locals19.currentTime + 0.01)) >>> 0);
                        // haha. wtf jsc. :)
                        currentTime = (currentTime + 0.01f);

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

                        gl.uniform1f(shaderProgram_fTimeUniform, currentTime);
                        gl.drawElements(drawingMode, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0);

                        mvPopMatrix();

                    };

                    #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)
        {
            "Spiral".ToDocumentTitle();

            var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0);

            #region gl

            var gl = default(WebGLRenderingContext);

            try
            {

                gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");

            }
            catch { }

            if (gl == null)
            {
                //Native.Window.alert("WebGL not supported");
                //throw new InvalidOperationException("cannot create webgl context");
                return;
            }
            #endregion

            #region Dispose
            var IsDisposed = false;

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

            //    IsDisposed = true;

            //    canvas.Orphanize();
            //};
            #endregion


            var s = new SpiralSurface(this);

            this.onsurface(gl);

            #region AtResize
            Action AtResize = delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                canvas.width = Native.window.Width;
                canvas.height = Native.window.Height;

                this.onresize(Native.window.Width, Native.window.Height);
            };

            AtResize();

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


          

            Native.window.onframe += delegate { this.onframe(); };


            #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




            Native.Document.onmousemove +=
                e =>
                {
                    s.ucolor_1 = e.CursorX / Native.window.Width;
                    s.ucolor_2 = e.CursorY / Native.window.Height;
                };

        }
        private void InitializeContent(IDefault page = null)
        {
			#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: "ChromeUDPSendAsync");

						var xappwindow = await chrome.app.window.create(
							   Native.document.location.pathname, options: null
						);

						//xappwindow.setAlwaysOnTop

						xappwindow.show();

						await xappwindow.contentWindow.async.onload;

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


					return;
				}
			}
			#endregion


			var canvas = new IHTMLCanvas().AttachToDocument();

            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;

            canvas.style.SetLocation(0, 0);


            //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html


            var gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");

            #region Dispose
            var IsDisposed = false;

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;

                canvas.Orphanize();
            };
            #endregion


            var s = new PulsSurface(this);

            this.onsurface(gl);

            #region AtResize
            Action AtResize = delegate
            {
                if (IsDisposed)
                {
                    return;
                }

                canvas.width = Native.window.Width;
                canvas.height = Native.window.Height;

                this.onresize(Native.window.Width, Native.window.Height);

                Console.WriteLine("onresize");
            };

            AtResize();

            Native.window.onresize += delegate
            {
                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




            #region loop
            Action loop = null;

            loop = delegate
            {
                if (IsDisposed)
                    return;

                this.onframe();

                Native.window.requestAnimationFrame += loop;

            };

            Native.window.requestAnimationFrame += loop;
            #endregion


        }