+ All Categories
Home > Documents > GLDrawer Documentation - Read the Docs

GLDrawer Documentation - Read the Docs

Date post: 17-Jan-2022
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
35
GLDrawer Documentation Michael Manning Feb 11, 2019
Transcript
Page 1: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Michael Manning

Feb 11, 2019

Page 2: GLDrawer Documentation - Read the Docs
Page 3: GLDrawer Documentation - Read the Docs

Contents

1 More than a drawing library 3

i

Page 4: GLDrawer Documentation - Read the Docs

ii

Page 5: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

GLDrawer is a simple drawing and game engine which has been modeled closely after GDIDrawer. It is can be usedin nearly all the same ways as it’s predecessor, but runs faster and has many more features.

Contents 1

Page 6: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

2 Contents

Page 7: GLDrawer Documentation - Read the Docs

CHAPTER 1

More than a drawing library

In addition to being an alternative to GDIDrawer to complete assignments, GLDrawer comes equipped with gameengine tools which enable you to create simple hardware accelerated games.

1.1 Overview

The GLDrawer is a simple rendering tool that allows you to create a window, or an embedded view in which you canrender a variety of graphical elements. GLDrawer is used through C#, but does not require knowledge of how graphicswork and is easy to learn with.

In addition to being a learning tool for coding, GLDrawer can even be used to create simple games with the built intools! To get started using GLDrawer, continue to the Quick Start page to learn how to install it.

1.2 Quick Start

To install GLDrawer in your project follow these steps.

Step 1Download The .DLL from the Github repository here.

Step 2Extract the files, locate the latest release of GLDrawer, then copy the GLDrawer.DLL file.Place the .DLL file somewhere easy to find or in your project directory.

Step 3

3

Page 8: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Open your project. In the solution explorer, right click references, then click add reference.Click Browse, navigate to GLDrawer.DLL and hit okay.

Step 4Include the GLDrawer namespece in your file with the “using” keyword and test the following program.

using GLDrawer;

namespace myProject{

public static class Program{

static void Main(string[] args){

GLCanvas can = new GLCanvas();can.AddText("It Works :)");Console.ReadKey();

}}

}

A window should will pop up and you should see the “it works” text. If you did, GLDrawer has been installedsuccessfully!

Issues?

For GLDrawer to work, your project must be target .NET Framework 4.5 or earlier. You also may need to tell visualstudio to Prefer 32-bit or even target x86 for your CPU.

Right click your project in the solution explorer and click properties. You will find these two settings under Applicationand Build respectively.

4 Chapter 1. More than a drawing library

Page 9: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

1.3 The Canvas

A canvas is a virtual surface on which shapes can be drawn. This section describes How the canvas system works andthe two ways in which you can create one.

Standalone window vs embedded

Just like in GDIDrawer, a canvas window is an actual, seperate window that contains nothing but a canvas. To get thiswindow to appear, it’s common to start with console application and create it from there.

An embedded window is exclusively for windows forms applications. It lets you create a canvas within a form insteadof creating two separate windows.

A note about buffers

The canvas system in GLDrawer uses two different buffers. A buffer is a dynamic block of memory which is used tostore the pixel values to display on screen. When you add normal shapes the the canvas, they are drawn to the frontbuffer. The front buffer is cleared every frame and all the shapes you’ve added to the screen are redrawn in case yourchanged something about them.

The Back Buffer is shown behind the front buffer and is never redrawn unless done manually or if the window isreSized. The backBuffer is like Microsoft paint. Any pixels you change will stay that way, but if you change the samepixel twice, you lose the first one.

You can also draw standard shapes to the back buffer. Adding shapes to the front buffer slows down your program themore you add because they all get redrawn every frame. shapes pasted to the back buffer are only ever drawn once,and will never slow down your program, no matter how many you add. The drawback is that you cannot move orchange any shape once it’s been drawn to the backBuffer.

Adding thousands of shapes per second to the back buffer with no performance hit

1.3. The Canvas 5

Page 10: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

1.3.1 Canvas Window

Creating a new GLCanvas object will open a new canvas window 800 by 600 pixels.

GLCanvas canvas = new GLCanvas();

Use named parameters!

There are many optional parameters of a canvas window, many more than you likely care about. To input only theparameters which are important to you, use the format of (paramater name): value. The following example will createa window of custome custome width, name, and back color.

GLCanvas canvas = new GLCanvas(900, title: "my fancy window", BackColor: Color.Red);

Once you have Initialised your canvas like the example above, a new window will emediatly pop up. If you wouldprefer to control when this happens, you can define your canvas on one line, but only initialse it when you would likeit to apear.

The canvas window can be closed with the “.closed()” function.

A standard canvas window with 10,000 rectangles

6 Chapter 1. More than a drawing library

Page 11: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

1.3.2 Embedded Canvas

When working with a Windows forms application, it’s not always convenient to have to open up a second window foryour canvas. Fortunatly, GLDrawer has built in functionality to expose the native window component of a canvas andembed it into your forms.

