The code for this article is provided at the end of the article.

This article is intended as an alternative to the Practical Application. With this article you'll learn how to combine several different ideas and features floating around on the wiki to create a blank project that can serve as the beginnings of a real project or just a staging ground for your own learning exercises.

This article assumes a windows platform. The basic idea is universal to all platforms, but you'll need to change the details in a few places to get things working under Linux or Mac.

Introduction

Aside from the Practical Application articles, there aren't many resources on setting up a real project using Ogre. There are other considerations, too. Such as organizing your source code, assets, and binaries to allow you to easily release your game as it stands. This article presents the amalgamation of ideas presented on the wiki with some of my own ideas to create a robust framework for new projects.

Features:

  • Organized directory allows you to easily strip developmental files and create a releasable .zip
  • Input manager for each window handles multiple listeners. Also handles anonymous polling
  • Threaded architecture allows for multiple threads
  • Packing binaries to decrease their physical size without changing
  • Game state stacks - organize your game states in a clean manner
  • Debugging controls
  • Controls the main game loop


Limits:

  • No GUI is set up at the moment. I'm not a fan of CEGUI, and there are so many alternatives that you'll want to explore all the options and set up your own.

Creating the directories

The directory structure I present here is based on how I've seen real games do it, and is based on the following requirements:

  • You need to be able to easily delete any intermediate files (ie: .obj files).
  • You need to create separate directories for your debug, release, console, and other compilation modes.
  • You need to be able to create a release of your game at a moment's notice.
  • You need to be able to add or remove assets by modifying a single file..


Based on these requirements, I came up with this structure:

  • Your Game Directory
    • System - contains your "real" game binaries and dependancies
      • Plugins - contains your render systems and other binaries as needed
    • Debug - contains your "debug" game binaries and dependancies
      • Plugins - yep, contains your debug render systems
    • Any other binary modes and dependancies follow likewise
    • Assets - Parent directory for all your assets. You create all the sub directories as you go.
    • DontInclude - A dumping ground for any intermediate files that get created during the build process. Don't include this directory with any release. It's just not needed.
    • Source - Contains all the source for your project.
      • Trunk - To allow you to easily start a source control method, all the source code is placed in this sub directory. Your workspace and sub projects go here.


To create a release of your game, just include the System and Assets directory. To create a source SDK for your game, to let other programmers start programming with you, just include the Source, Assets, System, and Debug directories.

This leaves the primary directory of your game empty of everything but some folders. You might want to add a shortcut to your game in this directory, so players know how to start playing your game. You can also add a Readme.

The following is the code for a .bat under windows that will set up all your directories like I describe above. Just place the text in a .bat file in your game directory and run it.
Alternative: open console in target directory and copy&paste the code by context menu.

md Debug
 md Debug\Plugins
 md System
 md System\Plugins
 md DontInclude
 md Assets
 md Source
 md Source\Trunk

What binaries do you need?

Ogre comes with a lot of binaries in its bin folder. Thankfully, most of them aren't necessary. And half of them are debug releases of the same binaries.

Static linking vs. dynamic

With newer versions of Ogre, licensing lets you statically link Ogre into your commercial project without "linking in" the LGPL. For this article, I'll be dynamically linking (ie: the program will need the Ogre binaries (.dll in windows) to run).

Pros for dynamic linking:

  • Your main executable size is reduced considerably. With the proper linker settings, you can get your final binary down to just a couple of kilobytes.

Cons of dynamic linking:

  • Your final release will be much bigger because you're dependencies have code for things you don't use.

The bare bones

What binaries do you actually need?

Ogre by itself just needs two: OgreMain.dll and a render system (usually either OpenGL or DirectX). Since it requires the same amount of work, I'll just be including both render systems. You can pick and change the render system as you please. OIS, Ogre's defacto input library, requires its own binary too. OIS.dll

All of the other binaries are for different plugins and behaviors. You can add them in as you need them.

The following is the .bat code for automatically copying the binaries in to your directories (set up in the last section) from teh Ogre SDK. The OGRE_HOME environment variable will need to be defined. If you installed from an Ogre SDK, this will have already been done. Again, just copy the text into a .bat file in your game's directory and run it. You can also rerun this script to recopy Ogre's binaries if you recompile Ogre or install a new SDK.

