Skip to content

Basic Tutorial

Josh edited this page Mar 26, 2024 · 38 revisions

Onyx - Basic Tutorial

This is a tutorial that will help you easily get started creating projects with Onyx.
Before we get into the code, we need to set up our project.

Setup

The pre-compiled binaries provided are compiled with Visual Studio 2022 for x64 and Release mode, and therefore this setup is specific to Visual Studio. If you choose to compile yourself so you don't have to use VS, be sure to also compile or find pre-compiled binaries for GLFW and FreeType that fit your platform.

Create a new C++ project in Visual Studio. Again, this setup is specific to Visual Studio; you can do whatever you want but can still follow this setup loosely.

We will need to set up the proper include and library directories, and specify what libraries we will be using.
From the download, move/copy the include and lib directories to wherever you want in the solution. Go to the properties page for the project (make sure the dropdowns at the top are All Configurations and All Platforms), and under C/C++ > General, enter the include path in Additional Include Directories. Do the same for Additional Library Directories under Linker > General. Then, under Linker > Input, in Additional Dependencies, add opengl32.lib, glfw3.lib, freetype.lib, and onyx.lib. It is also necessary to change your configuration to Release and x64. Lastly, move the resources folder from the download to the project directory (one more than the solution directory, unless the solution and project are in the same directory). Alternatively you could move the resources folder wherever you want and specify it with Onyx::SetResourcePath(<path>).

If you aren't using VS then you probably know what you're doing, just set the include and lib directories as I have described and link those four libraries, however you may have compiled them.

Now, to test, create a source file. Include the core library, initialize it with an error handler, run the demo, and terminate the library. Here is how that's done:

#include <Onyx/Core.h>

int main()
{
	Onyx::ErrorHandler errorHandler(true, false);
	Onyx::Init(errorHandler);
	Onyx::Demo();
	Onyx::Terminate();

	return 0;
}

Hit Ctrl + F5 in Visual Studio to run the program. If everything was done right, the application should start with a demo of a spinning textured cube with some text. If it worked, congratulations! If not, try researching the errors you got.

Also, there may be a bunch of PDB warnings, you can safely ignore these.

Start Coding!

As we have seen, you can run a quick demo with the code above, but let's make something ourselves.

Include Onyx/Core.h if you haven't already. The first steps are to create an error handler (not necessary but recommended) and initialize the library using that handler. (If you don't create an error handler, which you may not for production since it would be slightly faster, then you can just call Init() with no arguments.) Let's terminate the library after. All of the code from this point will come before the terminate call.

Onyx::ErrorHandler errorHandler(true, false);
Onyx::Init(errorHandler);
Onyx::Terminate();

The first argument in the error handler constructor is whether to log errors, the second whether to throw them.

Window

Now, let's create a window. We will use the Window class, so include Onyx/Window.h. When we create a window, we can specify the title, width, and height. We also have to initialize the window. At the end of the program, we need to dispose of the window.

// after Onyx initialization
Onyx::Window window("Onyx Tutorial", 1280, 720);
window.init();

// at the end of the program, just before Onyx termination
window.dispose();

Running the program now should flash a window on the screen, but it will disappear instantly. We need to create the mainloop, a code block that runs every frame until the window is closed. Every frame, at the minimum, we need to tell the window to start rendering and to end rendering.

// in between window init and dispose
while (window.isOpen())
{
	window.startRender();
	window.endRender();
}

Now the window should stay on the screen until we close it. The background is black, though, let's spice it up. Before the mainloop, let's set the background color of the window after we initialize it. This function takes a Vec3 as its argument, consisting of RGB values ranging from 0 to 1. Let's include Onyx/Math.h to use a Vec3.

// after window init, before mainloop
window.setBackgroundColor(Onyx::Math::Vec3(0.0f, 0.7f, 1.0f));

This should set the background to a nice sky blue color. Obviously, you can set it to whatever you want.