To insert a canvas in your form, open the designer first. Add a new panel which has the location and size of yourdesired canvas.

1.3. The Canvas 7

Page 12: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

In the above example, the panels have had their back color set to black so they would be easy to see. Nothing else waschanged to them. In order to get a canvas to show up on both panels, we need to create a canvas like before, but withspecial parameters.

//we simply call the constructor and give our form and our panel as argumentsGLCanvas can = new GLCanvas(this, largePanel);

//the small panel gets the same background color as the form to look transparentGLCanvas previewCan = new GLCanvas(this, smallPanel, BackColor: BackColor);

Success! now we can use the canvas’ like normal. The panels used are still in the background, but the canvas willfollow it around and even appear as the same window in the taskbar.

1.3.3 Members

Properties

8 Chapter 1. More than a drawing library

Page 13: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Name Type DescriptionTime long Time in seconds since canvas creationDeltaTime long Time in seconds since previous frameWidth int Width of the canvas in pixelsHeight int Height of the canvas in pixelsWindowTitle string Text displayed on the top window barScale float Multiplier for all coordinates such as shape positions and scaleBackColor Color The color of the canvas background or back bufferExtraInfo bool Adds information such as FPS, render time, and shape count to the window titleVSync bool Limits the framerate to 60fps and waits for vertical screen synchronization (read

only)DebugMode bool Overlays text displaying render times and shape count of the canvasBorderless bool wether the canvas window has BordersAutoRender bool wether the canvas will render the adde shapes automaticallyCenter vec2 Property that returns the center point of the canvasShapeCount int Property that returns the number of shapes on the canvas at any given timeGameObject-Count

int Property that returns the number of GameObjects the canvas

CameraPosition vec2 A translation applied to every coordinate on the screen before renderingCameraZoom float A scale applied to every coordinate on the screen before renderingGravity vec2 Direction and amount of gravity for physics

Functions

Name Type DescriptionAdd Shape Adds any shape or GameObject to the canvas and returns a copy of the referenceRemove void Removes a shape or Gameobject from the canvas given a referenceRefresh void Removes any lingering shapes from the canvas which have no referencesSendBack void Sets a shape one index earlier in the drawing orderSendforward void Sets a shape one index later in the drawing orderSendToBack void sets a shape to the first item in the drawing orderSentToFront void sets a shape to the last item in the drawing orderSwapDrawOrder void Switches the drawing order placement of two shapes on a canvassetBBPixel void Sets the color of a single pixel in the backgroundsetBBShape void Draws a shape to the background with no reoccurring performance cost and returns a referencegetPixel Color gets the color of a single pixel on the canvasClearBackBuffer void Redraws the background with the background colorClear void Removes all shapes from the canvasClose void Closes the canvas window or removes the canvas from a forms panelRender void Renders the scene if AutoRender is turned offSetWindowPostion void Moves the canvas window to a new location on the screenAddRectangle Rectangle Adds a Rectangle to the canvas and returns a referenceAddCenteredectangle Rectangle Adds a centered Rectangle to the canvas and returns a referenceAddEllipse Ellipse Adds an Ellipse to the canvas and returns a referenceAddCenteredEllipse Ellipse Adds a centered Ellipse to the canvas and returns a referenceAddLine Line Adds a Line to the canvas where start and end points are defined and returns a reference

Continued on next page

1.3. The Canvas 9

Page 14: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Table 1 – continued from previous pageName Type DescriptionAddLine Line Adds a line segment to the canvas at a known start point using a length and rotation angleAddSprite Sprite Adds an image to the canvas given a filepath and returns a referenceAddCenteredSprite Sprite Adds a centered image to the canvas given a filepath and returns a referenceAddText Text Adds text to the canvas given a bounding box and returns a referenceAddCenteredText Text Adds centered text to the canvas and returns a referenceAddCenteredPolygon Polygon Adds a centered polygon to the canvas and returns a referenceInstantiate GameObject Creates an initialized clone of a GameObject and adds it to the canvas with an optional transformLoadAsset void Loads an image into the canvas memory. This prevents stuttering when loading sprites at runtimeLoadAssets void Loads multiple images into canvas memory with an optional loading screenInvoke void Invokes a given function after a a number of secondsInvokeRepeating void Invokes a function repeatedly at a given frequencyDispose void Releases unmanaged canvas memory. Only used by the garbage collector and will cause problems if incorrectly calledRayCast bool detects the presence of a collider between two points

Events

Name Type DescriptionEarlyUpdate Action invoked once per frameUpdate Action invoked once per frame, after EarlyUpdateLateUpdate Action invoked once per frame, after LateUpdateCanvasResized GLResizeEvent called when the canvas is manually resized or dy dragging the window

1.4 Shapes

In these docs, a shape is used to describe anything that can be drawn on a canvas. In GLDrawer, a Shape is an objectinheritance tree which has a similar definition. While objects and inheritance are out of the scope of this guide, it willbe described here briefly as having general understanding will make your life much easier.