REM Copy Ogre binaries
 copy %OGRE_HOME%\bin\Release\OgreMain.dll System\OgreMain.dll
 copy %OGRE_HOME%\bin\Debug\OgreMain_d.dll Debug\OgreMain_d.dll
 
 REM Copy OIS binaries
 copy %OGRE_HOME%\bin\Release\OIS.dll System\OIS.dll
 copy %OGRE_HOME%\bin\Debug\OIS_d.dll Debug\OIS_d.dll
 
 REM DirectX binaries
 copy %OGRE_HOME%\bin\Release\RenderSystem_Direct3D9.dll System\Plugins\RenderSystem_Direct3D9.dll
 copy %OGRE_HOME%\bin\Debug\RenderSystem_Direct3D9_d.dll Debug\Plugins\RenderSystem_Direct3D9_d.dll
 
 REM OpenGL binaries
 copy %OGRE_HOME%\bin\Release\RenderSystem_GL.dll System\Plugins\RenderSystem_GL.dll
 copy %OGRE_HOME%\bin\debug\RenderSystem_GL_d.dll Debug\Plugins\RenderSystem_GL_d.dll


Last, we need to define a plugins.cfg file. Copy these contents to a file called plugins.cfg in the System/Plugins directory:

# Defines plugins to load
 
 # Define plugin folder
 PluginFolder=.\Plugins
  
 # Define plugins
 Plugin=RenderSystem_Direct3D9
 Plugin=RenderSystem_GL

And copy these contents into a plugins.cfg file in your debug/plugins directory:

# Defines plugins to load
 
 # Define plugin folder
 PluginFolder=.\Plugins
  
 # Define plugins
 Plugin=RenderSystem_Direct3D9_d
 Plugin=RenderSystem_GL_d

Assets

Last, we'll need to set up the assets directory. First, copy the OgreCore.zip file from the OgreSDK to your assets directory. This zip contains the graphics and fonts for the basic Ogre debug overlay.

Next, create a file called resource.cfg and copy this text in to it:

# Resource locations to be added to the 'boostrap' path
 # This also contains the minimum you need to use the Ogre example framework
 [Bootstrap]
 Zip=OgreCore.zip
 
 # Resource locations to be added to the default path
 [General]


You'll add in other entries as you add directories and packages to your game.

Creating the project workspace

Create the solution

Open up MSVC and go to file->new->project. Go to VC++, and at the very bottom click on Win32. Create a Win32 Project as follows:

