Chapter 0: Learn OpenTK in 15'

So, you have downloaded the latest version of OpenTK - what now?

This is a short tutorial that will help you get started with OpenTK in 3 simple steps.

[Step 1: Installation]

Run the installer you downloaded. It will ask where you want OpenTK to be installed. Any folder will do.

[Step 2: Use OpenTK]

Create a new project in your .NET IDE (don't have a .NET IDE? Check out MonoDevelop or Visual Studio Express). Make it of type "Console Application".

Now, add a reference to OpenTK.dll: In your new project, right click "References" and select "Add Reference". Locate OpenTK.dll and add it.

Repeat this process for System.Drawing.dll. OpenTK depends on this.

Now you are ready to add some graphics! Open Program.cs and copy-paste the following code:

using System;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
 
namespace Example
{
    class MyApplication
    {
        [STAThread]
        public static 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(-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);
            }
        }
    }
}

Build and run this application. You should see a window with a triangle inside. Press escape to exit.

[Step 3: Play]

Now it's time to start playing with the code. This is a great way to learn OpenGL and OpenTK at the same time.

Every OpenTK game will contain 4 basic methods:

  1. Load: this is the place to load resources from disk, like images or music.
  2. UpdateFrame: this is a suitable place to handle input, update object positions, run physics or AI calculations.
  3. RenderFrame: this contains the code that renders your graphics. It typically begins with a call to GL.Clear() and ends with a call to SwapBuffers.
  4. Resize: this method is called automatically whenever your game window changes size. Fullscreen applications will typically call it only once. Windowed applications may call it more often. In most circumstances, you can simply copy & paste the code from Game.cs.

Why don't you try modifying a few things? Here are a few suggestions:

  1. Change the colors of the triangle or the window background (OnLoad and OnRenderFrame methods). Hint: use GL.Color4() to control the triangle color and GL.ClearColor() to control the background color.
  2. Make the triangle change colors when you press a key (OnUpdateFrame and OnRenderFrame methods).
  3. Make the triangle move across the screen. Use the arrow keys or the mouse to control its position (OnUpdateFrame). Hint: use Matrix4.CreateTranslation() to create a translation matrix and call GL.LoadMatrix() to load it (OnRenderFrame).
  4. Use a for-loop to render many triangles arranged on a plane (OnRenderFrame method).
  5. Rotate the camera so that the plane above acts as ground (OnRenderFrame method). Hint: use Matrix4.LookAt() to create a modelview matrix and use GL.LoadMatrix() to load it.
  6. Use the keyboard and mouse to walk on the ground. Make sure you can't fall through it! (OnUpdateFrame and OnRenderFrame methods).

Some things you might find useful: Vector2, Vector3, Vector4 and Matrix4 classes for camera manipulations. Mouse and Keyboard properties for interaction with the mouse and keyboard, respectively. Joysticks property for interaction with joystick devices.

Don't be afraid to try things and see the results. OpenTK lends itself to explorative programming - even if something breaks, the library will help you pinpoint the cause of the error.

Check out the examples at: https://github.com/opentk/opentk/tree/master/Source/Examples

[Step: next]

There's a lot of functionality that is not visible at first glance: audio, advanced OpenGL, display devices, support for GUIs through GLControl... Then there's the subject of proper engine and game design, which could cover a whole book by itself.

Hopefully, you'll have gained a feel of the library by now and you'll be able to accomplish more complex tasks. You might wish to consult the complete documentation for the more advanced aspects of OpenTK and, of course, don't hesitate to post at the forums if you hit any roadblocks!


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
objarni's picture

Great tutorial!