Drawing Shapes without a reference

When adding a rectangle to a canvas, you could do so like this:

//adds a rectangle at position 100,100 with a width and height of 200canvas.AddCenteredRectangle(100, 100, 200, 200, Color.White);

If you decided that after waiting for an input, you would now like that rectangle to move 100 pixels to right, you areforced to do so like this:

canvas.AddCenteredRectangle(100, 100, 200, 200, Color.White);Console.ReadKey();canvas.Clear();canvas.AddCenteredRectangle(200, 100, 200, 200, Color.White);

What the above code is doing, is creating a rectangle, then after an input, removing that rectangle and creating a newone 100 pixels further to the right. This works, but in GLDrawer, there are better ways to accomplish this.

Drawing Shapes with an object reference

10 Chapter 1. More than a drawing library

Page 15: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

A GLDrawer canvas itself is actually an object. This is because we can create an instance of a canvas on on line ofcode, and then do something else with it on a different one. In the exact same way, we can create an instance of aPolygon, then add it to a canvas later. Adding a rectangle to a canvas while keeping a reference can be done in twoways. The following examples do the same thing as the previous example, but with references.

Polygon shrecktangle = new Polygon(new vec2(100,100), new vec2(200,200), 0, 4, Color.→˓White);canvas.Add(shrecktangle);Console.ReadKey();shrecktangle.Position = new vec2(200, 100);

As you can see above, we create a Polygon object with 4 sides, then add it to the canvas on the next line of code.Unlike before, we actually get to keep a reference of that rectangle called shrecktangle. If we would like to move theshrecktangle, we don’t have to recreate it; we only need to change its Position property. This can also be done withthe following shortcut:

Polygon shrecktangle = canvas.AddCenteredRectangle(100, 100, 200, 200, Color.White);Console.ReadKey();shrecktangle.Position += new vec2(100, 0);

The GLDrawer AddCenteredRectangle function not only adds a Polygon to a canvas, it actually returns a reference!With this function, the Polygon reference is always created behind the scenes, and you can choose wether or not tokeep it. Another “shortcut” is instead of creating a new vec2 for position, we can alternatively increment it by a vec2with an x value.

How can there be Polygons AND Shapes? (advanced)

If the idea of creating a Polygon you can use makes sense to you, it likely stands to reason you could also create aLine, Sprite, Text .ect the same way. Seemingly unneeded, in addition to these object types, there is also a Shape type.

Your understanding of this isn’t required to use GLDrawer, but in short: all Lines are Shapes, but not all Shapes areLines.

You cannot create a standalone Shape in the same way as a Polygon or a Line, but because they are both membersof the shape hierarchy, we are allowed to make some assumptions. We can use the canvas.Add() function to add anyshape, regardless of what kind. You can also create a list of shapes eg. List<Shape> shapes, and store both Polygonsand Lines in it.

Creating a list like this would be considered a more advanced use of the shape hierarchy. That being said, there arebenefits thanks to the Shape type. Regardless of what spesific type of shape a Shape actually is, we can assume itwill have all the members seen in the top level member list. This means that even though you cannot create a genericShape without knowing what kind it is, if you already have one, like in a list, you can still change it. If you have angeneric Shape, you can’t change its filepath, but you can still change it’s position. This is because not all shapes, havefilepaths, but all shapes do have a location.

1.4.1 Shape Type Trivia

There are four different types of shapes that can be created with GLDrawer with six different construction options.

Rectangle

1.4. Shapes 11

Page 16: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

A “Rectangle” is just a Polygon with 4 sides. It has no special shape properties, but you can never go wrong with thefundamentals.

Ellipse

An Ellipse is also just a Polygon, this time with 1 Side. The difference in rendering is handled by the backend.

The only reason you see a circle instead of something else is because the shader running on your graphics processorknows when to draw round corners.

12 Chapter 1. More than a drawing library

Page 17: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Polygon

The two shape types above are polygons, but the Polygon type itself can be drawn with any number of sides. It is farless precise than the other shapes with more than 4 sides because the width and height of the polygon is dependant onthe number of sides it has as well as its angle.

Any >4 sided Polygons will almost always be drawn slightly smaller than its width and height values.

Line

A Line is actually is not polygon, but it keeps one privately. The reason lines are usefull is because you can modifythe start and end locations individually and the resulting position, scale, and angle of the resulting Rectangle areautomatically calculated.

1.4. Shapes 13

Page 18: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Sprite

Unlike in GDIDrawer which requires you to set the back buffer pixel by pixel to create an image, a GlDrawer Spriteacts like a Rectangle you can show an image or animation with.

Sprites render just as quickly as the other shape types, and you can use them to make repeating textures in small games.

Sprites work with most image file types and transparency is supported.

Text

GLDrawer has the ability rasterize TrueTypeFont files. This means that with nothing but the font filepath, and a stringof text, you can generate an image for every letter of the alphabet and have the letters appear in the same order as yourstring.

1.4.2 Members

Top level properties

14 Chapter 1. More than a drawing library

