Exit() public method

Closes the GameWindow. Equivalent to NativeWindow.Close method.

Override if you are not using GameWindow.Run().

If you override this method, place a call to base.Exit(), to ensure proper OpenTK shutdown.

public Exit ( ) : void
return void
Ejemplo n.º 1
0
    protected void OpenExampleClick(object senderObj, EventArgs eArgs)
    {
        using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    game.VSync = VSyncMode.On;

                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.KeyDown += (sender, e) =>
                {
                  if(e.Key == OpenTK.Input.Key.Escape)
                  {
                    game.Exit();
                  }
                };

                game.UpdateFrame += (sender, e) =>
                {
        //                    // add game logic, input handling
        //                    if (game.Keyboard[OpenTK.Input.Key.Escape])
        //                    {
        //                        game.Exit();
        //                    }
                };

                game.RenderFrame += (sender, e) =>
                {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);

                    GL.Begin(PrimitiveType.Triangles);

                    GL.Color3(Color.MidnightBlue);
                    GL.Vertex2(-1.0f, 1.0f);
                    GL.Color3(Color.SpringGreen);
                    GL.Vertex2(0.0f, -1.0f);
                    GL.Color3(Color.Ivory);
                    GL.Vertex2(1.0f, 1.0f);

                    GL.End();

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
    }
Ejemplo n.º 2
0
        private static void Main(string[] args)
        {
            var sprites = new List<Sprite>();

            Window = new GameWindow(800, 600, GraphicsMode.Default, "Blunder Buzz");

            Window.Load += (sender, e) => {
                Window.VSync = VSyncMode.On;

                sprites.Add(new Sprite(new Shader("Shaders/basicVertex.glsl", "Shaders/basicFragment.glsl")));
            };

            Window.UpdateFrame += (sender, e) => {
                if (Window.Keyboard[Key.Escape]) {
                    Window.Exit();
                }

                foreach (var sprite in sprites) {
                    sprite.Update();
                }
            };

            Window.RenderFrame += (sender, e) => {
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                GL.ClearColor(Color.CornflowerBlue);

                foreach (var sprite in sprites) {
                    sprite.Render();
                }

                Window.SwapBuffers();
            };

            Window.Run(DisplayDevice.Default.RefreshRate);
        }
Ejemplo n.º 3
0
		public static void Main (string[] args)
		{
			Console.WriteLine ("Hello World!");

			using (var game = new GameWindow ())
			{
				const int kVertsPerParticle = 6;
				const int kParticleCountX = 500;
				const int kParticleCountY = 320;

				var solution = new MapPersistent (kVertsPerParticle, game.Width, game.Height);
				var problem = new DynamicStreamingProblem (solution, kVertsPerParticle, kParticleCountX, kParticleCountY);

				game.Load += (sender, e) =>
				{
					// setup settings, load textures, sounds
					game.VSync = VSyncMode.On;

					problem.Init();
				};

				game.Unload += (sender, e) => 
				{
					problem.Shutdown();
				};

				game.KeyDown += (object sender, KeyboardKeyEventArgs e) => 
				{
					if (e.Key == Key.Space)
					{
						game.Exit();
					}
				};

				game.UpdateFrame += (sender, e) =>
				{
					// add game logic, input handling

					// update shader uniforms

					// update shader mesh
				};

				game.RenderFrame += (sender, e) =>
				{
					game.SwapBuffers();
				};

				game.Resize += (sender, e) =>
				{
					//GL.Viewport(0, 0, game.Width, game.Height);
					solution.SetSize(game.Width, game.Height);
				};

				game.Run(60.0);
			}
		}
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    game.VSync = VSyncMode.On;
                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                };
                double rotation = 0;
                game.RenderFrame += (sender, e) =>
                {
                    rotation += 1;
                    rotation %= 360;
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);
                    GL.Rotate(rotation, 0, 0, 1);
                    GL.Begin(PrimitiveType.Triangles);

                    GL.Color3(Color.MidnightBlue);
                    GL.Vertex3(-1.0f, 1.0f,-1.0f);
                    GL.Color3(Color.SpringGreen);
                    GL.Vertex3(0.0f, -1.0f,-1.0f);
                    GL.Color3(Color.Ivory);
                    GL.Vertex3(1.0f, 1.0f,-1.0f);

                    GL.End();

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 5
0
        public MyApplication()
        {
            gameWindow = new GameWindow();
            logic = new GameLogic();
            Texture texPlayer = TextureLoader.FromBitmap(Resourcen.blueships1);
            Texture texEnemy = TextureLoader.FromBitmap(Resourcen.redship4);
            Texture texBullet = TextureLoader.FromBitmap(Resourcen.blueLaserRay);
            visual = new Visual(texEnemy, texBullet, texPlayer);
            sound = new Sound();
            logic.OnShoot += (sender, args) => { sound.Shoot(); };
            logic.OnEnemyDestroy += (sender, args) => { sound.DestroyEnemy(); };
            logic.OnLost += (sender, args) => { sound.Lost(); gameWindow.Exit(); };

            gameWindow.Load += GameWindow_Load;
            gameWindow.Resize += GameWindow_Resize;
            gameWindow.UpdateFrame += GameWindow_UpdateFrame;
            gameWindow.RenderFrame += GameWindow_RenderFrame;
            gameWindow.RenderFrame += (sender, e) => { gameWindow.SwapBuffers(); };
            sound.Background();
            timeSource.Start();
            gameWindow.Run(60.0);
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {

            Mesh monkey = new Mesh(null,null) ;
            bool spaceHeld = false;
            float rotation = 0;

            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    
                    monkey = Mesh.LoadFromOBJFile(@"Content/Models/Monkey.obj");

                    game.VSync = VSyncMode.On;
                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    spaceHeld = Keyboard.GetState().IsKeyDown(Key.Space);

                    if (Keyboard.GetState().IsKeyDown(Key.Right))
                        rotation += -0.1f;
                    if (Keyboard.GetState().IsKeyDown(Key.Left))
                        rotation += 0.1f;

                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                };

                game.RenderFrame += (sender, e) =>
                {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);


                    Matrix4 translation = Matrix4.LookAt(new Vector3((float)Math.Cos(rotation),0,(float)Math.Sin(rotation)), Vector3.Zero, Vector3.UnitY);
                    Matrix4 scale = Matrix4.CreateScale(0.2f);
                    Matrix4 modelView = translation * scale;
                    GL.LoadMatrix(ref modelView);


                    GL.Begin(PrimitiveType.Triangles);


                    for(int t = 0; t < monkey.tris.Length; t += 3)
                    {
                        GL.Color3(spaceHeld ? Color.MidnightBlue : Color.OrangeRed);
                        GL.Vertex3(monkey.vertices[monkey.tris[t] - 1]);
                        GL.Color3(Color.SpringGreen);
                        GL.Vertex3(monkey.vertices[monkey.tris[t + 1] - 1]);
                        GL.Color3(Color.Ivory);
                        GL.Vertex3(monkey.vertices[monkey.tris[t + 2] - 1]);
                    }

                    GL.End();

                    game.SwapBuffers();
                };

                game.Run(60.0);

            }
        }
Ejemplo n.º 7
0
        public void Run()
        {
            //initPoints();
            Color c = Color.MidnightBlue;
            Matrix4 m = Matrix4.Mult(Matrix4.Identity, Matrix4.CreateRotationY(Convert.ToSingle(-Math.PI / 4)));
            m = Matrix4.Mult(m, Matrix4.CreateRotationX(Convert.ToSingle(Math.PI/4)));
            Matrix4 DefaultMatrix = m;
            float pos = 0;
            float rot = 0;
            float scale=1.0f;
            int zoomDirection = 0;

            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    game.VSync = VSyncMode.On;
                    game.Title = "Space State 3D";
                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    if (game.Keyboard[Key.Number1])
                    {
                        m = Matrix4.Identity;
                    }
                    if (game.Keyboard[Key.Number2])
                    {
                        m = Matrix4.Mult(Matrix4.Identity, Matrix4.CreateRotationX(Convert.ToSingle(-Math.PI/2)));
                    }
                    if (game.Keyboard[Key.Number3])
                    {
                        m = Matrix4.Mult(Matrix4.Identity, Matrix4.CreateRotationY(Convert.ToSingle(Math.PI/2)));
                    }
                    if (game.Mouse[MouseButton.Left])
                    {
                        m = DefaultMatrix;
                    }
                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                    if (game.Keyboard[Key.W])
                    {
                        m=Matrix4.Mult(m,Matrix4.CreateTranslation(0, 0.1f, 0));
                        //pointsArray[0].Z = pointsArray[0].Z + 0.1f;
                    }
                    if (game.Keyboard[Key.S])
                    {
                        m=Matrix4.Mult(m,Matrix4.CreateTranslation(0, -0.1f, 0));
                        //pointsArray[0].Z = pointsArray[0].Z - 0.1f;
                    }
                    if (game.Keyboard[Key.A])
                    {
                        m = Matrix4.Mult(m, Matrix4.CreateTranslation(-0.1f, 0, 0));
                        //pointsArray[0].X = pointsArray[0].X - 0.1f;
                    }
                    if (game.Keyboard[Key.D])
                    {
                        m = Matrix4.Mult(m, Matrix4.CreateTranslation(+0.1f, 0, 0));
                        //pointsArray[0].X = pointsArray[0].X + 0.1f;
                    }


                    if (game.Keyboard[Key.Up])
                    {
                        //rot += .1f;
                        //m= Matrix4.CreateTranslation(pos, 0, 0);
                        m = Matrix4.Mult(m, Matrix4.CreateRotationX(.1f));
                    }
                    if (game.Keyboard[Key.Right])
                    {
                        m = Matrix4.Mult(m, Matrix4.CreateRotationY(.1f));
                    }
                    if (game.Keyboard[Key.Left])
                    {
                        m = Matrix4.Mult(m, Matrix4.CreateRotationY(-0.1f));
                    }
                    if (game.Keyboard[Key.Down])
                    {

                        m = Matrix4.Mult(m, Matrix4.CreateRotationX(-0.1f));
                    }
                    if (game.Keyboard[Key.KeypadPlus])
                    {
                        if (zoomDirection == 1)
                            scale += 0.01f;
                        else
                            scale = 1.01f;

                        m = Matrix4.Mult(m, Matrix4.Scale(scale));
                        zoomDirection = 1;
                    }
                    if (game.Keyboard[Key.KeypadMinus])
                    {
                        if (zoomDirection == -1)
                            scale -= 0.01f;
                        else
                            scale = 0.99f;
                        
                        m = Matrix4.Mult(m, Matrix4.Scale(scale));
                        zoomDirection = -1;
                    }
                    if (game.Keyboard[Key.Keypad0])
                    {
                        zoomDirection = 0;
                        m = Matrix4.Mult(m, Matrix4.Scale(2.0f-scale));
                        scale = 1.0f;
                    }
                };

                game.RenderFrame += (sender, e) =>
                {
                    //m=Matrix4.Mult(m,Matrix4.Scale(scale));
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadMatrix(ref m);
                    //GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);
                    
                    // Draw the Axes
                    GL.Begin(PrimitiveType.Lines);
                    GL.Color4(new Color4(255, 0, 0, 64));
                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(1f, 0f, 0f);
                    GL.Color4(new Color4(0, 255, 0, 64));
                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(0f, 1f, 0f);
                    GL.Color4(new Color4(0, 0, 255, 64));
                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(0f, 0f, 1f);
                    GL.End();
              

                    // Draw the Planes
                    /*
                    GL.Begin(PrimitiveType.Quads);
                    GL.Color4(new Color4(255, 255, 255, 64));
                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(1f, 0f, 0f);
                    GL.Vertex3(1f, 1f, 0f);
                    GL.Vertex3(0f, 1f, 0f);

                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(1f, 0f, 0f);
                    GL.Vertex3(1f, 0f, 1f);
                    GL.Vertex3(0f, 0f, 1f);

                    
                    GL.Vertex3(0f, 0f, 0f);
                    GL.Vertex3(0f, 1f, 0f);
                    GL.Vertex3(0f, 1f, 1f);
                    GL.Vertex3(0f, 0f, 1f);
                    GL.End();*/

                    // Draw the points
                    if ((pointsArray != null) && !BoxMode)
                    {
                        GL.Begin(PrimitiveType.Points);
                        GL.Color3(Color.Red);
                        for (int i = 0; i < pointsArray.Length; i++)
                        {
                            if (stimulusActive[i])
                                GL.Color3(Color.Red);
                            else
                                GL.Color3(Color.Cyan);

                            if (i == pointsArray.Length - 1) // Last point added will be White
                                GL.Color3(Color.White);

                            GL.Vertex3(pointsArray[i]);
                            /*DrawBox(pointsArray[i].X,
                                    pointsArray[i].Y,
                                    pointsArray[i].Z,
                                    0.0025f);*/
                        } 
                        GL.End();
                   
                    }

                    // Draw the Box
                    if ((pointsArray != null) && (BoxMode))
                    {
                        for (int i = 0; i < pointsArray.Length; i++)
                        {
                            GL.Color3(Color.FromArgb(cubeColor[i],cubeColor[i],cubeColor[i]));
                            DrawBox(pointsArray[i].X,
                                    pointsArray[i].Y,
                                    pointsArray[i].Z,
                                    0.025f);
                        }
                                                  
                    }

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(30.0);
            }

        }
