Skip to content

Tutorial 1. Simple Application

Timur Gafarov edited this page Oct 21, 2022 · 30 revisions

Dagon version: >=0.14

This tutorial will guide you through creating your first Dagon application.

  1. Create a new Dub project and run dub add dagon.

  2. Import dagon module and create a class that inherits from Scene:

module main;

import dagon;

class TestScene: Scene
{
    Game game;
    OBJAsset aOBJSuzanne;

    this(Game game)
    {
        super(game);
        this.game = game;
    }

    override void beforeLoad()
    {    
        aOBJSuzanne = addOBJAsset("data/suzanne.obj");
    }

    override void afterLoad()
    {
        auto camera = addCamera();
        auto freeview = New!FreeviewComponent(eventManager, camera);
        freeview.zoom(-20);
        freeview.pitch(-30.0f);
        freeview.turn(10.0f);
        game.renderer.activeCamera = camera;

        auto sun = addLight(LightType.Sun);
        sun.shadowEnabled = true;
        sun.energy = 10.0f;
        sun.pitch(-45.0f);
        
        auto matSuzanne = addMaterial();
        matSuzanne.baseColorFactor = Color4f(1.0, 0.2, 0.2, 1.0);

        auto eSuzanne = addEntity();
        eSuzanne.drawable = aOBJSuzanne.mesh;
        eSuzanne.material = matSuzanne;
        eSuzanne.position = Vector3f(0, 1, 0);
        
        auto ePlane = addEntity();
        ePlane.drawable = New!ShapePlane(10, 10, 1, assetManager);
    }
}

In the example above we load a model from OBJ file (data/suzanne.obj) and attach it to an entity. We also create a plane object in the same manner. Adding FreeviewComponent to the camera allows the user to navigate the scene with mouse like in 3D editors.

  1. Create a class that inherits from Game, create your scene and assign it to currentScene:
class MyGame: Game
{
    this(uint w, uint h, bool fullscreen, string title, string[] args)
    {
        super(w, h, fullscreen, title, args);
        currentScene = New!TestScene(this);
    }
}
  1. Add a main function, create an instance of MyApplication and call its run method:
void main(string[] args)
{
    MyGame game = New!MyGame(1280, 720, "Dagon tutorial 1", args);
    game.run();
    Delete(game);
}
  1. Compile and run (dub build). Make sure to have latest SDL2 installed. If you're on Windows, Dub will automatically copy the libraries after each build to the project directory, so you don't have to do it manually. It will also copy some internal data files used by the engine and put them to data/__internal folder. Please, don't delete it, otherwise the application will work incorrectly.

You should see something like this:

Use left mouse button to rotate the view, right mouse button to translate, and mouse wheel (or LMB+Ctrl) to zoom.

Browse source code for this tutorial