Page 19: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Name Type DescriptionPosition vec2 Location of the Shape on the canvas in pixelsScale vec2 Width and Height of the Shape in pixelsAngle float The angle of the Shape in radiansFillColor Color Color of the ShapeBorderColor Color Color of the Shapes’ outlineBorderWidth float Width of the Shapes’ outline in pixelsRotationSpeed float Animates the rotation of the ShapeHidden bool If true, the shape will not be drawn

Bottom level properties

Name Type ShapeType DescriptionThickness float Line Width of the LineLength float Line Length of the LineStart vec2 Line Location of one of the Line’s endsEnd vec2 Line Location of one of the Line’s endsSideCount int Polygon Number of sides to draw the Polygon WidthFilePath string Sprite Path of the image file to be drawnJustification JustificationType Text Justification of the paragraphBound Rectangle Text An optional boundry box to format a paragraph withinBody string Text The string of text to be drawnFont string Text The filepath to the ttf file to use. (Default Times new Roman)

1.5 Input

The input system in GLDrawer lets you find out what the keyboard and mouse are doing when using your program.There are a large number of options available for reading input information and the functions you choose will dependon the workflow you prefer.

Event style input

Because GLDrawer has been modeled after GDIDrawer, all input functions that it has can also be found in GLDrawer.This style of input detection uses a delegate event subscription system where you can create functions that will beautomatically called by GLDrawer whenever a specific type of input occurs.

Game style input

GLDrawer has been outfitted with many other simple input checks. When using GLDrawer to program a game, youwill likely have script style classes and functions which run ever frame. Being forced to use events to find out whichkeys are being held down is an inconvenience that has to be worked around when structuring code this way. To makelife easier, GLDrawer has a set of functions and properties that will let you find out where the mouse is at any giventime without havening to create new events for every type of input.

1.5. Input 15

Page 20: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

1.5.1 Creating Input Events

Creating an input event with GLDrawer is simple. All you need to do is create a special function to handle your input.After that, you just need to tell GLDrawer to use it.

The fast and easy way

Simply type the name of your canvas, followed by a dot, and use the arrow keys to find the event you’re lookingfor. Then, type “+=” and hit tab. An appropriate function will be automatically generated by intellisense with theparameters you need. There’s nothing else you need to set up. Any time the particular input occurs, your new functionwill be called.

If the shortcut doesn’t work for you, or you’d like to understand how to set up the event yourself, keep reading formore info.

Step 1

Read these docs or use intellisense to find the delegate format your need to use. There are only three.

Name ParametersGLMouseEvent (vec2 Position, GLCanvas Canvas)GLKeyEvent (Keys Code, GLCanvas Canvas)GLScrollEvent (int Delta, GLCanvas Canvas)

Step 2

Once you know the parameters you need, create a static function that takes those parameters. For this example we willcreate a function to handle a left mouse click which takes a vec2 and a GLCanvas reference. Your function must be avoid function that takes only these parameters or you will get an error.

private static void Can_MouseLeftClick(vec2 Position, GLCanvas Canvas){}

Step 3

We need to tell the canvas about our input function. Somewhere near the start of your program (after initializing thecanvas) use “+=” to subscribe your function to the MouseLeftClick event of your canvas.

can.MouseLeftClick += Can_MouseLeftClick;

Step 4

Your function should now be subscribed and will be called every time the canvas is left clicked. Lets test our work byadding an ellipse to the canvas wherever we click!

16 Chapter 1. More than a drawing library

Page 21: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

private static void Can_MouseLeftClick(vec2 Position, GLCanvas Canvas){

Canvas.AddCenteredEllipse(Position.x, Position.y, 50, 50, Color.White);}

If you’re still having issues, Make sure your function is a static void. Double check that the function has the requiredparameters and that the line of code that subscribes the function actually runs.

1.5.2 Members

Delegates

Name ParametersGLMouseEvent (vec2 Position, GLCanvas Canvas)GLScrollEvent (int Delta, GLCanvas canvas)GLKeyEvent (Keys Code, GLCanvas Canvas)

Events

1.5. Input 17

Page 22: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Name Type DescriptionMouseLeftClick GL-

MouseEventLeft click somewhere on the Canvas

MouseRightClick GL-MouseEvent

Right click somewhere on the Canvas

MouseMiddleClick GL-MouseEvent

Middle click somewhere on the Canvas

MouseLeft-ClickScaled

GL-MouseEvent

Left click somewhere on the Canvas multiplied by the canvas scale factor

MouseRightClickScaledGL-MouseEvent

Right click somewhere on the Canvas multiplied by the canvas scale factor

MouseMid-dleClickScaled

GL-MouseEvent

Middle click somewhere on the Canvas multiplied by the canvas scale factor

MouseLeftRelease GL-MouseEvent

Left mouse button released somewhere on the canvas

MouseRightRelease GL-MouseEvent

Right mouse button released somewhere on the canvas

MouseMiddleRe-lease

GL-MouseEvent