Ejemplo n.º 8
0
    /// <summary>
    /// This procedure contains the user code. Input parameters are provided as regular arguments, 
    /// Output parameters as ref arguments. You don't have to assign output parameters, 
    /// they will have a default value.
    /// </summary>
    private void RunScript(Mesh Profile, List<Mesh> x, bool y, ref object A)
    {
        if(y){
          try{
        using (var game = new GameWindow(Width, Height, GraphicsMode.Default))
        {
          game.Load += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.ClearColor(Color.Gray);// 背景
            OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.DepthTest);//线框模式
            // OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.CullFace);//反面不可见
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Ambient, LightAmbient);//设置系统灯光
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Diffuse, LightDiffuse);		// 设置漫射光
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Position, LightPosition);	// 设置光源位置
            OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Light0);//加载灯光
            xl = 0;
            };

          game.Resize += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.Viewport(0, 0, Width, Height);
            OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Projection);
            OpenTK.Graphics.OpenGL.GL.LoadIdentity();
            OpenTK.Graphics.OpenGL.GL.Ortho(-200.0, 200.0, -200.0, 200.0, 0.0, 1000.0);
            };
          game.UpdateFrame += (sender, e) =>
            {
            if (game.Keyboard[Key.Escape]){ game.Exit();}
            };
          game.RenderFrame += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.Clear
              (OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit | OpenTK.Graphics.OpenGL.ClearBufferMask.DepthBufferBit);
            OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Modelview);
            OpenTK.Graphics.OpenGL.GL.LoadIdentity();
            Drawface2D(x[xl],4);
            if(xl < x.Count){
              Bitmap bitmap1 = new Bitmap(Width, Height);
              int arrLen = Width * Height * 4;
              Byte[] colorArr = new Byte[arrLen];
              OpenTK.Graphics.OpenGL.GL.ReadPixels(0, 0, Width, Height, OpenTK.Graphics.OpenGL.PixelFormat.Rgba,
                OpenTK.Graphics.OpenGL.PixelType.Byte, colorArr);
              int sign = 0;
              for(int i = Height - 1;i >= 0;i--){
                for(int j = 0;j < Width;j++){
                  bitmap1.SetPixel(j, i, Color.FromArgb(colorArr[sign + 3] * 2, colorArr[sign] * 2, colorArr[sign + 1] * 2, colorArr[sign + 2] * 2));
                  // Print(colorArr[sign + 3].ToString() + "/" + colorArr[sign].ToString() + "/" + colorArr[sign + 1].ToString() + "/" + colorArr[sign + 2].ToString());

                  sign += 4;
                }}
              String str = @"D:\maps\temp" + xl.ToString() + ".jpg";
              bitmap1.Save(str);
              game.SwapBuffers();
            }
            xl++;
            if(xl >= x.Count)game.Close();//xl = x.Count - 1;
            };
          game.Run(1);
        }
          }catch(Exception ex){Print(ex.ToString());}
        }
    }
Ejemplo n.º 9
0
        public void Start(string path = "")
        {
            // Configuration
            double xOffset = 0, yOffset = 0, zOffset = 0,
                   xRotate = 0, yRotate = 0, zRotate = 0,
                   scale = 1,
                   moveSpeed = 3, rotateSpeed = 3, scaleSpeed = 0.05;
            bool perspectiveMode = false, drawAxis = false;

            _drawPolygon = false;

            // Visual window init
            _visualWindow       = new VisualWindow();
            _visualWindow.Load += (s, args) =>
            {
                _visualWindow.Width = _visualWindow.Height = 400;
                _visualWindow.VSync = VSyncMode.On;

                if (string.IsNullOrEmpty(path))
                {
                    LoadDefaultScene();
                }
                else
                {
                    LoadFile(path);
                }
            };
            _visualWindow.Resize += (s, args) =>
            {
                GL.Viewport(0, 0, _visualWindow.Width, _visualWindow.Height);
            };
            _visualWindow.FileDrop += (s, args) =>
            {
                LoadFile(args.FileName);
            };
            _visualWindow.UpdateFrame += (s, args) =>
            {
                var keyboardState = Keyboard.GetState();

                if (keyboardState.IsKeyDown(Key.Escape))
                {
                    _visualWindow.Exit();
                }


                if (keyboardState.IsKeyDown(Key.Up))
                {
                    yOffset += moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Down))
                {
                    yOffset -= moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Right))
                {
                    xOffset += moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Left))
                {
                    xOffset -= moveSpeed;
                }

                if (keyboardState.IsKeyDown(Key.Plus))
                {
                    scale += scaleSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Minus))
                {
                    scale -= scaleSpeed;
                }

                if (keyboardState.IsKeyDown(Key.Home))
                {
                    xRotate -= rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.End))
                {
                    yRotate -= rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Delete))
                {
                    zRotate -= rotateSpeed;
                }


                if (keyboardState.IsKeyDown(Key.PageUp))
                {
                    xRotate += rotateSpeed;
                    yRotate += rotateSpeed;
                    zRotate += rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.PageDown))
                {
                    xRotate -= rotateSpeed;
                    yRotate -= rotateSpeed;
                    zRotate -= rotateSpeed;
                }

                if (keyboardState.IsKeyDown(Key.BackSpace))
                {
                    xOffset = 0; yOffset = 0; zOffset = 0;
                    xRotate = 0; yRotate = 0; zRotate = 0;
                    scale   = 1;
                }

                if (keyboardState.IsKeyDown(Key.P))
                {
                    perspectiveMode = true;
                }
                if (keyboardState.IsKeyDown(Key.O))
                {
                    perspectiveMode = false;
                }
                if (keyboardState.IsKeyDown(Key.Z))
                {
                    drawAxis = true;
                }
                if (keyboardState.IsKeyDown(Key.Z) && keyboardState.IsKeyDown(Key.ShiftLeft))
                {
                    drawAxis = false;
                }
                if (keyboardState.IsKeyDown(Key.L))
                {
                    _drawPolygon = true;
                }
                if (keyboardState.IsKeyDown(Key.L) && keyboardState.IsKeyDown(Key.ShiftLeft))
                {
                    _drawPolygon = false;
                }
            };
            _visualWindow.RenderFrame += (s, args) =>
            {
                float width  = _loadedScene.WorldRight - _loadedScene.WorldLeft,
                      height = _loadedScene.WorldTop - _loadedScene.WorldBottom,
                      depth  = _loadedScene.WorldForward - _loadedScene.WorldBack;

                float halfX = (_loadedScene.WorldRight + _loadedScene.WorldLeft) / 2,
                      halfY = (_loadedScene.WorldTop + _loadedScene.WorldBottom) / 2,
                      halfZ = (_loadedScene.WorldBack + _loadedScene.WorldForward) / 2;


                GL.ClearColor(255, 255, 255, 255);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadIdentity();

                if (perspectiveMode)
                {
                    // GLU Perspective
                    Matrix4 perspectiveMatrix = Matrix4.CreatePerspectiveFieldOfView(
                        MathHelper.DegreesToRadians(90),
                        width / height,
                        0.1f,
                        depth * 2);
                    GL.LoadMatrix(ref perspectiveMatrix);
                    // Look at
                    GL.Translate(-halfX, -halfY, -halfZ);
                }
                else
                {
                    GL.Ortho(_loadedScene.WorldLeft, _loadedScene.WorldRight,
                             _loadedScene.WorldBottom, _loadedScene.WorldTop,
                             _loadedScene.WorldForward, _loadedScene.WorldBack);
                }
                GL.Translate(0, 0, -depth);


                // Draw Axis
                if (drawAxis)
                {
                    GL.Color3(0f, 255f, 0f);
                    GL.Begin(BeginMode.Lines);
                    GL.Vertex3(-width, halfY, halfZ);
                    GL.Vertex3(width * 2, halfY, halfZ);
                    GL.Vertex3(halfX, -height, halfZ);
                    GL.Vertex3(halfX, height * 2, halfZ);
                    GL.Vertex3(halfX, halfY, -depth);
                    GL.Vertex3(halfX, halfY, depth);
                    GL.End();
                }

                // Translations
                GL.Translate(xOffset, yOffset, zOffset);
                GL.Translate(halfX, halfY, halfZ);
                GL.Rotate(xRotate, 1, 0, 0);
                GL.Rotate(yRotate, 0, 1, 0);
                GL.Rotate(zRotate, 0, 0, 1);
                GL.Scale(scale, scale, scale);
                GL.Translate(-halfX, -halfY, -halfZ);

                // Draw
                GL.Color3(255f, 0, 0);
                foreach (Parallelepiped parallelepiped in _loadedScene.Parallelepipeds)
                {
                    DrawParallelepiped(parallelepiped.FirstCoordinates, parallelepiped.SecondCoordinates);
                }


                _visualWindow.SwapBuffers();
            };

            _visualWindow.Run(60.0);
        }