Quick note - there is doxygen documentation for all functions. If it's unclear what something does, in most IDEs, you can hover over the function and get a description of it.

Input Handling

Before we get to rendering some stuff, let's detect some key presses. For this, we need an input handler. Include Onyx/InputHandler.h. After we create the window, let's create an input handler and bind it to the window by passing it as an argument. Then, in the mainloop, let's test if the escape key is pressed, and if it is, let's close the window. We also need to 'update' the input handler every frame.

// after window initialization
Onyx::InputHandler input(window);

// beginning of mainloop
input.update();

if (input.isKeyDown(ONYX_KEY_ESCAPE)) window.close();

We use the isKeyDown method to test whether a key is currently pressed down, and to identify the key we use definitions prefixed with ONYX_KEY.

Try running the program and hitting the escape key. It should close.

Rendering

Let's render something! To do this, we create renderables and render them in between the start and end render calls. Onyx has renderable presets that we can use to start. Let's include Onyx/RenderablePresets.h and create a colored triangle renderable with a side length of 1 and a red color. Then, let's render it in the mainloop. We also need to dispose of the renderable before the program exits.

// after window and input handler creation
Onyx::Renderable triangle = Onyx::RenderablePresets::ColoredTriangle(1.0f, Onyx::Math::Vec3(1.0f, 0.0f, 0.0f));

// in between start and end render calls in mainloop
triangle.render();

// just after window is disposed
triangle.dispose();

Now there should be a red triangle in the middle of the screen.

3D World

To go 3D, we need a camera. But to use a camera, we need a renderer. A renderer is a class to organize your renderables and render them from the perspective of a camera. Let's include Onyx/Renderer.h and Onyx/Camera.h. Let's create a camera bound to our window, and then a renderer that uses that camera. Then, add the triangle to the renderer, and instead of calling render on the triangle, let's call it on the renderer. The camera needs to know whether we want perspective projection, in which further objects appear smaller, or orthographic projection, in which they don't. Orthographic is used for 2D or confusing art, so let's use perspective, with a field of view of 60 degrees (the first argument). The second two arguments are just the screen dimensions. We can also just dispose of the renderer now, rather than the triangle. Don't worry about memory leaks from the renderer copying the renderable, it's all covered by the library. We also need to 'update' the camera each frame.

// after triangle creation
Onyx::Camera cam(window, Onyx::Projection::Perspective(60.0f, 1280, 720));

Onyx::Renderer renderer(cam);
renderer.add(triangle);

// mainloop, after input handling but before rendering
cam.update();

// between start and end render calls
renderer.render()

// after window disposal
renderer.dispose()

If you run the program now, you'll see... nothing! Don't worry, this is because the camera is inside of our triangle. Let's translate (change position) it backwards a bit.

// after cam creation
cam.translateFB(-2.0f);

Now, we can see the triangle again, and you may notice that its size has changed a bit. This is because, with our camera, the side lengths of the triangle are now truly 1 unit - before they were 1 times a percentage of the screen width or height, so it was wider than it was tall.

Now, let's actually add some camera controls so we can move around in our (seemingly not) 3D world. We'll use the input handler to test for the traditional movement controls (WASD, mouse movement), and use some camera functions to move it around. Again, for more info on each of the functions being run, you can hover over them in most IDEs to get documentation.

if (input.isKeyDown(ONYX_KEY_W)) cam.translateFB(1.0f);
if (input.isKeyDown(ONYX_KEY_A)) cam.translateLR(-1.0f);
if (input.isKeyDown(ONYX_KEY_S)) cam.translateFB(-1.0f);
if (input.isKeyDown(ONYX_KEY_D)) cam.translateLR(1.0f);
if (input.isKeyDown(ONYX_KEY_SPACE)) cam.translateUD(1.0f);
if (input.isKeyDown(ONYX_KEY_C)) cam.translateUD(-1.0f);

cam.rotate(input.getMouseDeltas().getX(), input.getMouseDeltas().getY());