Middle mouse button released somewhere on the canvas

MouseLeftReleas-eScaled

GL-MouseEvent

Left mouse button released somewhere on the canvas multiplied by the canvasscale factor

MouseRightReleas-eScaled

GL-MouseEvent

Right mouse button released somewhere on the canvas multiplied by the can-vas scale factor

MouseMiddleRe-leaseScaled

GL-MouseEvent

Middle mouse button released somewhere on the canvas multiplied by thecanvas scale factor

MouseMove GL-MouseEvent

The mouse position is changed while over the canvas

MouseMoveScaled GL-MouseEvent

The mouse position is changed while over the canvas. Delegate vec2 is mul-tiplied by the canvas scale factor

KeyDown GLKeyEvent A key was pressed down with the canvas window in focusKeyUp GLKeyEvent A key was released with the canvas window in focusMouseScrolled GLScrollEventThe mouse scroll wheel was turned

Properties

18 Chapter 1. More than a drawing library

Page 23: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Name Type DescriptionMousePosition vec2 Location of the mouse in pixels relative to the canvasMousePositionScaled vec2 Location of the mouse in pixels relative to the canvas, multiplied by the canvas

scale factorMousePosition-ScreenSpace

vec2 Location of the mouse minus the screen center

MouseDeltaPosition vec2 The difference in mouse position since the previous frameLastLeftClick vec2 The Location of the Last left click in pixels relative to the canvasLastRightClick vec2 The Location of the Last Right click in pixels relative to the canvasLastNumberKey int The Last number key pressed with the canvas window in focusMouseLeftState bool Wether the left mouse button is currently held downMouseRightState bool Wether the Right mouse button is currently held downMouseMiddleState bool Whether the scroll wheel button (mouse button 3) is currently held downMouseScrollDirection int Returns the scroll direction of the current frame (usually -1 or +1)

Functions

Name Type Pa-rame-ters

Description

GetKey bool char Returns true if a given ASCII key is being held downGetKeyDown bool char Returns true if a given ASCII key was pressed on the current frameGetKeyUp bool char Returns true if a given ASCII key was released on the current frameGetSpecialKey bool key-

codeReturns true if a given Keycode is being held down

GetSpecialKey-Down

bool char Returns true if a given Keycode key was pressed on the current frame

GetSpe-cialKeyUp

bool char Returns true if a given Keycode key was released on the current frame

GetMouse bool int Returns true if the given Mouse button is being held down. (0 for left click,1 for right click)

GetMouseDown bool int Returns true if the given Mouse button was pressed on the current frame. (0for left click, 1 for right click)

GetMouseUp bool int Returns true if the given Mouse button was released on the current frame. (0for left click, 1 for right click)

GetLastMouse-LeftClick

bool outvec2

(Legacy) Returns true if there was a left click since the last time the functionwas called

GetLast-MouseRightClick

bool outvec2

(Legacy) Returns true if there was a Right click since the last time the func-tion was called

GetLastMouse-LeftClickScaled

bool outvec2

(Legacy) Returns true if there was a left click since the last time the functionwas called. out vec2 is multiplied by the canvas scale factor

GetLast-MouseRightClickScaled

bool outvec2

(Legacy) Returns true if there was a Right click since the last time the func-tion was called. out vec2 is multiplied by the canvas scale factor

GetLastMouse-Position

bool outvec2

(legacy) Returns true if the mouse has moved (within the canvas) since thelast time the function was called (same as MousePosition)

GetLastMouse-PositionScaled

bool outvec2

(legacy) Returns true if the mouse has moved (within the canvas) since thelast time the function was called. out vec2 is multiplied by scale

1.5. Input 19

Page 24: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

SpecialKey values

Also found on the GLFW docs: http://www.glfw.org/docs/latest/group__keys.html

Name Enum/ASCII value NoteUNKNOWN -1SPACE 32 SpacebarAPOSTROPHE 39 ‘COMMA 44 ,MINUS 45 -PERIOD 46 .FORWARDSLASH 47 /D0 48 0D1 49 1D2 50 2D3 51 3D4 52 4D5 53 5D6 54 6D7 55 7D8 56 8D9 57 9SEMICOLON 58 ;EQUALS 61 =LEFTBRACKET 91 [BACKSLASH 92RIGHTBRACKED 93 ]GRAVEACCENT 96 ‘ESCAPE 256ENTER 257TAB 258BACKSPACE 259INSERT 260DELETE 261RIGHT 262LEFT 263DOWN 264UP 265PAGEUP 266PAGEDOWN 267HOME 268END 269CAPSLOCK 280SCROLLLOCK 281NUMLOCK 282PRINTSCREEN 283PAUSE 84F1 290F2 291

Continued on next page

20 Chapter 1. More than a drawing library