Ejemplo n.º 10
0
        public static void Main()
        {
            // remove local variables later as needed
            float posY = 0.0f;
            float posX = 0.0f;
            float rotate = 0.0f;
            float rotateVel = 0.0f;
            float rotateAcc = 0.0f;
            float accX = 0.0f;
            float accY = 0.0f;
            float velX = 0.0f;
            float velY = 0.0f;
            const float MAX_VELOCITY = 5.0f;
            const float ACCELERATION = 0.1f;
            const float ROT_ACC = .30f;
            const float MAX_ROT_VEL = 17 * ROT_ACC; // if not an exact rotation, will continue to spin once key is lifted up

            List<float[]> bullets = new List<float[]>();
            //bool fireBullet = false;
            //float bulX = 0.0f;
            //float bulY = 0.0f;
            const float BULLET_VEL = 15.0f;
            //float bulR = 0.0f;

            // firing rate in ms
            const int FIRE_RATE = 500; //ms

            fireRate = new Timer(FIRE_RATE);
            fireRate.Elapsed += new ElapsedEventHandler(FireBullet);

            using (var game = new GameWindow(1000, 800))
            {
                game.Load += (sender, e) =>
                {
                    // occurs before window is displayed for the first time
                    // setup settings, load textures, sounds from disk
                    // VSync will let the CPU idle if game is not running any calculations
                    game.VSync = VSyncMode.On;
                };

                game.Resize += (sender, e) =>
                {
                    // what happens when the window resizes?
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // occurs when it is time to update a frame
                    // update occurs before a render
                    // handle input
                    // update object positions
                    // run physics
                    // AI calculations

                    // physics calculations

                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                    if (game.Keyboard[Key.Up])
                    {
                        accX = ACCELERATION * (float)Math.Cos((rotate + 90) * Math.PI / 180);
                        accY = ACCELERATION * (float)Math.Sin((rotate + 90) * Math.PI / 180);
                    }
                    if (game.Keyboard[Key.Left])
                    {
                        rotateAcc += ROT_ACC;
                    }
                    if (game.Keyboard[Key.Right])
                    {
                        rotateAcc -= ROT_ACC;
                    }
                    if (game.Keyboard[Key.Space])
                    {
                        if (canFire)
                        {
                            canFire = false;
                            bullets.Add(new float[] { posX, posY, rotate });
                            //fireBullet = true;
                            fireRate.Start();
                        }
                    }

                    // end key bindings

                    // fire bullet?
                    for (int i = 0; i < bullets.Count; i++)
                    {
                        bullets[i][0] += BULLET_VEL * (float)Math.Cos((bullets[i][2] + 90) * Math.PI / 180);
                        bullets[i][1] += BULLET_VEL * (float)Math.Sin((bullets[i][2] + 90) * Math.PI / 180);

                        if ((bullets[i][0] < -(game.Width / 2) - 30) || (bullets[i][0] > (game.Width / 2) + 30) || (bullets[i][1] < -(game.Height / 2) - 30) || (bullets[i][1] > (game.Height / 2) + 30))
                        {
                            bullets.RemoveAt(i);
                        }
                    }

                    /*if (fireBullet)
                    {
                        // if bullet is not yet set to ship's position
                        if (bulX == 0 && bulY == 0 && bulR == 0)
                        {
                            bulX = posX;
                            bulY = posY;
                            bulR = rotate;
                        }
                        else
                        {
                            bulX += BULLET_VEL * (float)Math.Cos((bulR + 90) * Math.PI / 180);
                            bulY += BULLET_VEL * (float)Math.Sin((bulR + 90) * Math.PI / 180);
                        }

                        if ((bulX < -(game.Width / 2) - 30) || (bulX > (game.Width / 2) + 30) || (bulY < -(game.Height / 2) - 30) || (bulY > (game.Height / 2) + 30))
                        {
                            bulR = bulX = bulY = 0;
                            fireBullet = false;
                        }
                    }*/

                    // determine ship placement
                    velX += accX;
                    velY += accY;

                    float maxVY = (accY / ACCELERATION) * MAX_VELOCITY;
                    float maxVX = (accX / ACCELERATION) * MAX_VELOCITY;

                    float totalVel = (float)Math.Sqrt(velX * velX + velY * velY);
                    if (totalVel > MAX_VELOCITY)
                    {
                        if (velX > maxVX)
                            velX -= ACCELERATION;
                        else if (velX < maxVX)
                            velX += ACCELERATION;

                        if (velY > maxVY)
                            velY -= ACCELERATION;
                        else if (velY < maxVY)
                            velY += ACCELERATION;
                    }

                    posX += velX;
                    posY += velY;

                    // determine rotational amount
                    rotateVel += rotateAcc;

                    if (rotateVel > MAX_ROT_VEL || rotateVel < -MAX_ROT_VEL)
                        rotateVel -= rotateAcc;

                    if (rotateAcc == 0.0 && rotateVel > 0)
                    {
                        if (rotateVel < 0.0001)
                            rotateVel = 0;
                        else
                            rotateVel -= ROT_ACC;
                    }
                    if (rotateAcc == 0.0 && rotateVel < 0)
                    {
                        if (rotateVel > -0.0001)
                            rotateVel = 0;
                        else
                            rotateVel += ROT_ACC;
                    }

                    rotate += rotateVel;

                    if (rotate > 360)
                        rotate = rotate - 360;
                    if (rotate < 0)
                        rotate = rotate + 360;

                    //Console.WriteLine("v: " + rotateVel + " a: " + rotateAcc);

                    // reset acceleration for next time key is pressed
                    accX = 0;
                    accY = 0;
                    rotateAcc = 0;

                    // if ship goes off screen, wrap around

                    if (posX < -(game.Width / 2) - 30)
                        posX = (game.Width / 2) + 30;
                    if (posX > (game.Width / 2) + 30)
                        posX = -(game.Width / 2) - 30;
                    if (posY < -(game.Height / 2) - 30)
                        posY = (game.Height / 2) + 30;
                    if (posY > (game.Height / 2) + 30)
                        posY = -(game.Height / 2) - 30;
                };

                game.RenderFrame += (sender, e) =>
                {
                    // occurs when it is time to render a frame
                    // render graphics
                    // always begins with GL.Clear() and ends with a call to SwapBuffers
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    // two types of matrix modes:
                    // Projection: alters how the points get projected onto the screen. Be in this mode to call Matrix4.CreatePerspectiveFieldOfView() or GL.Ortho()
                    // ModelView: alters how the points will be shifted around in  space, by being translated with GL.Translate() and rotated with GL.Rotate()
                    // "It is common to switch to projection mode before each major drawing step (main scene, GUI, etc) set up the projection matrices, then switch to
                    // "model-view until the next one. This way, you can leave your projection unaltered while you change around the transformations of the scene by moving
                    // "the camera, altering positions of objects, etc."
                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity(); // only worry about the projection matrix, replace previous matrix
                    //GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);
                    GL.Ortho(game.Width / -2f, game.Width / 2f, game.Height / -2f, game.Height / 2f, -1.0, 0.0);

                    // remove later as needed:
                    GL.MatrixMode(MatrixMode.Modelview);

                    // remove later as needed:
                    foreach (float[] bullet in bullets)
                    {
                        GL.LoadIdentity();

                        GL.Translate(bullet[0], bullet[1], 0.0f);
                        GL.Rotate(bullet[2], 0.0f, 0.0f, 1.0f);
                        // end remove

                        GL.Begin(PrimitiveType.Triangles); // begin points

                        GL.Color3(Color.Yellow);
                        GL.Vertex2(0f, 10f);

                        //GL.Vertex2(0f / game.Width, 35f / game.Width);
                        GL.Color3(Color.Black);
                        GL.Vertex2(-4f, -10f);
                        GL.Vertex2(4f, -10f);

                        //GL.Vertex2(-30f / game.Width, -35f / game.Width);
                        //GL.Vertex2(30f / game.Width, -35f / game.Width);

                        GL.End(); // end points
                    }

                    GL.LoadIdentity();

                    GL.Translate(posX, posY, 0.0f);
                    GL.Rotate(rotate, 0.0f, 0.0f, 1.0f);
                    // end remove

                    GL.Begin(PrimitiveType.Triangles); // begin points

                    GL.Color3(Color.DimGray);
                    GL.Vertex2(0f, 17f);

                    //GL.Vertex2(0f / game.Width, 35f / game.Width);
                    GL.Color3(Color.White);
                    GL.Vertex2(-15f, -17f);
                    GL.Vertex2(15f, -17f);

                    //GL.Vertex2(-30f / game.Width, -35f / game.Width);
                    //GL.Vertex2(30f / game.Width, -35f / game.Width);

                    GL.End(); // end points

                    game.SwapBuffers(); // draw the new matrix

                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 11
0
        public static void Main()
        {
            using(var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {

                    // Setup settings, load textures, sound etc.
                    game.VSync	= VSyncMode.On;
                    game.Width	= 1280;
                    game.Height	= 720;

                    // Center window to desktop
                    game.Location = new Point(	OpenTK.DisplayDevice.Default.Width/2 - game.Width/2,
                                                OpenTK.DisplayDevice.Default.Height/2 - game.Height/2);

                    GL.ClearColor(0.4f, 0.4f, 0.4f, 1);
                    GraphicsManager.init_text_writer(game.ClientSize, game.ClientSize);
                    _skeletons.Add(new Skeleton());
                };

                game.Resize += (sender, e) =>
                {
                    int offset = 0;
                    GL.Viewport(0 + offset, 0 + offset, game.Width + offset, game.Height + offset);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // Add game logic, input handling
                    if(game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                    if(game.Keyboard[Key.R])
                    {
                        reset();
                        Nearest.release_check();
                    }
                    if(game.Keyboard[Key.A] && _active_time < DateTime.Now.Ticks)
                    {
                        add_doll();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.P] && _active_time < DateTime.Now.Ticks)
                    {
                        _pause = !_pause;
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.F] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].toggle_forces();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.B] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].toggle_bones();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.G] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].toggle_graphics();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.C] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].toggle_climbing_mode();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Keyboard[Key.M] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].toggle_christmas_mode();

                        _snow.toggle();

                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Mouse[MouseButton.Right] && _active_time < DateTime.Now.Ticks)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].pin_point();
                        if(_active_time < DateTime.Now.Ticks + 2000000)
                            _active_time = DateTime.Now.Ticks + 2000000;
                    }
                    if(game.Mouse[MouseButton.Left])
                    {
                        // Finds the nearest ragdoll to mouse
                        Nearest.check_nearest(_skeletons, new Vector2D(game.Mouse.X, game.Mouse.Y));
                        if(_ragdoll_release_time < DateTime.Now.Ticks + 2000000)
                            _ragdoll_release_time = DateTime.Now.Ticks + 2000000;

                        // Adds a mouse drag force.
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].mouse_force(new Vector2D(game.Mouse.X, game.Mouse.Y));
                    }
                    else
                    {
                        // Makes it possible to drag around another ragdoll
                        if(_ragdoll_release_time < DateTime.Now.Ticks)
                            Nearest.release_check();

                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].release_point_lock();
                    }

                    // Update skeleton
                    if(!_pause)
                    {
                        for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].update(1.0/10.0);
                        _snow.update(1.0/10.0);
                    }
                };

                game.RenderFrame += (sender, e) =>
                {
                    // Render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(0, game.Width, game.Height, 0, -1, 1);

                    // Render ragdolls
                    for(int i = 0; i < _skeletons.Count; ++i)
                            _skeletons[i].draw(new Vector2D(game.Mouse.X, game.Mouse.Y));

                    // Render snow
                    _snow.draw();

                    // Some user friendly info
                    if(_fps_timer < DateTime.Now.Ticks)
                    {
                        _fps_timer = DateTime.Now.Ticks + 800000;
                        _fps = Math.Round(game.RenderFrequency, 2);
                    }

                    // Render help text
                    draw_info();

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 12
0
		public static void Main (string[] args)
		{
			using (var game = new GameWindow ())
			using (var ac = new AudioContext ())
			{				
				using (var fs = File.OpenRead ("01_Ghosts_I.flac"))
				using (var reader = new FLACDecoder (fs, new FLACPacketQueue (), new EmptyStubLogger ()))
				using (var ms = new MemoryStream())
				{
					Console.WriteLine ("Sample rate : {0}", reader.SampleRate);
					Console.WriteLine ("Duration : {0}", reader.Duration);

					reader.CopyTo (ms);

					byte[] sound_data = ms.ToArray ();

					int buffer = AL.GenBuffer ();
					AL.BufferData(buffer, reader.Format, sound_data, sound_data.Length, reader.SampleRate);
					ALError error_code = AL.GetError ();
					if (error_code != ALError.NoError)
					{
						// respond to load error etc.
						Console.WriteLine(error_code);
					}

					int source = AL.GenSource(); // gen 2 Source Handles

					AL.Source( source, ALSourcei.Buffer, buffer ); // attach the buffer to a source
					error_code = AL.GetError ();
					if (error_code != ALError.NoError)
					{
						// respond to load error etc.
						Console.WriteLine(error_code);
					}


					AL.SourcePlay(source); // start playback
					error_code = AL.GetError ();
					if (error_code != ALError.NoError)
					{
						// respond to load error etc.
						Console.WriteLine(error_code);
					}

					AL.Source( source, ALSourceb.Looping, false ); // source loops infinitely
					error_code = AL.GetError ();
					if (error_code != ALError.NoError)
					{
						// respond to load error etc.
						Console.WriteLine(error_code);
					}
				}

				game.Load += (sender, e) =>
				{
					// setup settings, load textures, sounds
					game.VSync = VSyncMode.On;
				};

				game.Unload += (sender, e) => 
				{
				};

				game.KeyDown += (object sender, KeyboardKeyEventArgs e) => 
				{
					if (e.Key == Key.Space)
					{
						game.Exit();
					}
				};

				game.UpdateFrame += (sender, e) =>
				{
					//stream.Update(1.0f / 60f);
				};				

				game.RenderFrame += (sender, e) =>
				{
					GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

					game.SwapBuffers();
				};

				game.Resize += (sender, e) =>
				{
					GL.Viewport(0, 0, game.Width, game.Height);
				};

				game.Run(60.0);
			}
		}
Ejemplo n.º 13
0
		static void Main() {
			Console.WriteLine("Entering");

			using (var game = new GameWindow(1920, 1080, new GraphicsMode(ColorFormat.Empty, 8, 0, 6), "Heart of Gold", GameWindowFlags.Default)) {
				
				game.Icon = Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);
				var size = 2048;
				var zoom = 1.0;
				game.Load += (sender, e) => { game.VSync = VSyncMode.On;
					GL.PointSize(10);
					
				};
				game.MouseWheel += delegate (object sender, MouseWheelEventArgs args) {
					if (args.Delta > 0)
						zoom *= 1.1;
					//zoom += args.Delta/10.0;
					else
						zoom /= 1.1;
					//zoom += args.Delta/10.0;

					if (zoom <= 0.1) zoom = 0.1;

					var aspect = game.Width / (double)game.Height;

					//GL.Viewport(0, 0, game.Width, game.Height);
					//GL.Ortho(-xsize, xsize, ysize, -ysize, 0, 4.0);
				};
				game.Resize += (sender, e) =>
					GL.Viewport(0, 0, game.Width, game.Height);

				#region Heights

				var matrix = new double[size, size];
				var r = new Random();

				#endregion


				#region Color

				Console.WriteLine("Initializing color...");
				var cmatrix = new Color[size, size];
				using (var b = (Bitmap)Image.FromFile(@"E:\Downloads\Untitled5.png")) {
					for (var i = 0; i < size; i++) {
						Console.Write($"\rOn column {i,4} of {size}");
						for (var j = 0; j < size; j++) {
							matrix[i, j] = ((double)b.GetPixel(i, j).A + 1);// / 8.0;
							cmatrix[i, j] = Color.FromArgb(255, b.GetPixel(i, j));
						}
					}
				}
				Console.WriteLine();
				#endregion


				bool wDown = false,
					 aDown = false,
					 sDown = false,
					 dDown = false;
				game.KeyDown += delegate(object sender, KeyboardKeyEventArgs args) {
					switch (args.Key) {
						case Key.W:
							wDown = true;
							break;
						case Key.A:
							aDown = true;
							break;
						case Key.S:
							sDown = true;
							break;
						case Key.D:
							dDown = true;
							break;
					}
				};
				Vector2 translate = Vector2.Zero;
				game.KeyUp += delegate(object sender, KeyboardKeyEventArgs args) {
					switch (args.Key) {
						case Key.Escape:
							game.Exit();
							break;
						case Key.R:
							zoom = 1;
							break;
						case Key.W:
							if (wDown)
								translate += new Vector2(1f, 1f);
							wDown = false;
							break;
						case Key.A:
							if (aDown)
								translate += new Vector2(1f, -1f);
							aDown = false;
							break;
						case Key.S:
							if (sDown)
								translate += new Vector2(-1f, -1f);
							sDown = false;
							break;
						case Key.D:
							if (dDown)
								translate += new Vector2(-1f, 1f);
							dDown = false;
							break;
					}
				};

				double time=0, sin = 0;

				game.UpdateFrame +=
					delegate(object sender, FrameEventArgs e) {
						time += e.Time;
						sin = (Math.Sin(time/4) + 1) / 2;
						game.Title = $"Heart of Gold - {game.RenderFrequency:000.00}fps - {game.UpdateFrequency:000.00}tps";
					};

				var items = new List<BufferElement>(size * size * 12);
				Console.WriteLine("Prepping buffer elements...");
				//First half
				var side = matrix.GetLength(0);
				var half = side / 2;
				for (var i = 0; i < side; i++) {
					Console.Write($"\rCreating row {i,4} of {side}");
					int x = i, y = 0;
					while (x >= 0) {
						var hasleft = y != side - 1;
						var hasright = x != side - 1;
						var left = hasleft ? (double?)matrix[x, y + 1] : -2;
						var right = hasright ? (double?)matrix[x + 1, y] : -2;
						items.AddRange(AddOne(matrix[x, y], x - half, y - half, cmatrix[x--, y++], left, right));
					}
				}
				// Pt 2
				for (var i = 1; i <= side - 1; i++) {
					Console.Write($"\rCreating column {i,4} of {side}");
					int x = side - 1, y = i;
					while (y < side) {
						var hasleft = y != side - 1; var hasright = x != side - 1;
						var left = hasleft ? (double?)matrix[x, y + 1] : -2;
						var right = hasright ? (double?)matrix[x + 1, y] : -2;
						items.AddRange(AddOne(matrix[x, y], x - half, y - half, cmatrix[x--, y++], left, right));
					}
				}
				Console.WriteLine("\rCreating vertex buffer object...           ");
				Action a = delegate {
					GL.EnableClientState(ArrayCap.VertexArray);
					GL.EnableClientState(ArrayCap.ColorArray);
					GL.VertexPointer(3, VertexPointerType.Float, BufferElement.SizeInBytes, new IntPtr(0));
					GL.ColorPointer(3, ColorPointerType.Float, BufferElement.SizeInBytes, new IntPtr(Vector3.SizeInBytes));
				};
				var terrain = new VertexBuffer<BufferElement>(items.ToArray(), a, BufferUsageHint.StaticDraw);
				Console.WriteLine("Done!");
				game.RenderFrame += delegate {
					// render graphics
					GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
					GL.MatrixMode(MatrixMode.Projection);
					GL.LoadIdentity();

					GL.Ortho(size, -size, size, -size, -double.MaxValue, double.MaxValue);

					GL.Scale(1*zoom, (game.Width/(double) game.Height)*zoom, 1*zoom);
					GL.Rotate(90*sin, 1, 0, 0);
					GL.Rotate(45, 0, 0, 1);
					GL.Translate(translate.X, translate.Y, -matrix[(int) -translate.X + half, (int) -translate.Y + half]);

					terrain.Render(PrimitiveType.Quads);

					//GL.Begin(PrimitiveType.LineLoop);

					//DrawOne(matrix[(int) -translate.X + half, (int) -translate.Y + half], (int) -translate.X, (int) -translate.Y,
					//	Color.Black);
					//GL.End();

					game.SwapBuffers();
				};
				game.WindowState = WindowState.Maximized;
				game.Run(60.0, 60);
			}
		}