(Actually it got me thinking: how do I create a fixed-size GameWindow..? Eg. important if creating a retro-game/platformer. Also important if you have a fixed-aspect-ratio heads-up display in 3d games, eg. a cockpit in an airplane. Is it possible? Haven't tested GameWindow in a couple of months now..)

the Fiddler's picture

Use the WindowBorder property:

WindowBorder = WindowBorder.Fixed;

You can also disable the border completely with WindowBorder.Hidden. In general, this is not a good idea but some applications have managed to make it work: Google Chrome and the ZSNES emulator, for example.

pounce's picture

I want to start out by saying thanks to all that have made OpenTK possible and the above is a great tutorial....However I have encountered issues =( I followed the instructs after downloading (if it helps any what I DLed was "opentk-1.0.0-rc1.zip"). When I got to step 2, I double-clicked QuickStart.sln as instructed it launched my .Net IDE (which is MonoDevelop) and it seemed all was going according to plan. Well, when I took a look at the 'OpenTK' reference, it was highlighted in red and had a yellow triangle with an "!" in it with the words "Assembly not found"....Me, being who I am, went ahead and ran it (F5) for a better explaination ...Here's what I got for the build output.

Building: QuickStart (Debug)

Building Solution QuickStart

Building: QuickStart (Debug)
Performing main compilation...
/usr/bin/gmcs "/out:/home/demidione/Downloads/opentk-1.0.0-rc1/Binaries/QuickStart/Debug/QuickStart.exe" "/r:System.dll" "/r:System.Drawing.dll" /noconfig /nologo /warn:4 /debug:+ /debug:full /optimize- /codepage:utf8 /define:"DEBUG;TRACE" /t:winexe "/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs"
Compilation failed: 6 error(s), 0 warnings

/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(5,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(6,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(7,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(8,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(9,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs(10,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?

Build complete -- 6 errors, 1 warning

---------------------- Done ----------------------

Assembly 'OpenTK' not found. Make sure that the assembly exists in disk. If the reference is required to build the project you may get compilation errors.
Build: 6 errors, 1 warning

Can anyone help me figure out exactly what's going on at this point and how I can go about fixing the problem? Thanks in advance =)

the Fiddler's picture

Try adding the reference manually (right click on references -> add reference and navigate to opentk-1.0.0-rc1/Binaries/OpenTK/Release/OpenTK.dll). This should work correctly in the next release.

Edit: Quickstart.sln should also contain a file named "OpenTK.dll.config". If it does not, you should add this and set it to "copy to output directory" (you can find this file in the same directory as OpenTK.dll). Again, this should be fixed in the next release.

pounce's picture

Yay, it worked =)

Building: QuickStart (Debug)

Building Solution QuickStart

Building: QuickStart (Debug)
Performing main compilation...
/usr/bin/gmcs "/out:/home/demidione/Downloads/opentk-1.0.0-rc1/Binaries/QuickStart/Debug/QuickStart.exe" "/r:System.dll" "/r:System.Drawing.dll" "/r:/home/demidione/Downloads/opentk-1.0.0-rc1/Binaries/OpenTK/Release/OpenTK.dll" /noconfig /nologo /warn:4 /debug:+ /debug:full /optimize- /codepage:utf8 /define:"DEBUG;TRACE" /t:winexe "/home/demidione/Downloads/opentk-1.0.0-rc1/Source/QuickStart/Game.cs"
Build complete -- 0 errors, 0 warnings

---------------------- Done ----------------------

Build successful.

Ty Ty =)

SP_Otaku's picture

Using Win7 and Linux, but working in win7 (cause of magikjack). Had to manually add the reference to compile, but the problem is that the Quickstart didn't compile. Wondering if maybe the reference isn't reading right or something of that nature, like it's there but isn't being seen.

Note: the config file for the dll is in the bin dir of the project along with the dll.

Got the Following 5 Errors:
e:\Documents\Projects\Hello World\Hello World\Main.cs(13,13): Error CS0012: The type 'System.Drawing.Rectangle' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. (CS0012) (Hello World)

e:\Documents\Projects\Hello World\Hello World\Main.cs(41,41): Error CS1061: 'System.Drawing.Rectangle' does not contain a definition for 'X' and no extension method 'X' accepting a first argument of type 'System.Drawing.Rectangle' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Hello World)

e:\Documents\Projects\Hello World\Hello World\Main.cs(60,60): Error CS1061: 'System.Drawing.Rectangle' does not contain a definition for 'Y' and no extension method 'Y' accepting a first argument of type 'System.Drawing.Rectangle' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Hello World)

Can't wait to Jump in to this, Thanks You Everyone that has contributed :)

e:\Documents\Projects\Hello World\Hello World\Main.cs(79,79): Error CS1061: 'System.Drawing.Rectangle' does not contain a definition for 'Width' and no extension method 'Width' accepting a first argument of type 'System.Drawing.Rectangle' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Hello World)

e:\Documents\Projects\Hello World\Hello World\Main.cs(102,102): Error CS1061: 'System.Drawing.Rectangle' does not contain a definition for 'Height' and no extension method 'Height' accepting a first argument of type 'System.Drawing.Rectangle' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Hello World)

the Fiddler's picture

OpenTK depends on System.Drawing, so you need to add a reference to System.Drawing.dll.

carlo.milanesi's picture

First of all: Is OpenTK a game development toolkit or a generic low-level library?
I don't develop games. I develop industrial graphical software for touchscreen (CAD/CAM and SCADA).
Why do you call GameWindow the main window? Is OpenTK appropriate to develop industrial software for .NET Framework (Windows+Mono)?
Second issue: The first example makes the CPU load go to 100% even if I write game.Run(1, 1);
Third issue: Why there is a periodic "Render" event and a periodic "Update" event? I need a "Paint" event, an "Invalidate" command (that causes the "Paint" event), a "MouseDown" event, a "MouseUp" event, and a "MouseMove" event. My applications are for touchscreen, so keyboard events are not used.

FingersLingers's picture

Hi Carlo,

You may want to check out this chapter about the GLControl, Sounds like it will be more suited to what you are looking for.

Regards

rathan001's picture

Thanks @FingersLingers