Page 25: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Table 2 – continued from previous pageName Enum/ASCII value NoteF3 292F4 293F5 294F6 295F7 296F8 297F9 298F10 299F11 300F12 301F13 302F14 303F15 304F16 305F17 306F18 307F19 308F20 309F21 310F22 311F23 312F24 313F25 314NP0 320 Numpad 0NP1 321 Numpad 1NP2 322 Numpad 2NP3 323 Numpad 3NP4 324 Numpad 4NP5 325 Numpad 5NP6 326 Numpad 6NP7 327 Numpad 7NP8 328 Numpad 8NP9 329 Numpad 9NPDECIMAL 330 Numpad .NPDIVIDE 331 Numpad /NPMULTIPLY 332 Numpad *NPSUBTRACT 333 Numpad -NPADD 334 Numpad +KPENTER 335KPEQUAL 336 Numpad =LEFTSHIFT 340LEFTCONTROL 341LEFTALT 342LEFTSUPER 343RIGHTSHIFT 344RIGHTCONTROL 345RIGHTALT 346RIGHTSUPER 347MENUE 348

1.5. Input 21

Page 26: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

1.6 Using vec2

A vec2 is a simple struct containing nothing but an X and Y float. It is similar to a Pointf in that regard, but is packedwith mathematical features and shortcuts.

You can create a vec2 with its standard constructor:

//creates a vec2 with an X value of 100.0, and a Y value of 200.0vec2 location = new vec2(100f, 200f);

Giving a vec2 one parameter will assign the value to both X and Y.

//creates a vec2 with an X and Y value of 100.0vec2 location = new vec2(100f);

You can add, subtract, multiply, and divide vec2s together. The following two code blocks perform the same opera-tions.

vec2 A = new vec2(10f, 20f);vec2 B = new vec2(5f, 2f);

//creates a vec2 with an X value of 15.0, and a Y of 22.0vec2 C = new vec2(A.x + B.x, A.y + B.y);

Is the same as..

vec2 A = new vec2(10f, 20f);vec2 B = new vec2(5f, 2f);

vec2 C = A + B

vec2 math operators can also be performed with floats to affect both X and Y

vec2 A = new vec2(5f, 10f);

//A now has an X value of 30.0, and a Y of 60.0vec2 A *= 6f;

Calling vec2.Length will return the distance between vec2s in pixels

vec2 A = new vec2(); //same as vec2.Zerovec2 B = new vec2(5f, 10f);

//equivalent to 11.18 or Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y))float distance = A.Length(B);

Calling vec2.Normalize will return a direction vector from (0,0) with a radius of 1.0

vec2 position = new vec2(100f, 150f);vec2 destination = new vec2(50f, 30f);float moveDistance = 3f;

vec2 moveDirection = (position - destination).Normalize();

//position will be exactly 3 pixels closer to destinationposition += moveDirection * moveDistance;

vec2 can be implicitly converted between Pointf as well as rounded down to a standard Point.

22 Chapter 1. More than a drawing library

Page 27: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Pointf A = new Pointf(100f, 200f);vec2 B = A; //X and Y from A get assigned to B

//If you need to use Pointf and are feeling lazy, casting as a vec2 allows use of all→˓math operatorsPointf C = (vec2)A + B;

1.6.1 Members

Fields

Name Typex floaty float

Properties

Name DescriptionZero Returns a vec2 with the value of (0.0, 0.0)Max Returns a vec2 with the largest possible float valuesAbs Returns a new vec2 with the absolute values of X and Y from the current vec2

Functions

Name Parame-ters

Description

Length vec2 Returns the distance between the current vec2 and the vec2 parameterNormal-ize

None Returns a normalized version of the vec2

Lerp vec2, float Performs linear interpolation between the current vec2 and the vec2 parameter with thefloat parameter as time

1.7 Color

The Color data type in GLDrawer is a simple stucture containing four ints for the R, G, B, and A values. In computergraphics, all colors can be expressed with different combinations of red, green, and blue values between 0 and 255 for8 bit color. The A, or Alpha value is the Transparency of the Color.

1.7. Color 23

Page 28: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

In GLDrawer, there is also a special color if you choose Color.Rainbow

Aren’t you glad you decided to read the docs?

Dealing with System.Drawing.Color conflicts

GDIDrawer uses System.Drawing.Color whereas GLDrawer has its own color type. For the most part this doesn’tmatter because there’s little reason to include the System.Drawing namespace in a project using GLDrawer.

Unfortunately, when you create a Windows Forms application, System.Drawing gets added by default. This can createissues when creating a color, because the C# compiler doesn’t know which Color data type to use since they are bothcalled “color”. What the “using” keyword does is tell the compiler not to worry about specifying which namespaceyour accessing when you use its classes

Fortunately GLDrawer.color can be implicitly converted between System.Drawing.Color. So for most cases, you canjust uninclude the System.Drawing namespace from you document and use GLDrawer.Color exclusively. Since it canbe converted, you can still use colors eg. setting the back color of a control with a GLDrawer Color.

24 Chapter 1. More than a drawing library

Page 29: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Delete this line of code

If for any reason you do need both color structures, you can have two options. One option is to not using the Sys-tem.Drawing namespace, but specify your namespace every time you create a System.Drawing color. The other optionwould be to include System.Drawing and specify which namespace you’re using for every color, although this willlikely be more work.