(This is going to seem a little weird, but it's necessary to get the directories set up properly.)

  • Name: [Desired project name]
  • Location: [YourGameDirectory]\Source
  • Solution Name: Trunk (make sure Create Directory For Solution is checked)


Click OK to enter the wizard. Click next. Check "empty project", then the Finish button. Right click on your "Trunk" project in the solution browser in MSVC, and rename it to whatever would be more appropriate (or just leave it as trunk if you wish).

Congratulations, your source directory is set up properly. It should look like this:

  • Source - Contains your .sln file
    • [Project Name] - contains your .vcproj files


To add in a new project to the solution (for, say, unit tests), right click on your solution in the solution browser. Add->new project. Set it up however you wish, but for location make sure it says [YourGameDirectory]\Source\Trunk.

Settings

Right click on your project, and go to Configuration Properties. Make sure the configuration is on 'release'. Change the following properties in the following tabs:

General:
Output Directory: $(SolutionDir)\..\..\System
Intermediate Directory: $(SolutionDir)\..\..\DontInclude\$(ConfigurationName)

Debugging:
Working Directory: $(OutDir)

Library->input:
Additional Dependancies: OgreMain.lib OIS.lib

Library->Debugging:
Generate program Database File: $(IntDir)$(TargetName).pdb

Now change the configuration to '''debug'''. Change the following properties in the following tabs:
General:
Output Directory: $(SolutionDir)\..\..\Debug
Intermediate Directory: $(SolutionDir)\..\..\DontInclude\$(ConfigurationName)

Debugging:
Working Directory: $(OutDir)

Library->input:
Additional Dependancies: OgreMain_d.lib OIS_d.lib

Library->Debugging:
Generate program Database File: $(IntDir)$(TargetName).pdb


__Last:
__You'll want to set a preprocessor symbol so OIS knows you want to compile it as a dynamic link library (aka DLL). Got to C/C++->Preprocessor. For preprocessor definitions, add OIS_DYNAMIC_LIB

Important Note

This is what I've learned from trial and error. I'll try updating this section as necessary.

MSVC creates a .user file with the .csproj file. This .user file contains information on paths, such as which working directory to use, etc. For you to easily give your game directory to someone else so they can compile and modify your program, they'll need their own .user file to be set up properly. Ordinarily this won't happen. Go to your project directory. You should see a .user file that looks something like [Project Name].vcproj.[Your computer's name].[Your user profile name].user.

This file contains all the information we set up in the last section. Other people's computers won't read this information when they open the solution. This will result in all sorts of headaches. Rename this file to [Project Name].vcproj.user. This is now a universal "seed" file. If a user opens up the solution and MSVC can't find a specific user file, it will use this "seed" file to create a specific user file from.

Just remember from now on if you want to change any of the project's settings, you'll need to delete any specific user files and edit the "seed" file in a text editor. Other people on your project will need to delete their specific user files when they get your updated copy.

Boilerplate code

The following download is a zip of the roughly 1000 lines of boiler plate code that comes with this article. You are free to do pretty much whatever you want with it. You'll also need to understand how it works eventually if you want to add extra features.

Link is dead - no code - no dice. :-(

http://www.mediafire.com/?1yhwznmjg49 - Download the source code

Where to start

If you just want to start typing, add your code to MainGameState.cpp. Update, HandleEvents, and Draw are all executed in different threads. See Game states and Threading for information on how this works. To add something to look at, add code to the Initialization function.

Try code

You don't want windows telling the user when you have a problem, so all the code is try-catch'ed in a central way through the TryCode class. Errors are caught and sent to a dialog box through Ogre. Ogre comes with some built-in, cross platform dialog boxes, but you'll want to make your own eventually as your project gets more serious. At the moment, if there's an error it should get caught and sent to a proper dialog box (divide-by-0 is a notable exception).

Game states

Inspired by this article and another on this site, the code includes the idea of a game state, defined in AbstractGameState.h. Game states are simple abstractions that define an Initialization function, a Shutdown function, a HandleEvents function, and an Update and Draw function. To define a new game state, inherit from the AbstractGameState class, and implement the pure virtual functions.

Game states are loaded into a list by the GameStateManager, defined in GameStateManager.h. Slightly different from how the above articles use game states, the GameStateManager just maintains a list of GameStates to run through. This way, to run several different game states at once, all you need to do is call your GameStateManagerInstance.Update, etc. The game state manager will handle any initialization or shutdown of game states, but it won't delete them. If you create a game state on the heap, you'll need to delete it yourself.

Threading

All the threading code is contained in main.cpp at the moment. Threading is strongly tied in with the idea of game states. The input thread polls for new input data from OIS and makes the data available to the game states through their HandleEvents function. The game engine thread handles core game logic, like AI, basic gameplay, etc. It calls a game state's Update function. Last, the primary thread is responsible for all the Ogre related graphics, and calls the game states' Draw function.

Input data

The InputData class handles all the specifics of keeping the input data synced properly. Use the isDown or isUp functions to test for keys being down or up. The justDown and justUp functions only return true if a key was pressed or released this last cycle (useful for things like toggles). The last MouseState is also recorded into a buffer to let you access the mouse data from the last cycle.

Packing the binaries (and why)

Binaries for your Ogre project can take up a lot of space. An Ogre project folder that does nothing can take up 30 MB (that's including the debug OgreMain DLL that takes up 15 MB). What does this matter, right? What's 30MB in the modern world where we have hundreds of gigs of hard drive space? Well, honestly it doesn't make that big of a difference. But it's nice when things are small, and it isn't hard to set things up to pack your binaries, so why not do it?

Enter UPX. There are other binary packing utilities out there, but I've found this to be the easiest to use. Using it I managed to compress most of the binaries down to under 10MB.

You will need to add the directory you "installed" UPX to your system path for the following bat to work. This can be accomplished by pressing windows key + break, navigating to the Advanced tab, and clicking on Environment Variables. For user variables, scroll down to "path", and edit the entry. Add a semicolon (;) to the end, and then type in the directory where UPX is.

note Warning: UPX packed files relatively often will be detected as male software by some Virus scanners (false positive). Even http://www.virustotal.com virustotal.com give no bad result, this can happen in the future. So it's better to don't use it to avoid trouble with some users.


The following bat file will compress Ogre's binaries. Feel free to add any of your own binaries at the end.

UPX -9 System\OgreMain.dll
 UPX -9 System\OIS.dll
 UPX -9 System\Plugins\RenderSystem_Direct3D9.dll
 UPX -9 System\Plugins\RenderSystem_GL.dll
 
 UPX -9 Debug\OgreMain_d.dll
 UPX -9 Debug\OIS_d.dll
 UPX -9 Debug\Plugins\RenderSystem_Direct3D9_d.dll
 UPX -9 Debug\Plugins\RenderSystem_GL_d.dll

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.