Ejemplo n.º 14
0
        public void Main()
        {
            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    game.VSync = VSyncMode.On;
                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                };

                game.RenderFrame += (sender, e) =>
                {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(-1000.0, 1000.0, -1000.0, 1000.0, 0.0, 2000.0);

                    GL.Translate(x, y, 0); // position triangle according to our x variable

                    //GL.Color3(Color.MidnightBlue);
                    //GL.Vertex2(-1.0f, 1.0f);
                    //GL.Color3(Color.SpringGreen);
                    //GL.Vertex2(0.0f, -1.0f);
                    //GL.Color3(Color.Ivory);
                    //GL.Vertex2(1.0f, 1.0f);


                    framenr++;
                    System.Diagnostics.Trace.WriteLine("RenderFrame " + framenr.ToString());
                    DrawStars();

                    game.SwapBuffers();
                };

                // Run the game at 30 updates per second
                game.Run(30.0);
            }
        }
Ejemplo n.º 15
0
        public static void Main()
        {
            System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr) (System.Environment.ProcessorCount); //Assign the process to the last CPU-core of the System
            Console.WriteLine("We have " + System.Environment.ProcessorCount + " CPU-Cores.");
            Random rnd = new Random();
            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                {
                    // setup settings, load textures, sounds
                    FormWindow();
                    game.X = 32;
                    game.Y = 16;
                    game.VSync = VSyncMode.On;
                    game.Width = windowX;
                    game.Height = windowY;
                    game.WindowBorder = WindowBorder.Fixed; //Disables the resizable windowframe
                    GL.Enable(EnableCap.Blend);                                                     //These lines
                    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);  //enable transparency using alpha-channel

                    //////////////////////////////////////////////////////////////////////////////////////////////// Load all Background-Objects from the Folder
                    int i = 0;
                    foreach (string bmpFile in Directory.GetFiles((exePath + @"\gfx\backgrounds\tiles"), "*.bmp"))  //get all background tiles and load them
                    {
                        Texture.bgTilesArray[i, 0] = MyImage.LoadTexture(bmpFile);
                        string framesCount = (bmpFile.Replace((exePath + @"\gfx\backgrounds\tiles\"), "").Substring(4, 2));   //get Animation FrameCount ( "<id><id><id>_<frameCount><frameCount>.bmp")
                        if (!int.TryParse(framesCount, out Texture.bgTilesArray[i, 1]))
                            Texture.bgTilesArray[i, 1] = 1;
                        i++;
                    }
                    foreach (string bmpFile in Directory.GetFiles((exePath + @"\gfx\backgrounds\tiles"), "*.png"))  //get all background tiles and load them
                    {
                        Texture.bgTilesArray[i, 0] = MyImage.LoadTexture(bmpFile);
                        string framesCount = (bmpFile.Replace((exePath + @"\gfx\backgrounds\tiles\"), "").Substring(4, 2));   //get Animation FrameCount ( "<id><id><id>_<frameCount><frameCount>.bmp")
                        if (!int.TryParse(framesCount, out Texture.bgTilesArray[i, 1]))
                            Texture.bgTilesArray[i, 1] = 1;
                        i++;
                    }
                    ////////////////////////////////////////////////////////////////////////////////////////////////

                };

                //string s = "---4";
                //Console.WriteLine("3" + s[3]);
                //Console.ReadKey();

                Map karte = new Map(16);

                game.Resize += (sender, e) =>
                {
                    //sceneX = game.Height;
                    //sceneY = game.Width;

                    GL.Viewport(0, 0, windowX, windowY);  //unZoomed

                };
                var mouse = Mouse.GetState();
                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    mouse = Mouse.GetState();

                    keyboard = Keyboard.GetState();

                    if (keyboard[Key.Escape])
                    {
                        game.Exit();
                    }

                    game.Title = (("FPS: " + (int)(game.RenderFrequency) +" ; "+ Math.Round(game.RenderTime*1000,2)+"ms/frame  Zoom="+zoom));

                    Map.fpsLine.Insert(0,(int)game.RenderFrequency);
                    while (Map.fpsLine.Count > 230)
                        Map.fpsLine.RemoveAt(Map.fpsLine.Count - 1);

                };

                game.RenderFrame += (sender, e) =>
                {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                    //GL.Scale(Map.temp, Map.temp, 0);
                    GL.MatrixMode(MatrixMode.Projection);
                    //GL.MatrixMode(MatrixMode.Modelview);
                    GL.LoadIdentity();

                    //GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                    //Console.WriteLine("Cam (X:" + camX + " |Y:" + camY + ")");

                    GL.Viewport((int)(0), (int)(0), windowX, windowY);
                    GL.LineWidth(1.0f);
                    game.Width = windowX;
                    game.Height = windowY;
                    Vector2d mouseVector = new Vector2d(game.Mouse.X, game.Mouse.Y);

                    if (zoomed)
                    {
                        GL.Ortho((int)(-sceneX / 2), (int)(sceneX / 2), (int)(sceneY / 2), (int)(-sceneY / 2), -1000, 1000);  //Render  distant objects smaller
                        GL.MatrixMode(MatrixMode.Modelview);

                        GL.PopMatrix();
                        GL.PushMatrix();
                        zoom = Map.temp;

                        GL.Scale(zoom, zoom, 1);        //glZomm the scene
                        GL.Translate(-camX, -camY, 0);  //glTranslate (add offset) the zoomed scene

                        GL.Vertex2(mouseVector.X, mouseVector.Y);

                        mouseVector.X -= (sceneX / 2);// + camX;
                        mouseVector.Y -= (sceneY / 2);// + camY;

                        mouseVector.X /= zoom * 2*(1.6);
                        mouseVector.Y /= zoom * 2*(0.9);
                    }
                    else
                    {
                        GL.Ortho((int)0, (int)windowX, (int)windowY, (int)0, -1000, 1000);  //Render  distant objects smaller
                        GL.MatrixMode(MatrixMode.Modelview);
                        GL.PopMatrix();
                        GL.PushMatrix();
                    }

                    karte.draw();    ///////////////////////////////////////// MAP-Object
                    karte.process((int)(mouseVector.X), (int)(mouseVector.Y));

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(199.0);
            }
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            using (var game = new GameWindow())
            {
                game.Load += (sender, e) =>
                    {
                        game.VSync = VSyncMode.On;
                    };
                game.Resize += (sender, e) =>
                    {
                        GL.Viewport(0, 0, game.Width, game.Height);
                    };
                game.UpdateFrame += (sender, e) =>
                    {
                        if (game.Keyboard[Key.Escape])
                        {
                            game.Exit();
                        }
                    };
                game.RenderFrame += (sender, e) =>
                    {
                        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                        GL.MatrixMode(MatrixMode.Projection);
                        GL.LoadIdentity();
                        GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);
                        GL.Begin(PrimitiveType.LineLoop);
                        GL.Color3(Color.Red);
                        GL.Vertex2(0.0f, -0.03f);
                        GL.Vertex2(0.02f, -0.03f);
                        GL.Vertex2(0.04f, 0.0f);
                        GL.Vertex2(0.01f, 0.04f);
                        GL.Vertex2(0.02f, 0.4f);
                        GL.Vertex2(0.6f, 0.9f);
                        GL.Vertex2(0.6f, 0.7f);
                        GL.Vertex2(0.2f, 0.35f);
                        GL.Vertex2(0.22f, 0.30f);
                        GL.Vertex2(0.6f, 0.6f);
                        GL.Vertex2(0.6f, 0.4f);
                        GL.Vertex2(0.3f, 0.15f);
                        GL.Vertex2(0.32f, 0.10f);
                        GL.Vertex2(0.6f, 0.3f);
                        GL.Vertex2(0.6f, 0.15f);
                        GL.Vertex2(0.3f, -0.07f);
                        GL.Vertex2(0.3f, -0.9f);
                        GL.Vertex2(0.28f, -0.9f);
                        GL.Vertex2(0.0f, -0.3f);
                        GL.Vertex2(-0.0f, -0.3f);
                        GL.Vertex2(-0.28f, -0.9f);
                        GL.Vertex2(-0.3f, -0.9f);
                        GL.Vertex2(-0.3f, -0.07f);
                        GL.Vertex2(-0.6f, 0.15f);
                        GL.Vertex2(-0.6f, 0.3f);
                        GL.Vertex2(-0.32f, 0.10f);
                        GL.Vertex2(-0.3f, 0.15f);
                        GL.Vertex2(-0.6f, 0.4f);
                        GL.Vertex2(-0.6f, 0.6f);
                        GL.Vertex2(-0.22f, 0.30f);
                        GL.Vertex2(-0.2f, 0.35f);
                        GL.Vertex2(-0.6f, 0.7f);
                        GL.Vertex2(-0.6f, 0.9f);
                        GL.Vertex2(-0.02f, 0.4f);
                        GL.Vertex2(-0.01f, 0.04f);
                        GL.Vertex2(-0.04f, 0.0f);
                        GL.Vertex2(-0.02f, -0.03f);
                        GL.Vertex2(-0.0f, -0.03f);
                        GL.End();

                        game.SwapBuffers();
                    };

                game.Run(60.0);
            }
        }
Ejemplo n.º 17
0
        private void Task1Btn_Click(object sender, RoutedEventArgs e)
        {
            double baseSpeed = 1, speedUp = 1.2, slowness = 0.95, maxSpeed = 40;
            double xOffset = 0, yOffset = 0, xSpeed = 0, ySpeed = 0;

            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width = visualWindow.Height = 400;
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }

                    GL.MatrixMode(MatrixMode.Modelview);

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up) || keyboardState.IsKeyDown(OpenTK.Input.Key.W))
                    {
                        ySpeed = baseSpeed + ySpeed * (ySpeed > 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down) || keyboardState.IsKeyDown(OpenTK.Input.Key.S))
                    {
                        ySpeed = -baseSpeed + ySpeed * (ySpeed < 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left) || keyboardState.IsKeyDown(OpenTK.Input.Key.A))
                    {
                        xSpeed = -baseSpeed + xSpeed * (xSpeed < 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right) || keyboardState.IsKeyDown(OpenTK.Input.Key.D))
                    {
                        xSpeed = baseSpeed + xSpeed * (xSpeed > 0 ? speedUp : 0);
                    }

                    // Max speed controll
                    xSpeed = Math.Abs(xSpeed) < maxSpeed ? xSpeed : maxSpeed * (xSpeed < 0 ? -1 : 1);
                    ySpeed = Math.Abs(ySpeed) < maxSpeed ? ySpeed : maxSpeed * (ySpeed < 0 ? -1 : 1);

                    // Small speed aprox to 0
                    if (Math.Abs(xSpeed) < 1)
                    {
                        xSpeed = 0;
                    }
                    if (Math.Abs(ySpeed) < 1)
                    {
                        ySpeed = 0;
                    }

                    // Auto slow speed
                    xSpeed *= slowness;
                    ySpeed *= slowness;

                    xOffset += xSpeed;
                    yOffset += ySpeed;
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = -1000,
                          right = 1000,
                          down  = -1000,
                          up    = 1000;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);


                    GL.Begin(BeginMode.Lines);
                    GL.Vertex2(left, 0);
                    GL.Vertex2(right, 0);
                    GL.Vertex2(0, up);
                    GL.Vertex2(0, down);
                    GL.End();

                    GL.PushMatrix();
                    GL.Translate(xOffset, yOffset, 0);

                    GL.Begin(BeginMode.Quads);

                    GL.Color3(1.0, 1.0, 1.0);
                    GL.Vertex2(250, 450);
                    GL.Color3(0.0, 0.0, 1.0);
                    GL.Vertex2(250, 150);
                    GL.Color3(0.0, 1.0, 0.0);
                    GL.Vertex2(550, 150);
                    GL.Color3(1.0, 0.0, 0.0);
                    GL.Vertex2(550, 450);

                    GL.End();

                    GL.PopMatrix();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