//specifying the use of a GlDrawer colorGLDrawer.Color A = new GLDrawer.Color.Blue;

//specifying the use of a System.Drawing colorSystem.Drawing.Color B = new System.Drawing.Color.Red;

//Colors are still implicitly convertible, so you don't always need to specifyA = B;

1.7.1 Members

Properties

1.7. Color 25

Page 30: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Name Type DescriptionR int The red value of the color between 0 and 255G int The green value of the color between 0 and 255B int The Blue value of the color between 0 and 255A int The Alpha transparency value of the color between 0 and 255White Color Returns an opaque color with RGB values of 255, 255, 255Black Color Returns an opaque color with RGB values of 0, 0, 0Gray Color Returns an opaque color with RGB values of 100, 100, 100LightGray Color Returns an opaque color with RGB values of 160, 160, 160DarkGray Color Returns an opaque color with RGB values of 70, 70, 70Blue Color Returns an opaque color with RGB values of 0, 0, 255LightBlue Color Returns an opaque color with RGB values of 50, 200, 255DarkBlue Color Returns an opaque color with RGB values of 0, 0, 160Red Color Returns an opaque color with RGB values of 255, 0, 0DarkRed Color Returns an opaque color with RGB values of 150, 0, 0Pink Color Returns an opaque color with RGB values of 255, 20, 153Yellow Color Returns an opaque color with RGB values of 255, 255, 0Orange Color Returns an opaque color with RGB values of 255, 130, 0Purple Color Returns an opaque color with RGB values of 188, 11, 129Green Color Returns an opaque color with RGB values of 0, 200, 0DarkGreen Color Returns an opaque color with RGB values of 0, 130, 0LightGreen Color Returns an opaque color with RGB values of 100, 255, 100Invisible Color Returns a transparent color with RGBA values of 0, 0, 0, 0Random Color Returns an opaque Color with random RGB valuesRainbow Color Returns a special, secret color with RGBA values of 255, 255, 255, 255

Functions

Name Type DescriptionSetMonochrome void Sets the color to a shade of grey by averaging the RGB valuesInvert void Inverts the RGB values

1.8 GameObjects

Want to try your hand at making a simple game? You can make one with GLDrawer.

The “Game Engine” in GLDrawer is collection of classes that contain more advanced feature that expand on theexisting functionality of the canvas. In short, GameObjects are an abstract class that you can implement and add to thecanvas. GameObjects can contain child shapes for drawing, as well as child GameObjects for complex parent/childtransform relationships like the example below. GLDrawer’s game features are closely modeled after the Unity engine,so if you’re familiar with it, you should feel right at home.

26 Chapter 1. More than a drawing library

Page 31: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

The orbiting demo above might seem intimidating at first glance, but the use of GameObjects makes it simple. Creatingit using nothing but shapes requires an understanding of matrix operations and how they relate to transformations.Fortunately GLDrawer efficiently implements this math and exposes it an simple to use way.

All four of the GameObjects simply contain one child Polygon, and one parent/child GameObjects. The GameObjectsare given an initial position, then for every frame, each GameObjects rotation value is incremented slightly. Nothingelse was done to achieve the effect. (see the demos on Github)

1.8.1 Examples

1-Circle on mouse

Getting a circle on the screen

First things first, we need to create a class for our GameObject. If you’re unfamiliar with inheritance, this will look newto you. We can’t just create a GameObject like a variable, we have to create our own class and say it’s a GameObjectin the definition using ” : GameObject” near the name.

