NxOgre   This page is related to a deprecated version of NxOgre, called BloodyMess. Some code from here may be adopted to newer versions with sufficient care and knowledge.   NxOgre


Disclaimer: This is not an official NxOgre tutorial. However, it has been revised and edited by the creator of NxOgre and BloodyMess, betajaen.

help Help: For any problems you encounter while working on these tutorials, as well as for detailed questions and propositions, please visit the NxOgre OgreAddons-Forum.

Image You can find the complete code for this tutorial here.

NxOgreCube.png Units Warning

NxOgre uses the metre-kilogram-second system, so for those of you who are most familiar with the imperial units system please take a moment to familiarize yourself with the International System of Units. Briefly put: NxOgre measures distance in metres, mass in kilograms, and time in seconds.

Newtons are a measurement of force. 1 Newton is the force required to accelerate one kilogram at a rate of one meter per second per second (1 KG·m/s2).

NxOgre makes use of the standard Cartesian coordinate system. So when I refer to the coordinates (10, 12, -8.7), I mean 10.0 metres in the X direction, 12.0 metres in the Y direction and -8.7 metres in the Z direction.

NxOgreCube.png Introduction

In the first tutorial, you have learned where to get BloodyMess, how to build NxOgre, and how to set up your IDE. Therefore, you now have everything you need to start simulating physics in your Ogre applications.

At the end of this tutorial something like the following should be achieved:

Peacefully Falling
Peacefully Falling

Midair Collision
Midair Collision

Rolling on the Floor
Rolling on the Floor

NxOgreCube.png The Initial Code

Start a new Ogre and NxOgre project in your -IDE. We will create the necessary code to make Ogre run using the ExampleApplication and ExampleFrameListener classes provided by the Ogre Samples.

Note: If you're fairly new with Ogre, it may be worth simply modifying the Ogre SkyBox sample instead of creating your own Ogre project.


The following code will serve as the basis for this tutorial. It should compile and run without errors.

#include "ExampleApplication.h"

class BloodyMessTutorial2Listener : public ExampleFrameListener
{ 
public:
    BloodyMessTutorial2Listener(RenderWindow *win, Camera *cam) 
        : ExampleFrameListener(win, cam)
    {
    }

    bool frameStarted(const FrameEvent& evt)
    {
        return ExampleFrameListener::frameStarted(evt);
    }

protected:
};

class BloodyMessTutorial2 : public ExampleApplication
{
protected:
    
    void createScene()
    {
        // Set ambient light
        mSceneMgr->setAmbientLight(ColourValue(0.5f, 0.5f, 0.5f));

        // Create a light
        Light* l = mSceneMgr->createLight("MainLight");
        l->setPosition(20, 80, 50);

        // Position the camera
        mCamera->setPosition(0, 20, 80);
        mCamera->lookAt(0, 20, 0);
    }

    // Create a new frame listener
    void createFrameListener()
    {
        mFrameListener = new BloodyMessTutorial2Listener(mWindow, mCamera);
        mRoot->addFrameListener(mFrameListener);
    }
};

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
    INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
    int main(int argc, char **argv)
#endif
    {
        // Create application object
        BloodyMessTutorial2 app;

        try {
            app.go();
        } catch(Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            MessageBoxA(NULL, e.getFullDescription().c_str(),
                "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
            std::cerr << "An exception has occurred: " << e.getFullDescription();
#endif
        }

        return 0;
    }

#ifdef __cplusplus
}
#endif

NxOgreCube.png Architecture of a BloodyMess World

The top-most BloodyMess class is the World, of which there can only be one instance. The size of this world is, for all intents and purposes, infinite, however truthfully it is only very, very large. Inside this world exist up to 32 Scenes. Objects in one scene cannot interact with objects in another scene.

In each scene are a large number of Actors, the number of which is only limited by your hardware. These Actors represent a physical object within the World, but they are completely invisible to us. In order to see them, you need to use a Body, which is simply an Actor that renders to your screen using a Render System. BloodyMess comes with several Rendering Systems built in including OpenGL and Ogre, however this does not restrict you from building your own.

Another important element of NxOgre is the TimeController. It controls the passage of time for the Actors within your World, from a frozen state, to that of real time, to a comically fast state.

NxOgreCube.png Our World, Scene, and Render System

First of all, you need to include NxOgre.h and NxOgreOGRE3D.h in order to use BloodyMess and its Ogre specific rendering classes, so place these at the top of your application:

#include <NxOgre.h>
#include <NxOgreOGRE3D.h>


Next, in our BloodyMessTutorial2 class, we declare our world, scene, and render system variables in the protected section of our class:

NxOgre::World* mWorld;
NxOgre::Scene* mScene;
OGRE3DRenderSystem* mRenderSystem;


You should notice that the render system is not part of the NxOgre namespace as it does not belong the the core BloodyMess code because the render systems are interchangeable. In our case, the OGRE3DRenderSystem comes from the NxOgreOGRE3D header.

Within our createScene() function we can then initialize the world:

mWorld = NxOgre::World::createWorld();


Before we initialise this scene, we will create as SceneDescription in our createScene() function, that we will then pass on to the scene initialization function:

NxOgre::SceneDescription sceneDesc;
sceneDesc.mGravity = NxOgre::Vec3(0, -9.8f, 0);
sceneDesc.mName = "BloodyMessTutorial2";