Now, we should be able to move around in our 3D world using WASD, space to go up, c to go down, and mouse to look around. But there's a problem, one you may have heard of if you've worked with graphics programming before. We move a static amount every frame, which makes it so the movements will be much more drastic if the frame rate is higher. We can fix this by multiplying values used every frame by the time since the last frame - the delta time. This calculation is covered by the window class. Multiply all 1.0f by window.getDeltaTime(). We don't need to do this with mouse deltas, though, since they are updated every frame by input.update(). It's also annoying how the cursor is still there while we're trying to fly around, so let's lock the cursor before the mainloop with input.setCursorLock(true).

Now, movement is pretty slow and sensitivity is pretty fast, so let's make some constants for the camera speed and sensitivity and multiply them as well. To make sensitivity a scale of 0-100 or something like it usually is in games, we'll multiply by .005 and then by the sensitivity. I like a speed of 4 and a sensitivity of 50:

// before mainloop
const float CAM_SPEED = 4.0f;
const float CAM_SENS = 50.0f;

// mainloop
if (input.isKeyDown(ONYX_KEY_ESCAPE)) window.close();
if (input.isKeyDown(ONYX_KEY_W)) cam.translateFB(1.0f * CAM_SPEED * window.getDeltaTime());
if (input.isKeyDown(ONYX_KEY_A)) cam.translateLR(-1.0f * CAM_SPEED * window.getDeltaTime());
if (input.isKeyDown(ONYX_KEY_S)) cam.translateFB(-1.0f * CAM_SPEED * window.getDeltaTime());
if (input.isKeyDown(ONYX_KEY_D)) cam.translateLR(1.0f * CAM_SPEED * window.getDeltaTime());
if (input.isKeyDown(ONYX_KEY_SPACE)) cam.translateUD(1.0f * CAM_SPEED * window.getDeltaTime());
if (input.isKeyDown(ONYX_KEY_C)) cam.translateUD(-1.0f * CAM_SPEED * window.getDeltaTime());

cam.rotate(input.getMouseDeltas().getX() * 0.005f * CAM_SENS, input.getMouseDeltas().getY() * 0.005f * CAM_SENS);

Now our 3D scene should have some smooth movement controls.
Let's change our boring triangle to a cube to complement our newfound third dimension:

Onyx::Renderable cube = Onyx::RenderablePresets::ColoredCube(1.0f, Onyx::Math::Vec3(1.0f, 0.0f, 0.0f));
// ...
renderer.add(cube);

Here's all the source code up to this point:

#include <Onyx/Core.h>
#include <Onyx/Window.h>
#include <Onyx/Math.h>
#include <Onyx/InputHandler.h>
#include <Onyx/RenderablePresets.h>
#include <Onyx/Renderer.h>
#include <Onyx/Camera.h>