class Ball : GameObject{

public override void Start(){

//Gets run once when a ball is added to the canvas}public override void Update(){

//Gets called once per frame}

}

The above class is a bare bones GameObject and already there are some new things here. By setting the ball’s baseclass as a GameObject, it gets all the features of the GameObject class. The virtual function you will likely use themost are Start and Update. These functions will be called by the canvas and most of your game’s code will be insideof update functions.

1.8. GameObjects 27

Page 32: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

Important Note

Avoid class constructors as much as possible. Any GameObject code not invoked by the canvas can be dangerous as itis possible to use canvas functions before it has been initialized. If you need to add GameObjects at different position,use Canvas.Instatiate which is designed for that and will be covered later.

class Ball : GameObject{

public override void Start(){

AddChildShape(new Polygon(vec2.Zero, new vec2(100), 0, 1, Color.White));}public override void Update(){

transform.Position = Canvas.MousePositionScreenSpace;}

}

Now in your main program

can.Add(new Ball());

This will create a white Ellipse that will follow your mouse. Note the use of “transform” and “Canvas”. EveryGameObject has a Transform type called transform and a reference to the canvas called Canvas build in.

2-Parent and Child

In the last example we created a ball GameObject. We got a circle to appear at the location of the GameObject usingAddChildShape. Adding a child Shape sets the location of that shape as a child of the GameObject. In the same waywe can set a GameObject to be a child of another GameObject.

Let’s create a simple GameObject which has a Rectangle for a Shape. Every frame, we take the Transform of theGameObject and increment the rotation by 0.03 radians so it spins.

class Box : GameObject{

public override void Start(){

AddChildShape(new Polygon(vec2.Zero, new vec2(100), 0, 4, Color.White, 10,→˓Color.Red));

}public override void Update(){

transform.Rotation += 0.03f;}

}

Canvas Instantiate

GlCanvas.Instantiate is similar to Add in that it will add a GameObject to the canvas. If you would like easy was to setthe initial position of a GameObject use Instantiate. Instantiate also creates a deep copy clone of your original whichmakes it useful for GameObjects with many instances such as projectiles.

Box A = can.Add(new Box()) as Box;Box B = can.Instantiate(new Box(), new vec2(150)) as Box;

We put the first box in the center of the screen and the second offset from the center. This creates our orbiting effect.If we give both boxes the same global location they will be in the same spot, just spinning at different speeds.

28 Chapter 1. More than a drawing library

Page 33: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

A.AddChildGameObject(B);

And just like that, we have an orbiting effect. The Transform of Box B will first apply the Transform of the Box Abefore it’s own.

Using parent child relationships is a great way to accomplish many simple tasks as well. If you have something inyour game with multiple elements, you can use parent child relationships to keep them together.

3-Invoke Repeating and Timers

When programming a game, you will regularly find yourself needing time dependant functionality. Games need manycycle based and delayed functions, but you can’t just sleep the thread without stopping the entire programming. Wewill cover some timing techniques as well as built in tools in GLDrawer.

Delta Time

At any time, you can read from DeltaTime which is every GameObject as well as the canvas they are on. DeltaTimeis the amount of time in seconds since the last frame. This is useful in variety of situations. One being movementdue to the fact that the framerate of your game changes. If you add one to the x coordinate of an object every frame,it might look smooth at 60 frames per second, but when it dips below that, the object will actually move slower withthe framerate. If you multiply that movement by DeltaTime, it will compensate for dropped frames and end up in thesame place regardless of FPS.

DeltaTime can also be used to create a simple timer by incrementing a variable:

class ThingWithTimer : GameObject{

float timer = 0;public override void Update(){

timer += DeltaTime;if (timer > 2f){

//this gets run once every two seconds

timer = 0;}

}}

1.8. GameObjects 29

Page 34: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

By accumulating DeltaTime, we are effectively creating keeping track of time locally. Unlike GLCanvas.Time whichnever stops increasing, our local timer gets whenever it accumulates enough time.

Canvas Invoke

An easy way to create a delayed call is to use the Invoke function of the canvas. It takes an Action which means youcan pass in a method or an anonymous function.

class ThingWithTimer : GameObject{

public override void Start(){

Canvas.Invoke(delayed, 2f);Canvas.Invoke(delegate { Console.WriteLine("It's been 4 seconds"); }, 4f);

}

public void delayed(){

//this gets called once after two seconds}

}

Similar to GLCanvas.Invoke is InvokeRepeating. This function is the same as invoke, but will call your function overand over until it’s destroyed or the program ends. The following code will accomplish the same result as the first timerexample using DeltaTime.

class ThingWithTimer : GameObject {

public override void Start() {

Canvas.InvokeRepeating(RepeatedFunction, 2f);

}

public void RepeatedFunction() {

//this gets called every 2 seconds

}

}

This approach has it’s downsides if you need something more complex. The timing of InvokeRepeating is fixed. Ifyou want a timer that can be easily turned on and off or have delays that can change on the fly, you should stick to theDeltaTime Method.

GameObject.Destroy

Now to leave you with an example. Destroy will destroy the GameObject and clean up it’s memory. Sticking to thetiming theme, it also accepts a delay parameter for how long to wait before destruction. This is useful for temporaryobjects such as an explosion effect since you can Instantiate a GameObject with a ParticleSystem child and immedi-ately call destroy with a delay. This Lets you do what ever you want with whatever called Instantiate and ensures theexplosion animation can carry out before Destroying itself.

class Projectile : GameObject{

public override void Start(){

//set drawing element and destroy after 3.5 secondsAddChildShape(new Polygon(vec2.Zero, new vec2(20), 0, 1, Color.Red));Destroy(3.5f);

}

(continues on next page)

30 Chapter 1. More than a drawing library

Page 35: GLDrawer Documentation - Read the Docs

GLDrawer Documentation

(continued from previous page)

public override void Update(){

//move to the right of the screentransform.Position += new vec2(3, 0);

}}class Spawner : GameObject{

Projectile bullet = new Projectile();public override void Start(){

//clone the bullet every 0.15 seconds at the current positionCanvas.InvokeRepeating(delegate { Instantiate(bullet, transform.Position);},

→˓0.15f);}public override void Update(){

//change spawn location over timetransform.Position = new vec2(-350, 200 * (float)Math.Sin(Time));

}}

1.8. GameObjects 31


Recommended