Ejemplo n.º 18
0
        private void Task2Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                double angle = 0, selfAngle = 0, xOffset = 0, yOffset = 0, scale = 1;
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width  = 600;
                    visualWindow.Height = 200;
                    visualWindow.VSync  = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }

                    GL.MatrixMode(MatrixMode.Modelview);

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up))
                    {
                        yOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down))
                    {
                        yOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left))
                    {
                        xOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right))
                    {
                        xOffset += 10;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Plus))
                    {
                        scale += 0.1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Minus))
                    {
                        scale -= 0.1;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Home))
                    {
                        angle += 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.End))
                    {
                        angle -= 5;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Q))
                    {
                        selfAngle += 3;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.E))
                    {
                        selfAngle -= 3;
                    }
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = 0,
                          right = 300,
                          down  = 0,
                          up    = 100;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    // Translations
                    GL.Translate(xOffset, yOffset, 0);
                    GL.Translate(150, 50, 0);
                    GL.Scale(scale, scale, 0);
                    GL.Rotate(angle, 0, 0, 1);
                    GL.Translate(-150, -50, 0);


                    GL.Color3(255.0, 0, 0);

                    // T
                    GL.PushMatrix();
                    GL.Translate(50, 50, 0);
                    GL.Rotate(selfAngle, 0, 0, 1);
                    GL.Translate(-50, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(10, 80);
                    GL.Vertex2(90, 80);
                    GL.Vertex2(90, 70);
                    GL.Vertex2(55, 70);
                    GL.Vertex2(55, 20);
                    GL.Vertex2(45, 20);
                    GL.Vertex2(45, 70);
                    GL.Vertex2(10, 70);
                    GL.End();

                    GL.PopMatrix();


                    // S
                    GL.PushMatrix();
                    GL.Translate(150, 50, 0);
                    GL.Rotate(-selfAngle, 0, 0, 1);
                    GL.Translate(-150, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(190, 80);
                    GL.Vertex2(110, 80);
                    GL.Vertex2(110, 45);
                    GL.Vertex2(180, 45);
                    GL.Vertex2(180, 30);
                    GL.Vertex2(110, 30);
                    GL.Vertex2(110, 20);
                    GL.Vertex2(190, 20);
                    GL.Vertex2(190, 55);
                    GL.Vertex2(120, 55);
                    GL.Vertex2(120, 70);
                    GL.Vertex2(190, 70);
                    GL.End();

                    GL.PopMatrix();

                    // I
                    GL.PushMatrix();
                    GL.Translate(250, 50, 0);
                    GL.Rotate(selfAngle, 0, 0, 1);
                    GL.Translate(-250, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(265, 80);
                    GL.Vertex2(265, 70);
                    GL.Vertex2(255, 70);
                    GL.Vertex2(255, 30);
                    GL.Vertex2(265, 30);
                    GL.Vertex2(265, 20);
                    GL.Vertex2(235, 20);
                    GL.Vertex2(235, 30);
                    GL.Vertex2(245, 30);
                    GL.Vertex2(245, 70);
                    GL.Vertex2(235, 70);
                    GL.Vertex2(235, 80);
                    GL.End();

                    GL.PopMatrix();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
Ejemplo n.º 19
0
		public static void Main (string[] args)
		{
			using (var game = new GameWindow ())
   			using (var ac = new AudioContext())
			{
//				var bag = new C5.TreeBag<IEffect> (new TimeToStartCutoffComparer ());
////				bag.Add (new SoundEffect{Id = 1, TimeToStart = 1.0f });
////				bag.Add (new SoundEffect{Id = 2, TimeToStart = 2.0f });
////				bag.Add (new SoundEffect{Id = 3, TimeToStart = 1.5f });
////				bag.Add (new SoundEffect{Id = 5, TimeToStart = 1.5f });
////				bag.Add (new SoundEffect{Id = 4, TimeToStart = 1.2f });
//
//				foreach (IEffect effect in bag.RangeTo(new SoundEffect{TimeToStart=1.5f}))
//				{
//					Console.WriteLine ("Effect {0} - {1}", effect.Id, effect.TimeToStart);
//				}
				//var audio = new SoundMachine(new [] {ac});
				//var scheduler = new EffectScheduler (new [] { audio }, 0f);
				 
				using (var fs = File.OpenRead ("01_Ghosts_I.flac"))
				using (var wav = new WaveOverFlacStream(fs, WaveOverFlacStreamMode.Decode))
				using (var ms = new MemoryStream())
				{
					wav.CopyTo(ms);

					if (wav.StreamInfo == null)
					{
						throw new InvalidDataException ("FLAC: Missing wav stream info");
					}
					else
					{
						var sound_data = ms.ToArray();

						int channels = wav.StreamInfo.ChannelsCount;
						int bits_per_sample = wav.StreamInfo.BitsPerSample;
						int sample_rate = wav.StreamInfo.SampleRate;

						var sound_format =
							channels == 1 && bits_per_sample == 8 ? ALFormat.Mono8 :
							channels == 1 && bits_per_sample == 16 ? ALFormat.Mono16 :
							channels == 2 && bits_per_sample == 8 ? ALFormat.Stereo8 :
							channels == 2 && bits_per_sample == 16 ? ALFormat.Stereo16 :
							(ALFormat)0; // unknown

						Console.WriteLine ("Seconds : {0}",((wav.StreamInfo.TotalSampleCount / sample_rate) + ((wav.StreamInfo.TotalSampleCount % sample_rate)/(sample_rate))) );

						int buffer = AL.GenBuffer ();
						AL.BufferData(buffer, sound_format, sound_data, sound_data.Length, sample_rate);
						ALError error_code = AL.GetError ();
						if (error_code != ALError.NoError)
						{
							// respond to load error etc.
							Console.WriteLine(error_code);
						}

						int source = AL.GenSource(); // gen 2 Source Handles

						AL.Source( source, ALSourcei.Buffer, buffer ); // attach the buffer to a source

						AL.SourcePlay(source); // start playback
						AL.Source( source, ALSourceb.Looping, false ); // source loops infinitely

					}
				}


				game.Load += (sender, e) =>
				{
					// setup settings, load textures, sounds
					game.VSync = VSyncMode.On;
				};

				game.Unload += (sender, e) => 
				{
				};

				game.KeyDown += (object sender, KeyboardKeyEventArgs e) => 
				{
					if (e.Key == Key.Space)
					{
						game.Exit();
					}
				};

				game.UpdateFrame += (sender, e) =>
				{
					// add game logic, input handling

					// update shader uniforms

					// update shader mesh
				};

				game.RenderFrame += (sender, e) =>
				{
					GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

					game.SwapBuffers();
				};

				game.Resize += (sender, e) =>
				{
					GL.Viewport(0, 0, game.Width, game.Height);
				};

				game.Run(60.0);
			}
		}
Ejemplo n.º 20
0
        [STAThread] //Single Threaded Appartment
        public static void Main()
        {
            Application game = new Application();   //Genereller Objektverweis. Hiermit kann auf nicht statische Objekte zugegriffen werden via game.example(x, y)

            //--------- Systemvariablen ----------//

            int cron = 0;   //Globale Steuervariable

            int Width = 0;
            int Height = 0;

            Point mousePos = new Point();
            var mouse = Mouse.GetState();
            bool globalClickLock = false;   //wenn ein Klick fortbesteht, so sperre via ClickLock, damit beim Drag auf einen Button dieser nicht aktiviert werden kann.

            var BGColor = new Color(); //Hintergrundfarbe       BGColor = Color.FromArgb(0, 128, 128, 128);

            var Border = WindowBorder.Hidden;   //Rahmen
            var Fullscreen = WindowState.Fullscreen; //Vollbildmodus

            Config config = new Config();

            int volumeMusic = config.getValue(1);
            int volumeEffects = config.getValue(2);

            foreach (DisplayIndex index in Enum.GetValues(typeof(DisplayIndex)))    //Nimm die derzeit besten Vollbildkoordinaten vom Primären Bildschirm
            {
                DisplayDevice device = DisplayDevice.GetDisplay(index);
                if (device == null)
                {
                    continue;
                }

                Width = device.Width;
                Height = device.Height;
            }

            //---------- Audios ----------// // Muss noch bearbeitet werden. Wahrscheinlich werden alle Daten in Wave-Instanzen gespeichert.


            SoundPlayer Sound = new SoundPlayer("sounds/Main.wav");

            //---------- Panels ----------//

            Panel pan_MenuBG = null;
            Panel pan_MenuEnd = null;
            Panel pan_MenuOpts = null;
            Panel pan_MenuNew = null;

            Panel pan_OptsBack = null;
            Panel lab_Music = null;
            Panel lab_Effects = null;
            HSlider hsl_VolumeMusic = null;
            HSlider hsl_VolumeEffects = null;
            //Panel pan_MenuTest = null;
            
            using (var app = new GameWindow())
            {
                app.Load += (sender, e) =>
                {
                    //Width = app.
                    //Height = app.Bounds.Y;

                    app.Title = "VenusBuggy";
                    app.Width = Width;
                    app.Height = Height;
                    app.WindowBorder = Border;
                    app.WindowState = Fullscreen;

                    pan_MenuBG = new Panel(0, 0, Width, Height, 0, "texturen/Menu/MenuBG_1920_1080.jpg");
                    pan_MenuEnd = new Panel(100, 100, 225, 44, -1, "texturen/Menu/MenuEnd0.bmp", "texturen/Menu/MenuEnd1.bmp");
                    pan_MenuOpts = new Panel(100, 160, 225, 44, 1, "texturen/Menu/MenuOpts0.bmp", "texturen/Menu/MenuOpts1.bmp");
                    pan_MenuNew = new Panel(100, 220, 225, 44, 10, "texturen/Menu/MenuNew0.bmp", "texturen/Menu/MenuNew1.bmp");

                    lab_Music = new Panel((int)(Width/2) - 300, (int)(Height/2) + 100, 225, 44, 0, "texturen/Menu/Music.bmp");
                    lab_Effects = new Panel((int)(Width / 2) - 300, (int)(Height / 2) + 40, 225, 44, 0, "texturen/Menu/Effects.bmp");

                    pan_OptsBack = new Panel((int)(Width / 2) - 300, (int)(Height / 2) -80, 225, 44, 2, "texturen/Menu/OptsBack0.bmp", "texturen/Menu/OptsBack1.bmp");

                    hsl_VolumeMusic = new HSlider(volumeMusic, (int)(Width / 2), (int)(Height / 2) + 100, 300, 5, 44,  11, 44, 13, 44, "texturen/Menu/SliderEnd.bmp", "texturen/Menu/SliderBar.bmp", "texturen/Menu/Slider0.bmp", "texturen/Menu/Slider1.bmp", "texturen/Menu/Slider2.bmp");
                    hsl_VolumeEffects = new HSlider(volumeEffects, (int)(Width / 2), (int)(Height / 2) + 40, 300, 5, 44, 11, 44, 13, 44, "texturen/Menu/SliderEnd.bmp", "texturen/Menu/SliderBar.bmp", "texturen/Menu/Slider0.bmp", "texturen/Menu/Slider1.bmp", "texturen/Menu/Slider2.bmp");

                    GL.Enable(EnableCap.Texture2D); //Texturierung aktivieren
                    GL.Enable(EnableCap.Blend); //Alpha-Kanäle aktivieren

                    

                    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                    //GL.Disable(EnableCap.DepthTest);

                    BGColor = Color.FromArgb(0, 128, 128, 128); //Die Standardfensterfarbe //Nur zur Sicherheit

                    app.VSync = VSyncMode.On;

                    Sound.Play();
                };

                app.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, app.Width, app.Height);
                };

                app.UpdateFrame += (sender, e) =>
                {
                    mousePos.X = app.Mouse.X;               //Aktualisiere Maus-Koordinaten
                    mousePos.Y = Height - app.Mouse.Y - 1;
                    mouse = Mouse.GetState();

                    //if (app.Keyboard[Key.Escape])
                    //{
                    //    app.Exit();
                    //}

                    switch (cron)
                    {
                        case (-1):
                            app.Exit();
                            break;
                        case 0:
                            //Console.WriteLine(mouse.GetType().ToString());
                            cron = pan_MenuEnd.clickCheck(mousePos.X, mousePos.Y, mouse, cron, globalClickLock);
                            cron = pan_MenuOpts.clickCheck(mousePos.X, mousePos.Y, mouse, cron, globalClickLock);
                            pan_MenuNew.clickCheck(mousePos.X, mousePos.Y, mouse, cron, globalClickLock);
                            break;
                        case 1:
                            cron = pan_OptsBack.clickCheck(mousePos.X, mousePos.Y, mouse, cron, globalClickLock);

                            if (!hsl_VolumeEffects.clickLock)
                            {
                                volumeMusic = hsl_VolumeMusic.clickCheck(mousePos.X, mousePos.Y, mouse, volumeMusic);
                            }
                            if (!hsl_VolumeMusic.clickLock)
                            {
                                volumeEffects = hsl_VolumeEffects.clickCheck(mousePos.X, mousePos.Y, mouse, volumeEffects);
                            }
                            break;
                        case 2:
                            config.writeConfig(volumeMusic.ToString(), volumeEffects.ToString());
                            cron = 0;
                            break;
                    }

                    globalClickLock = (mouse[MouseButton.Left]);    //Überprüft, ob die Maustaste gehalten wird


                };

                app.RenderFrame += (sender, e) =>
                {
                    //Console.WriteLine(mousePos.X);
                    //Console.WriteLine(mousePos.Y);


                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(0, app.Width, 0, app.Height, 0.0, 4.0);  //Nullpunkt ist unten links!

                    GL.ClearColor(BGColor);

                    switch (cron)
                    {
                        case 0: // 0 = Du befindest dich derzeit im Hauptmenü oberster Ebene

                            pan_MenuBG.draw();
                            pan_MenuEnd.draw();
                            pan_MenuOpts.draw();
                            pan_MenuNew.draw();
                            break;
                        case 1:
                            pan_MenuBG.draw();
                            pan_OptsBack.draw();
                            lab_Music.draw();
                            lab_Effects.draw();
                            hsl_VolumeMusic.draw();
                            hsl_VolumeEffects.draw();



                            //Console.WriteLine(volumeMusic);
                            //Console.WriteLine(volumeEffects);
                            break;
                    }

                    app.SwapBuffers();
                };

                app.Run(60.0);  //Updatefrequenz - Drawing wird notfalls übersprungen
            }
        }
        static void Main()
        {
            int mouseX = 0;
            int mouseY = 0;

            Dictionary<BrickTypeEnum, int> brickTextures = new Dictionary<BrickTypeEnum,int>();

            using (var w = new GameWindow(640, 480))
            {
                w.CursorVisible = false;

                w.RenderFrame += (o, e) => {
                    GL.ClearColor(Color.Gray);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    CogitaGameEntities.CogitaGameInstance.Instance.Player.Camera.UseCamera();

                    //GL.ClientActiveTexture(TextureUnit.Texture0);

                    foreach (var bt in Enum.GetValues(typeof(BrickTypeEnum)))
                    {
                        GL.Enable(EnableCap.Texture2D);
                        GL.BindTexture(TextureTarget.Texture2D, brickTextures[(BrickTypeEnum)bt]);
                        //Debug.Assert(GL.GetError() == ErrorCode.NoError);
                        CogitaGameEntities.CogitaGameInstance.Instance.MapCursor.Draw((BrickTypeEnum)bt);

                        GL.BindTexture(TextureTarget.Texture2D,0);
                        //Debug.Assert(GL.GetError() == ErrorCode.NoError);
                        GL.Disable(EnableCap.Texture2D);

                    }

                    w.SwapBuffers();

                };

                w.UpdateFrame += (o, e) => {
                    CogitaGameEntities.CogitaGameInstance.Instance.MapCursor.Update();
                    CogitaTerrainObjects.EventPumps.UIThreadEventPump.Instance.DoWork();
                    CogitaGameEntities.CogitaGameInstance.Instance.DoPhysics(Math.Max(e.Time,0.01));

                    var gi = CogitaGameEntities.CogitaGameInstance.Instance;
                    var player = gi.Player;

                    ProcessKeyPresses(w, player);

                    if (w.Keyboard[OpenTK.Input.Key.Escape])
                        w.Exit();

                    var mState = OpenTK.Input.Mouse.GetState();
                    var mdx = mState.X - mouseX;
                    var mdy = mState.Y - mouseY;

                    mouseX = mState.X;
                    mouseY = mState.Y;

                    player.Pitch += ((double)mdy / 200.0);
                    player.Yaw += ((double)mdx / 200.0);
                };

                w.Load += (o, e) =>
                {
                    foreach (var bt in Enum.GetValues(typeof(BrickTypeEnum)))
                    {
                      brickTextures[(BrickTypeEnum)bt] = Util.GenTexture(string.Format("../res/{0}.png",bt.ToString()));
                    }
                };

                w.Run();
            }
        }
Ejemplo n.º 22
0
        public static void Main()
        {
            using (game = new GameWindow()) {

                game.Load += (sender, e) => {
                    // setup settings, load textures, sounds
                    game.VSync = VSyncMode.On;

                    GL.ClearColor(Color.MidnightBlue);
                    GL.Enable(EnableCap.Texture2D);

                    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

                    GL.GenTextures(1, out texture);
                    GL.BindTexture(TextureTarget.Texture2D, texture);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

                    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                        ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
                        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

                    bitmap.UnlockBits(data);

                };

                game.Resize += (sender, e) => {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) => {
                    // add game logic, input handling
                    if (game.Keyboard[Key.Escape]) {
                        game.Exit();
                    }
                };

                game.RenderFrame += (sender, e) => {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0);

                    GL.Clear(ClearBufferMask.ColorBufferBit);

                    GL.MatrixMode(MatrixMode.Modelview);
                    GL.LoadIdentity();

                    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                    GL.Enable(EnableCap.Blend);
                    GL.BindTexture(TextureTarget.Texture2D, texture);
                    GL.Begin(PrimitiveType.Quads);

                    var Map = ResourceManager.Map;

                    for (int iy = 0; iy < Map.Height; iy++) {
                        int dX = iy % 2 == 0 ? 0 : Map.TileWidth / 2;
                        for (int ix = 0; ix < Map.Width; ix++) {
                            DrawTile(dX + ix * Map.TileWidth, iy * Map.HexSideLength.Value, Map.TileWidth, Map.TileHeight, ResourceManager.GetTile(ix, iy, 0).Gid);
                        }
                    }

                    GL.End();

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Game.ClientSize = new Size(1280, 720);

            //load textures
            TextureManager.LoadTexture("face", "./Assets/face.tif");
            TextureManager.LoadTexture("face_alpha", "./Assets/face_alpha.tif");

            //create state system
            System.AddState("splash", new SplashScreenState(System));
            System.AddState("title_menu", new TitleScreenState());
            System.AddState("sprite_test", new DrawSpriteState(TextureManager));
            System.AddState("test_sprite_class", new TestSpriteClassState(TextureManager));

            //set init state
            System.ChangeState("test_sprite_class");

            //set up events
            Game.Load += (sender, e) =>
            {
                Game.VSync = VSyncMode.On;
            };
            Setup2D(Game.Width, Game.Height);

            Game.Resize += (sender, e) =>
            {
                GL.Viewport(0, 0, Game.Width, Game.Height);
                Setup2D(Game.Width, Game.Height);
            };

            Game.UpdateFrame += (sender, e) =>
            {
                // add game logic, input handling
                if (Game.Keyboard[Key.Escape])
                {
                    Game.Exit();
                }
                if (Game.Keyboard[Key.AltRight] && Game.Keyboard[Key.Enter])
                {
                    if (Game.WindowState == WindowState.Normal)
                    {
                        Game.WindowState = WindowState.Fullscreen;
                    }
                    else
                    {
                        Game.WindowState = WindowState.Normal;
                    }
                }

                System.Update(e.Time);
            };

            Game.RenderFrame += (sender, e) =>
            {
                System.Render();
                Game.SwapBuffers();
            };

            // Run the game at 60 updates per second
            Game.Run(60.0);
            Game.Dispose();
        }
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            // set starting stage
            stageNumber = 0;

            randomator = new Random();
            explosions = new List<Explosion>();

            //// build ships
            //
            ships = new List<ShipDrone>();

            // build secondary ship
            ShipDrone otherShip = new ShipDrone(VEL, ACC, ROT_VEL, ROT_ACC, SHIP_RADIUS, S_HEALTH, S_LIVES);
            otherShip.SetProjectile(PROJECTILE_ROF, PROJECTILE_VEL, PROJECTILE_RADIUS, PROJECTILE_MASS, PROJECTILE_DAMAGE);
            otherShip.Color = new byte[] { 255, 255, 255 };
            otherShip.ProjectileColor = new byte[] { 170, 170, 255 };
            otherShip.Id = 0;
            otherShip.SetShip(S0_START_X, S0_START_Y, S0_START_R);

            ships.Add(otherShip);

            // build main ship
            ShipDrone mainShip = new ShipDrone(VEL, ACC, ROT_VEL, ROT_ACC, SHIP_RADIUS, S_HEALTH, S_LIVES);
            mainShip.SetProjectile(PROJECTILE_ROF, PROJECTILE_VEL, PROJECTILE_RADIUS, PROJECTILE_MASS, PROJECTILE_DAMAGE);
            mainShip.Color = new byte[] { 255, 255, 255 };
            mainShip.ProjectileColor = new byte[] { 255, 255, 0 };
            mainShip.Id = 1;
            myShipID = mainShip.Id;
            mainShip.SetShip(S1_START_X, S1_START_Y, S1_START_R);

            ships.Add(mainShip);

            //// connect to server
            //
            connectedToServer = false;
            tcpConnection = new ClientTCP();

            try
            {
                if (args.Length < 1)
                {
                    tcpConnection.ConnectToServer(SERVER_IP_ADDRESS, SERVER_PORT);
                    Console.WriteLine("Connected to server at: " + SERVER_IP_ADDRESS + ":" + SERVER_PORT);
                }
                else
                {
                    tcpConnection.ConnectToServer(args[0], SERVER_PORT);
                    Console.WriteLine("Connected to server at: " + args[0] + ":" + SERVER_PORT);
                }
                connectedToServer = true;
                new GraphicsWindow(tcpConnection);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to connect to server: \n" + e.ToString());
            }

            // send main ship information to server
            if(connectedToServer)
            {
                float[] shipSpecs = mainShip.RenderShip();
                tcpConnection.SendMessage("Join: DRONE x: " + shipSpecs[0] + " y: " + shipSpecs[1] + " r: " + shipSpecs[2] + "\n");
            }

            //// Main
            //
            using (var game = new GameWindow((int)(1600 / 1.25), (int)(1000 / 1.25)))
            {
                game.Load += (sender, e) =>
                {
                    game.VSync = VSyncMode.On;
                    // determine map size
                    mapWidth = TILE_SIZE * TILE_COUNT_WIDTH;
                    mapHeight = TILE_SIZE * TILE_COUNT_HEIGHT;

                    Console.WriteLine("Game started at: " + game.Width + "x" + game.Height + "on a " + mapWidth + "x" + mapHeight + " map.");

                    // collision detection grid
                    collisionGrid = new byte[TILE_COUNT_WIDTH + 1, TILE_COUNT_HEIGHT + 1][];

                    // set up star field
                    starField = CreateStarField(mapWidth, mapHeight, 1000, mapWidth * 2, mapWidth / 2);

                    ////  Graphics
                    //

                    // make background color the color of null space
                    GL.ClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Set background color to black and opaque

                    // load textures
                    droneShipTex = LoadTexture("t_drone_ship1_shadow.png");
                    explosionTex = LoadTexture("t_explosion1.png");
                    carrierShipTex = LoadTexture("t_carrier_ship1.png");
                    starTex = LoadTexture("t_star1.png");
                    carrierShipUpperTex = LoadTexture("t_carrier_ship1_upper.png");
                    carrierShipLowerTex = LoadTexture("t_carrier_ship1_lower.png");
                    number1Tex = LoadTexture("t_1.png");
                    number2Tex = LoadTexture("t_2.png");
                    number3Tex = LoadTexture("t_3.png");
                    loseTex = LoadTexture("t_lose.png");
                    winTex = LoadTexture("t_win.png");
                    droneShip2Tex = LoadTexture("t_drone_ship2_shadow.png");
                    carrierShip2Tex = LoadTexture("t_carrier_ship2.png");
                    carrierShip2UpperTex = LoadTexture("t_carrier_ship2_upper.png");
                    carrierShip2LowerTex = LoadTexture("t_carrier_ship2_lower.png");
                    waitingTex = LoadTexture("t_waiting.png");

                    countdown = new Countdown(new int[] { number3Tex, number2Tex, number1Tex }, 160, 160); // 160 is dimension of number-pngs in pixels

                    GL.Enable(EnableCap.Texture2D);

                    // enable transparency

                    // ready the text
                    text = new TextRender(new Size(game.Width, game.Height), new Size(300, 100),  new Font(FontFamily.GenericMonospace, 15.0f));
                    text.AddLine("HEALTH " + (int) ((ships[myShipID].Health * 100) / S_HEALTH) + "%", new PointF(10, 10), new SolidBrush(Color.Red));
                    text.AddLine("LIVES " + ships[myShipID].Lives, new PointF(10, 40), new SolidBrush(Color.Red));

                    GL.Enable(EnableCap.Blend);
                    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                   // GL.Disable(EnableCap.DepthTest);
                };

                //// Game resize?
                //
                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                //// Physics recalculation and keyboard updates
                //
                game.UpdateFrame += (sender, e) =>
                {
                    // collision detection grid
                    collisionGrid = new byte[TILE_COUNT_WIDTH + 1, TILE_COUNT_HEIGHT + 1][];

                    if (game.Keyboard[Key.Escape])
                    {
                        if (connectedToServer)
                        {
                            connectedToServer = false;
                            tcpConnection.Shutdown();
                            tcpConnection = null;
                        }
                        game.Exit();
                    }
                    if (game.Keyboard[Key.Up])
                    {
                        if(stageNumber == 1)
                            ships[myShipID].ThrottleOn();
                    }
                    if (game.Keyboard[Key.Left])
                    {
                        if (!ships[myShipID].FreezeShipMovement && stageNumber == 1)
                            ships[myShipID].TurnLeft();
                    }
                    if (game.Keyboard[Key.Right])
                    {
                        if (!ships[myShipID].FreezeShipMovement && stageNumber == 1)
                            ships[myShipID].TurnRight();
                    }
                    if (game.Keyboard[Key.Enter])
                    {
                        if (!ships[myShipID].FreezeShipMovement && stageNumber == 1)
                            ships[myShipID].FireProjectile();
                        //ships[0].FireShotgun();
                    }

                    if (game.Keyboard[Key.W])
                    {
                        if(myShipID == 0)
                            ships[1].ThrottleOn();
                        else
                            ships[0].ThrottleOn();
                    }
                    if (game.Keyboard[Key.A])
                    {
                        if (myShipID == 0)
                            ships[1].TurnLeft();
                        else
                            ships[0].TurnLeft();
                    }
                    if (game.Keyboard[Key.D])
                    {
                        if (myShipID == 0)
                            ships[1].TurnRight();
                        else
                            ships[0].TurnRight();
                    }
                    if (game.Keyboard[Key.Space])
                    {
                        if (myShipID == 0)
                            ships[1].FireProjectile();
                        else
                            ships[0].FireProjectile();
                    }

                    if(connectedToServer)
                        mainShip.CalculatePhysics(mapWidth, mapHeight);
                    else
                        foreach (ShipDrone ship in ships)
                        {
                            ship.CalculatePhysics(mapWidth, mapHeight);
                        }

                    foreach (ShipDrone ship in ships)
                    {
                        // if the ship collides with another ship, sometimes they get stuck, have them separate one to
                        // allow them to get unstuck
                        ShipDrone collidedWith = CollisionTest(ship);
                        if (collidedWith != null)
                        {
                            ship.CalculatePhysics(mapWidth, mapHeight);
                            collidedWith.CalculatePhysics(mapWidth, mapHeight);
                        }
                    }

                    // determine if ship is ready to move after respawn
                    if (ships[myShipID].FreezeShipMovement)
                    {
                        float[] xy = ships[myShipID].GetShipPosition();
                        double distance = Math.Sqrt((xy[0] - ships[myShipID].StartingCoordinates[0]) * (xy[0] - ships[myShipID].StartingCoordinates[0]) + (xy[1] - ships[myShipID].StartingCoordinates[1]) * (xy[1] - ships[myShipID].StartingCoordinates[1]));

                        if (distance > DISTANCE_UNFREEZE)
                            ships[myShipID].FreezeShipMovement = false;

                    }

                    for (int i = 0; i < explosions.Count; i++)
                    {
                        if (!(explosions[i].CalculateStreams()))
                            explosions.RemoveAt(i);
                    }

                    // advance the countdown frame, start the game when ready.
                    if (stageNumber == 0)
                        if (countdown.OneFrame())
                            stageNumber = 1;

                    // tell server of updates.
                    // specifically of main ship's coordinates and projectiles
                    if(connectedToServer)
                    {
                        //Console.WriteLine("Sending...");

                        StringBuilder sb = new StringBuilder();
                        float[] shipSpecs = mainShip.RenderShip();
                        foreach(float[] projectileSpecs in mainShip.GetNewProjectiles())
                        {
                            // missing [3], [4], [5]
                            sb.Append(" P: " + projectileSpecs[0] + " " + projectileSpecs[1] + " " + projectileSpecs[2]);
                        }
                        mainShip.ClearNewProjectiles();
                        tcpConnection.SendMessage("Update: DRONE x: " + shipSpecs[0] + " y: " + shipSpecs[1] + " r: " + shipSpecs[2] + sb.ToString() + "\n");
                    }
                };

                //// Render game
                //
                game.RenderFrame += (sender, e) =>
                {

                    // always begins with GL.Clear() and ends with a call to SwapBuffers
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    // game window follows the ship
                    float[] shipCoord = ships[myShipID].RenderShip();
                    GL.Ortho(shipCoord[0] - game.Width / 2, shipCoord[0] + game.Width / 2, shipCoord[1] - game.Height / 2, shipCoord[1] + game.Height / 2, -1.0, 0.0);
                    //GL.Ortho(0, game.Width, 0, game.Height, -1.0, 0.0);
                    GL.MatrixMode(MatrixMode.Modelview);

                    //text.Draw();

                    RenderBackground(mapWidth, mapHeight);

                    foreach (ShipDrone ship in ships)
                    {
                        if (ship.FreezeShipMovement)
                        {
                            //// The main drone ship should be wedged between the top part of the carrier and the carrier's bay
                            //
                            RenderCarrierShip("lower", ship);
                            RenderParticles(ship.RenderShipParticles());
                            RenderDroneShip(ship.Color, ship);
                            RenderCarrierShip("upper", ship);
                        }
                        else
                        {
                            RenderCarrierShip(ship);
                        }
                    }

                    foreach (ShipDrone ship in ships)
                    {
                        // do not render drone ship if in carrier.  Previously rendered.
                        if (!ship.FreezeShipMovement)
                            RenderParticles(ship.RenderShipParticles());
                    }

                    foreach (ShipDrone ship in ships)
                    {
                        RenderProjectiles(ship.ProjectileColor, ship);
                        // do not render drone ship if in carrier.  Previously rendered.
                        if (!ship.FreezeShipMovement)
                            RenderDroneShip(ship.Color, ship);
                    }

                    /*if (ships[myShipID].FreezeShipMovement)
                    {
                        //                    RenderCollisionGrid();

                        //// The main drone ship should be wedged between the top part of the carrier and the carrier's bay
                        //
                        RenderCarrierShip("lower", ships[0]);
                        RenderParticles(ships[myShipID].RenderShipParticles());
                        RenderDroneShip(ships[myShipID].Color, ships[myShipID]);
                        RenderCarrierShip("upper", ships[0]);

                        foreach (ShipDrone ship in ships)
                        {
                            // do not render player's drone ship's exhaust particles, rendered previously
                            if (ship.Id != myShipID)
                                RenderParticles(ship.RenderShipParticles());
                            RenderParticles(ship.RenderProjectileParticles());
                        }

                        foreach (ShipDrone ship in ships)
                        {
                            RenderProjectiles(ship.ProjectileColor, ship);
                            // do not render player's drone ship, rendered previously
                            if (ship.Id != myShipID)
                                RenderDroneShip(ship.Color, ship);
                        }

                    }
                    else
                    {

                        RenderCarrierShip(ships[0]);
                        //                    RenderCollisionGrid();

                        foreach (ShipDrone ship in ships)
                        {
                            RenderParticles(ship.RenderShipParticles());
                            RenderParticles(ship.RenderProjectileParticles());
                        }

                        foreach (ShipDrone ship in ships)
                        {
                            RenderProjectiles(ship.ProjectileColor, ship);
                            RenderDroneShip(ship.Color, ship);
                        }
                    }
                    */
                    foreach (Explosion explosion in explosions)
                    {
                        RenderParticles(explosion.RenderParticles());
                        RenderExplosion(explosion.Color, explosion);
                    }

                    // render text, anything drawn after text will be in relation to the screen and not the game grid
                    text.Draw();

                    if (stageNumber == 0)
                        RenderCountdown(game.Width, game.Height);

                    if (stageNumber == 2)
                        RenderEndScreen(game.Width, game.Height);

                    game.SwapBuffers(); // draw the new matrix

                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 25
0
        private void Task1Btn_Click(object sender, RoutedEventArgs e)
        {
            double xOffset = 0, yOffset = 0, zOffset = 0,
                   scale = 1, xRotate = 0, yRotate = 0, zRotate = 0;
            bool perspectiveMode = false;
            int  teaPotMode      = 1;

            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width = visualWindow.Height = 400;
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up))
                    {
                        yOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down))
                    {
                        yOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right))
                    {
                        xOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left))
                    {
                        xOffset -= 10;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Plus))
                    {
                        scale += 0.1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Minus))
                    {
                        scale -= 0.1;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Home))
                    {
                        xRotate -= 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.End))
                    {
                        yRotate -= 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Delete))
                    {
                        zRotate -= 5;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.PageUp))
                    {
                        xRotate += 5;
                        yRotate += 5;
                        zRotate += 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.PageDown))
                    {
                        xRotate -= 5;
                        yRotate -= 5;
                        zRotate -= 5;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.P))
                    {
                        perspectiveMode = true;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.O))
                    {
                        perspectiveMode = false;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F1))
                    {
                        teaPotMode = 1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F2))
                    {
                        teaPotMode = 2;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F3))
                    {
                        teaPotMode = 3;
                    }
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left    = -1000,
                          right   = 1000,
                          down    = -1000,
                          up      = 1000,
                          forward = -1000,
                          back    = 1000;

                    float width  = right - left,
                          height = up - down,
                          depth  = back - forward;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();

                    if (perspectiveMode)
                    {
                        // GLU Perspective
                        Matrix4 perspectiveMatrix = Matrix4.CreatePerspectiveFieldOfView(
                            MathHelper.PiOver2,
                            width / height,
                            0.1f,
                            depth);
                        GL.LoadMatrix(ref perspectiveMatrix);
                        // GLU Look at
                        GL.Translate(0, 0, forward);
                    }
                    else
                    {
                        GL.Ortho(left, right, down, up, forward, back);
                    }

                    // Draw Axis
                    GL.Color3(255d, 0d, 0d);
                    GL.Begin(BeginMode.Lines);
                    GL.Vertex3(left, 0, 0);
                    GL.Vertex3(right, 0, 0);
                    GL.Vertex3(0, up, 0);
                    GL.Vertex3(0, down, 0);
                    GL.Vertex3(0, 0, forward);
                    GL.Vertex3(0, 0, back);
                    GL.End();

                    // Translations
                    GL.Translate(xOffset, yOffset, zOffset);
                    GL.Scale(scale, scale, scale);
                    GL.Rotate(xRotate, 1, 0, 0);
                    GL.Rotate(yRotate, 0, 1, 0);
                    GL.Rotate(zRotate, 0, 0, 1);


                    // Drawing
                    GL.Color3(0d, 0d, 0d);
                    switch (teaPotMode)
                    {
                    case 1:
                        Teapot.DrawWireTeapot(500);
                        break;

                    case 2:
                        Teapot.DrawSolidTeapot(500);
                        break;

                    case 3:
                        Teapot.DrawPointTeapot(500);
                        break;
                    }

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
Ejemplo n.º 26
0
        public static void Main(int resX, int resY)
        {

            Graphics.Sprite sprite = new Graphics.Sprite();
            Graphics.Mesh mesh = new Graphics.Mesh();
            using (var game = new GameWindow())
            {
                game.VSync = VSyncMode.On;
                game.Width = resX;
                game.Height = resY;
                
                game.Load += (sender, e) =>
                {
                    Console.WriteLine("Using OpenGL version: " + GL.GetString(StringName.Version));

                    
                    Graphics.TextureManager.LoadTexture("F:/DestWa/Pictures/artkleiner.png", "art");

                    // setup settings, load textures, sounds


                    sprite = new Graphics.Sprite("art", Vector3.Zero, Vector3.Zero, Vector3.One);
                    sprite.scale = new Vector3(1280, 720, 1);
                    sprite.position.X = 10;


                    mesh = Graphics.Mesh.CreateMeshFromOBJ("C:/Users/DestWa/Desktop/man.obj");
                    mesh.scale = new Vector3(1, 1, 1);
                    mesh.position.Z = 100;

                    GL.ClearColor(Color.Cornsilk);
                };

                game.Resize += (sender, e) =>
                {
                    GL.Viewport(0, 0, game.Width, game.Height);
                };

                game.UpdateFrame += (sender, e) =>
                {
                    // add game logic, input handling
                    if (game.Keyboard[Key.Escape])
                    {
                        game.Exit();
                    }
                };
                
                game.RenderFrame += (sender, e) =>
                {
                    // render graphics
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    Graphics.Renderer.DrawSprite(sprite);
                    //mesh.rotation.X += 0.01f;
                    //mesh.rotation.Y += 0.01f;

                    Graphics.Renderer.activeCamera.location.Z -= 0.1f;
                    Graphics.Renderer.DrawMesh(mesh);

                    game.SwapBuffers();
                };

                // Run the game at 60 updates per second
                game.Run(60.0);
            }
        }