mScene = mWorld->createScene(sceneDesc);


With this code we have created a scene which uses the Earth's gravity and named the scene. Naming scenes are not important in BloodyMess, and it can indeed function quite well without them, but it is simply a good habit to name them.

With the next three lines, we will also specify some default physical values that are applied to the whole scene:

mScene->getMaterial(0)->setStaticFriction(0.5);
mScene->getMaterial(0)->setDynamicFriction(0.5);
mScene->getMaterial(0)->setRestitution(0.1);


These control the default frictional values and the bounce (restitution) of the scene. In this case the values you've just set are for a moderate amount of friction with very little bounce.

Now there is only one thing left before we have our scene set up: Declaring the renderer which is, in our case, Ogre.

mRenderSystem = new OGRE3DRenderSystem(mScene);


We are now ready to add objects to our scene.

NxOgreCube.png Adding a Cube

Since our scene is quite empty right now we will now populate it with a cube.

Note: This project makes use of the BloodyCake (an NxOgre example framework) mesh "cube.1m.mesh" which can be found in the archive here. For more information see this forum post.


We will create a body with a cube shape. First we need to create another variable, this time of the type OGRE3DBody, which we will initialize in our createScene() function.

OGRE3DBody* mCube;


To actually create this body we have to call the createBody()' function of the render system and pass some parameters:

  • the shape of our actor, which is in this case a box of the size 1x1x1 metre
  • the position of our new body, which is 20 metres above the center of the scene
  • the mesh we want to use to visualize our body

mCube = mRenderSystem->createBody(new NxOgre::Box(1, 1, 1), NxOgre::Vec3(0, 20, 0), "cube.1m.mesh");


If you compile the application now you will see the cube standing somewhere in the scene without moving at all, although we told our scene to have a gravity force. Why is this? We have not told our scene to "move". Or more precisely: we did not advance our TimeController.

NxOgreCube.png Getting Some Motion

To get some motion in the scene we will use our FrameListener to advance our TimeController every frame. Therefore, we have to alter its constructor a bit to get the TimeController, which the listener class has to store as a member. In every call of the frameStarted() function, the TimeController will now be advanced by the delta time (the time since the last frame).

Delete, or modify, the listener class and replace it with the following:

class BloodyMessTutorial2Listener : public ExampleFrameListener
{ 
public:
    BloodyMessTutorial2Listener(RenderWindow *win, Camera *cam) 
        : ExampleFrameListener(win, cam)
    {
        mTimeController = NxOgre::TimeController::getSingleton();
    }

    bool frameStarted(const FrameEvent& evt)
    {
        mTimeController->advance(evt.timeSinceLastFrame);
        return ExampleFrameListener::frameStarted(evt);
    }

protected:
    NxOgre::TimeController* mTimeController;
};


Compiling and running the application now, you will see NxOgre simulating physics within your application for the first time in the form of a box falling through your scene.

NxOgreCube.png Physical Interactions

What we did so far with NxOgre could also be easily achieved within Ogre by just moving the entity downward. To fully simulate a physical environment we will now have our box interact with other objects in the scene (what Ogre entities can't) by adding a few more things to our scene.

We will start with adding another cube. But as we don't want both of them just falling straight down, we will add a force to the second so that they collide in midair.

Declare a new OGRE3DBody:

OGRE3DBody* mCubeTwo;


And add the following to the bottom of the createScene() function:

mCubeTwo = mRenderSystem->createBody(new NxOgre::Box(1, 1, 1), NxOgre::Vec3(20, 35, 0), "cube.1m.mesh");
mCubeTwo->addForce(NxOgre::Vec3(-800, -200, 0));


The first line should look familiar to you, but the second needs a little explanation. The addForce() is a function which will will add a force to the box of 800 Newtons in the -X direction, 200 Newtons in the -Y direction and 0 newtons in the Z direction. In other words it will fly off at an angle and hopefully collide with the other box in our scene.

The last step is to create a floor plane, which is an actor, of infinite size that can not be moved:

mScene->createSceneGeometry(new NxOgre::PlaneGeometry(0, NxOgre::Vec3(0, 1, 0)), Matrix44_Identity);

Note: If you are using NxOgre BloodyMess version 1.5.4 then you will need to include the NxOgre namespace to the Matrix44_Identify call.


Now, we have an invisible floor plane on which our two cubes will land on. You can enhance the example by adding an Ogre::Plane to visualize the floor, but this has nothing to do with NxOgre and is only making use of simple Ogre calls:

MovablePlane *plane = new MovablePlane("Plane");
plane->d = 0;
plane->normal = Vector3::UNIT_Y;
Ogre::MeshManager::getSingleton().createPlane("PlaneMesh", 
    ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
    *plane, 120, 120, 1, 1, true, 1, 3, 3, Vector3::UNIT_Z);
Entity *planeEnt = mSceneMgr->createEntity("PlaneEntity", "PlaneMesh");
planeEnt->setMaterialName("Examples/GrassFloor");

Ogre::SceneNode* mPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
mPlaneNode->attachObject(planeEnt);
mPlaneNode->scale(100, 100, 100);


Compile and run your application and the two boxes should collide in mid air before finally landing on your floor plane to rest peacefully.

NxOgreCube.png Conclusion

That's it! You have now learned the very basics of BloodyMess. Now, continue on to the next tutorial where we will explore the very helpful Visual Debugger.


<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.