int main()
{
	Onyx::ErrorHandler errorHandler(true, false);
	Onyx::Init(errorHandler);

	Onyx::Window window("Onyx Tutorial", 1280, 720);
	window.init();
	window.setBackgroundColor(Onyx::Math::Vec3(0.0f, 0.7f, 1.0f));

	Onyx::InputHandler input(window);

	Onyx::Renderable cube = Onyx::RenderablePresets::ColoredCube(1.0f, Onyx::Math::Vec3(1.0f, 0.0f, 0.0f));

	Onyx::Camera cam(window, Onyx::Projection::Perspective(60.0f, 1280, 720));
	cam.translateFB(-2.0f);

	Onyx::Renderer renderer(cam);
	renderer.add(cube);

	const float CAM_SPEED = 4.0f;
	const float CAM_SENS = 30.0f;

	input.setCursorLock(true);

	while (window.isOpen())
	{
		input.update();

		if (input.isKeyDown(ONYX_KEY_ESCAPE)) window.close();

		if (input.isKeyDown(ONYX_KEY_W)) cam.translateFB(1.0f * CAM_SPEED * window.getDeltaTime());
		if (input.isKeyDown(ONYX_KEY_A)) cam.translateLR(-1.0f * CAM_SPEED * window.getDeltaTime());
		if (input.isKeyDown(ONYX_KEY_S)) cam.translateFB(-1.0f * CAM_SPEED * window.getDeltaTime());
		if (input.isKeyDown(ONYX_KEY_D)) cam.translateLR(1.0f * CAM_SPEED * window.getDeltaTime());
		if (input.isKeyDown(ONYX_KEY_SPACE)) cam.translateUD(1.0f * CAM_SPEED * window.getDeltaTime());
		if (input.isKeyDown(ONYX_KEY_C)) cam.translateUD(-1.0f * CAM_SPEED * window.getDeltaTime());

		cam.rotate(input.getMouseDeltas().getX() * CAM_SENS * window.getDeltaTime(), input.getMouseDeltas().getY() * CAM_SENS * window.getDeltaTime());

		cam.update();

		window.startRender();
		renderer.render();
		window.endRender();
	}

	window.dispose();
	renderer.dispose();

	Onyx::Terminate();
	return 0;
}

Transforms

We can translate, rotate, and scale renderables, and it's very simple. Let's rotate the cube a little each frame, multiplying by the delta time again so it isn't frame rate dependent. 20 looks nice.

// in mainloop
cube.rotate(20.0f * window.getDeltaTime(), Onyx::Math::Vec3(0.2f, 1.0f, 0.5f));

That Vec3 looks random and complicated. All it does is specify some multipliers of the angle for each axis. Well, that sounds complicated too. The X value of the vector is the multiplier of the angle around the x axis. The Y is the multiplier of the angle around the y axis, and you can probably figure out the Z. So, here, we rotate 20 * deltaTime * 0.2 degrees around the x axis, 20 * deltaTime * 1 degrees around the y axis, and 20 * deltaTime * 0.5 degrees around the y axis. No reason for these values in particular, just looks nice. Enough yapping, run the program and see for yourself!

You can also translate and scale renderables. Let's make the cube travel to the right and get smaller as time goes on, just for fun.
Because of how the math works, the order of transformations matters - we first scale, then rotate, then translate.

// in mainloop
cube.scale(1.0f - 0.1f * window.getDeltaTime());
cube.rotate(20.0f * window.getDeltaTime(), Onyx::Math::Vec3(0.2f, 1.0f, 0.5f));
cube.translate(Onyx::Math::Vec3(1.0f * window.getDeltaTime(), 0.0f, 0.0f));

Scale is a multiplier based on the current scale. So, if we scale by 0.999 every frame, it will slowly get smaller. To incorporate this with delta time, we take 1 and subtract a small amount multiplied by delta time.

You also may notice that it's not actually just traveling to the right. When we rotate an object, we rotate its axes too, so the x axis that we are translating on is actually rotating with the object. This makes it travel in some sort of circle, if you follow it around for a bit or go above it.

You may also notice, if you follow it around for a bit, that you seem to get faster. That confused me also, but I realized it's just because the cube is getting smaller.

Textures

Enough of that boring red color on our cube! Let's make it look like a wooden container. In the resources folder from the download, there is an image that we can use.
To create a texture, we need some image data to generate the texture from. We can do this with an ImageData object, so let's create one from that container image. We use the static Load() function in ImageData to load an image, and the Onyx::Resources() function to generate a file path relative to the resource path. Let's then create a Texture object from this image data, and we can just do that all in one line. This will generate the actual texture that we can then attach to the renderable using the TexturedCube preset.

// replace renderable creation with this
Onyx::Texture texture(Onyx::ImageData::Load(Onyx::Resources("textures/container.jpg"));

Onyx::Renderable cube = Onyx::RenderablePresets::TexturedCube(1.0f, texture);

There's more to do!

Check out the Advanced Tutorial for more advanced methods.

Clone this wiki locally