Ejemplo n.º 27
0
    /// <summary>
    /// This procedure contains the user code. Input parameters are provided as regular arguments, 
    /// Output parameters as ref arguments. You don't have to assign output parameters, 
    /// they will have a default value.
    /// </summary>
    private void RunScript(Mesh Profile, Mesh x, bool y, ref object A)
    {
        if(y){
          try{
        using (var game = new GameWindow(Width, Height, GraphicsMode.Default))
        {
          game.Load += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.ClearColor(Color.Gray);// 背景
            OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.DepthTest);
            // OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.CullFace);//反面不可见
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Ambient, LightAmbient);//设置系统灯光
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Diffuse, LightDiffuse);		// 设置漫射光
            OpenTK.Graphics.OpenGL.GL.Light(OpenTK.Graphics.OpenGL.LightName.Light0,
              OpenTK.Graphics.OpenGL.LightParameter.Position, LightPosition);	// 设置光源位置
            OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Light0);//启用灯光

            // OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Texture2D);							// 启用纹理映射
            // OpenTK.Graphics.OpenGL.GL.ShadeModel(OpenTK.Graphics.OpenGL.ShadingModel.Smooth);							// 启用阴影平滑

            // OpenTK.Graphics.OpenGL.GL.ClearDepth(1.0f);									// 设置深度缓存
            //OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.DepthTest);								// 启用深度测试
            // OpenTK.Graphics.OpenGL.GL.DepthFunc(OpenTK.Graphics.OpenGL.DepthFunction.Lequal);							// 所作深度测试的类型
            // OpenTK.Graphics.OpenGL.GL.Hint(OpenTK.Graphics.OpenGL.HintTarget.PerspectiveCorrectionHint,
            //   OpenTK.Graphics.OpenGL.HintMode.Nicest);// 告诉系统对透视进行修正
            //  OpenTK.Graphics.OpenGL.GL.Color4(1.0f, 1.0f, 1.0f, 0.5f);						// 全亮度, 50% Alpha 混合
            //  OpenTK.Graphics.OpenGL.GL.BlendFunc(OpenTK.Graphics.OpenGL.BlendingFactorSrc.SrcAlpha, OpenTK.Graphics.OpenGL.BlendingFactorDest.One);

            v1 = RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.CameraLocation;
            v2 = RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.CameraUp;
            v3 = RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.CameraTarget;
            };

          game.Resize += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.Viewport(0, 0, Width, Height);
            double aspect_ratio = Width / (double) Height;
            OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float) aspect_ratio, 1, 12000);//设置视野最大最小距离
            OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Projection);
            OpenTK.Graphics.OpenGL.GL.LoadMatrix(ref perspective);

            };

          game.UpdateFrame += (sender, e) =>
            {
            if (game.Keyboard[Key.Escape]){ game.Exit();}
            };

          game.RenderFrame += (sender, e) =>
            {
            OpenTK.Graphics.OpenGL.GL.Clear
              (OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit | OpenTK.Graphics.OpenGL.ClearBufferMask.DepthBufferBit);

            OpenTK.Matrix4 LookAt = OpenTK.Matrix4.LookAt(
              (float) v1.X, (float) v1.Z, -(float) v1.Y,
              (float) v3.X, (float) v3.Z, -(float) v3.Y,
              0, 1, 0
              );

            // Matrix4 modelview = Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY);
            OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Modelview0Ext);
            OpenTK.Graphics.OpenGL.GL.LoadMatrix(ref LookAt);

            angle = (float) ( (Width / 2 - game.Mouse.X) / (float) Width * 360f);

            OpenTK.Graphics.OpenGL.GL.Rotate(angle, OpenTK.Vector3d.UnitY);
            DrawMatrix();

            //OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Lighting);
            Drawface(x);
            //OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Lighting);
           // OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.LineSmooth);
            // Drawface(Profile);
            Drawline(x);
            game.SwapBuffers();
            };
          // Run the game at 60 updates per second
          game.Run(60);
        }

          }catch(Exception ex){Print(ex.ToString());}
        }
    }