| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870 |
- namespace Urho3D
- {
- /**
- \page Building Building Urho3D
- \section Building_Prerequisites Building prerequisites
- Although all required third-party libraries are included as source code, there are system-level dependencies that must be satisfied before Urho3D can be built successfully:
- - For Windows, the June 2010 DirectX SDK needs to be installed.
- - For Linux, the following development packages need to be installed: libx11-dev, libxrandr-dev, libasound2-dev on Debian-based distros; libX11-devel, libXrandr-devel, alsa-lib-devel on RedHat-based distros. Also install the package libgl1-mesa-dev (Debian) or mesa-libGL-devel (RH) if your GPU driver does not include OpenGL headers & libs. Building as 32-bit on a 64-bit system requires installing also the 32-bit versions of the development libraries.
- - For Raspberry Pi, the following development packages need to be installed: libraspberrypi0, libraspberrypi-dev, libasound2-dev on Raspbian; raspberrypi-vc-libs, raspberrypi-vc-libs-devel, alsa-lib-devel on Pidora. The first two packages which contain the Broadcom VideoCore IV libraries and development headers should normally come preinstalled.
- - For Mac OS X, the Xcode developer tools package should include everything necessary.
- - For Android, the Android SDK and Android NDK need to be installed. Optionally, also install Eclipse ADT plugin for building and deployment via Eclipse.
- To run Urho3D, the minimum system requirements are:
- - Windows: CPU with SSE instructions support, Windows XP or newer, DirectX 9.0c, GPU with %Shader %Model 2 support (%Shader %Model 3 recommended.)
- - Linux & Mac OS X: CPU with SSE instructions support, GPU with OpenGL 2.0 support, EXT_framebuffer_object and EXT_packed_depth_stencil extensions.
- - Raspberry Pi: %Model B revision 2.0 with at least 128 MB of 512 MB SDRAM allocated for GPU. OpenGL ES 2.0 capable GPU.
- - Android: OS version 2.2 or newer, OpenGL ES 2.0 capable GPU.
- - iOS: OpenGL ES 2.0 capable GPU.
- SSE requirement can be eliminated by disabling the use of SSE instruction set, see \ref Build_Options "Build options" below.
- \section Building_Desktop Desktop build process
- Urho3D uses CMake (http://www.cmake.org) to build. The process has two steps:
- -# Run CMake in the root directory with your preferred toolchain specified to generate the build files. You can use the provided batch files or shell scripts on the respective platform.\n
- - Windows: cmake_vs2008.bat, cmake_vs2010.bat or cmake_vs2012.bat,\n
- - Linux: cmake_gcc.sh or cmake_eclipse.sh,\n
- - Mac OS X: cmake_gcc.sh or cmake_macosx.sh.\n\n
- -# For Visual Studio, open Urho3D.sln and build the configuration(s) you like.\n
- For Eclipse, import the Eclipse's project generated by CMake into the workspace as a general project. The Eclipse's project is generated in "Build" sub-directory. See "Importing existing projects" in Eclipse Help for detail steps. Select "Build All" or "Build Project" in the menu. Note that Eclipse requires CDT plugin to build C/C++ project.\n
- For GCC, execute make in the "Build" sub-directory (by default, cmake_gcc.sh specifies to make a RelWithDebInfo build).\n
- For Xcode, open Urho3D.xcodeproj and build.
- On Windows, using other compilers than Visual Studio is not officially supported. MinGW may work (cmake -G "MinGW Makefiles"), but may lack required DirectX headers. They can be copied to a MinGW installation from the following package: http://www.libsdl.org/extras/win32/common/directx-devel.tar.gz.\n
- After the build is complete, the programs can be run from the Bin directory. These include the Urho3D script host application, which can run application scripts, the tools, and C++ sample applications if they have been enabled.
- To run the Urho3D application from the Visual Studio debugger, set the Urho3D project as the startup project and enter its relative path and filename into Properties -> Debugging -> Command: ..\..\Bin\Urho3D.exe. Additionally, entering -w into Debugging -> Command Arguments is highly recommended. This enables startup in windowed mode: without it running into an exception or breakpoint will be obnoxious as the mouse cursor will likely be hidden. To actually make the Urho3D application do something useful, it must be supplied with the name of the script file it should load and run. You can try for example the following arguments: Scripts/NinjaSnowWar.as -w
- To run from Eclipse on Linux, locate and select the Urho3D executable in the Project Explorer. From the menu, choose "Run Configurations" to create a new launch configuration for "C/C++ Application". Switch to "Arguments" tab, specify the argument required by Urho3D executable.
- To run from Xcode on Mac OS X, edit the Product Scheme to set "Run" setting to execute "Urho3D" in the "Info" tab. In the "Arguments" tab, specify the arguments required by Urho3D executable. Ensure the check boxes are ticked on the argument entries that you want to be active.
- \section Building_Android Android build process
- First, if you are building under Windows platform, copy Bin/Data and Bin/CoreData directories to the Android/assets directory (you can use the provided batch file CopyData.bat). This step is not necessary for non-Windows platform because the build script uses symbolic links for platforms that support it.
- Set the ANDROID_NDK environment variable to point to your Android NDK. On Windows, ensure that make.exe from the Android NDK is included in the path and is executable from the command line.
- On Windows, execute cmake_android.bat then go to the Android directory and execute the following commands. On OS X or Linux, execute cmake_gcc.sh (the ANDROID_NDK environment variable distinguishes from a normal desktop build) then go to the android-Build directory (which is a GCC out-of-source build) and execute the following commands.
- - android update project -p . -t 1 (only needed on the first time,
- replace '-t 1' with desired target-id)
- - make -j8 (replace '-j8' with the number of logical CPU cores of the
- host/build system)
- - ant debug
- After the commands finish successfully, the APK should have been generated to the Android/bin directory, from where it can be installed on a device or an emulator. The command "ant installd" can be used for this.
- For a release build, use the "ant release" command instead of "ant debug" and follow the Android SDK instructions on how to sign your APK properly.
- By default the Android package for Urho3D is com.googlecode.urho3d. For a real application you must replace this with your own package name. The Urho3D activity subclasses the SDLActivity from org.libsdl.app package, whose name (or the JNI code from SDL library) does not have to be changed.
- Note that the native code is built by default for armeabi-v7a ABI. To make your program compatible also with old Android devices, build also an armeabi version by executing the CMake batch file again with the parameter -DANDROID_ABI=armeabi added, then execute make again in the Android directory on Windows or android-Build directory on Mac/Linux.
- You can also build and deploy using Eclipse IDE with ADT plugin. To do that, after setting the ANDROID_NDK environment variable then run cmake_eclipse.sh. Import "Existing Android Code into Workspace" from the CMake generated Eclipse's project found in the android-Build directory. Switch Eclipse IDE to use Java Perspective. Update project properties to choose the desired Android API target and that's it. Just choose "Run" to let ADT automatically build and deploy the application to Android (virtual) device.
- \section Building_Ios iOS build process
- Run cmake_ios.sh. This generates an Xcode project named Urho3D.xcodeproj.
- Open the Xcode project and check the properties for the Urho3D project (topmost in the Project Navigator.) In Architectures -> Base SDK, choose your iOS SDK (CMake would automatically select latest iOS when generating the Xcode project). In Code Signing, enter your developer identity as necessary.
- The Urho3D target will actually build the application bundle and copy resources from Bin/Data and Bin/CoreData directories. Edit its build scheme to choose debug or release mode.
- To run from Xcode on iPhone/iPad Simulator, edit the Product Scheme to set "Run" destination setting to "iPhone Simulator" or "iPad Simulator", and executable to "Urho3D.app".
- \section Building_RaspberryPi Raspberry Pi build process
- For native build on Raspberry Pi itself, use the similar process for Linux Desktop build described above.
- For cross-compiling build on another build/host machine, set the RASPI_TOOL environment variable to point to your Raspberry Pi Cross-Compiling tool where all the arm-linux-gnueabihf-* executables are located. You can setup the tool using <a href="http://crosstool-ng.org/">crosstool-NG</a> or just download one from https://github.com/raspberrypi/tools. The RASPI_TOOL environment variable tells build script to generate additional build directory for cross-compiling.
- Run cmake_gcc.sh then go to the raspi-Build directory and proceed to execute make. After the build is complete, the ARM executables can be found in Bin-CC directory.
- You can also build, deploy, run/debug (as C/C++ Remote %Application) using Eclipse IDE, if you run cmake_eclipse.sh to generate the project file. Import the CMake generated Eclipse project in the raspi-Build directory into Eclipse's workspace. Build the project as usual. Use the SCP_TO_TARGET build option to automatically deploy the ARM executables to target Raspberry Pi as part of every project build or configure Eclipse to perform a "download to target path" in the Run/Debug configuration for C/C++ Remote %Application. Either way, you have to configure the Run/Debug configuration how to reach your target Raspberry Pi.
- \section Building_Library Library build
- CMake build configuration has been scripted to generate Urho3D executable as the default build target. This default target builds the Urho3D script host application (a tool to execute AngelScript and Lua script). To change it to generate an Urho3D static or shared (dynamic) library build target instead, specify the build option "-DURHO3D_BUILD_TYPE=STATIC" or "-DURHO3D_BUILD_TYPE=SHARED", respectively. When this option is set, the other build options to generate sample and tool targets are ignored. Due to the way the Urho3D project is being structured and the potential conflict of different visibility (export) attribute settings, when building the Urho3D library target then no other runtime targets can be built at the same time.
- Refer to \ref UsingLibrary "Using Urho3D as external library" on how to setup your own project to use Urho3D as external library.
-
- \section Building_64bit Desktop 64bit build
- Currently CMake build configuration has been set to compile Urho3D as 32bit by default. To enable 64bit build, run the provided cmake_xxxx.bat or cmake_xxxx.sh by passing the option "-DENABLE_64BIT=1" explicitly. For Visual Studio on Windows platform, this option also overrides CMake to use a 64bit solution generator.
- \section Building_Shaders Compiling Direct3D shaders
- When building with the Windows 8 SDK, copy d3dcompiler_46.dll from C:/Program Files (x86)/Windows Kits/8.0/bin/x86 to Urho3D Bin directory so that the ShaderCompiler program will run correctly.
- To make the Urho3D examples start faster on Windows & Direct3D9 mode, run CompileAllShaders.bat from the Bin directory first.
- Note that you can also force an OpenGL mode build on Windows by using the CMake option in the table below; OpenGL does not need a separate shader compilation step or utility.
- \section Build_Options Build options
- A number of build options can be defined explicitly when invoking the above cmake_xxxx batch files or shell scripts.\n
- |Defines |Build Options|
- |---------------------------------------------|---------------------|
- |-DENABLE_64BIT=1 |to enable 64bit build|
- |-DENABLE_LUA=1 |to enable additional Lua scripting support|
- |-DENABLE_SAMPLES=1 |to build the C++ sample applications|
- |-DENABLE_TOOLS=1 |to build the tools (only useful for Raspberry Pi build because this option is already enabled by default for other Desktop platforms)|
- |-DENABLE_SSE=0 |to disable SSE instruction set|
- |-DENABLE_MINIDUMPS=0 |to disable minidumps on crash (VS only)|
- |-DUSE_OPENGL=1 |to use OpenGL instead of Direct3D (only useful for VS on Windows platform because this option is enabled by default for other platforms)|
- |-DUSE_MKLINK=1 |to use mklink command to create symbolic links (Windows Vista and above only)|
- |-DSCP_TO_TARGET=user\@target:remote-location |to automatically scp executables to target system (only applicable for cross compiling Raspberry Pi on a build/host machine), SSH digital key must be setup first for this to work|
- |-DCMAKE_BUILD_TYPE=Release or RelWithDebInfo or Debug|to tell CMake which build configuration to be generated, default is Release (only applicable for cmake_gcc.sh and cmake_eclipse.sh)|
- |-DURHO3D_BUILD_TYPE=EXE or STATIC or SHARED |to tell CMake which Urho3D target to be built, default is EXE (Urho3D script host application)|
- \page Running Running Urho3D script host application
- The Urho3D script host application in the Bin directory contains all the engine runtime functionality. However, it does not contain any inbuilt logic, and therefore must be supplied with the name of the application script file it should run:
- \verbatim
- Urho3D <scriptfilename> [options]
- \endverbatim
- The scripting language supported by default is AngelScript (http://www.angelcode.com/angelscript); the script files have .as extension and need to be placed under either the Bin/Data or Bin/CoreData subdirectories so that Urho3D can find them. An application script is required to have the function void Start(), which will be executed before starting the engine main loop. It is this function's responsibility to initialize the application and to hook up to any necessary \ref Events "events", such as the update that happens every frame.
- Lua language support can be alternatively be built in, see \ref Build_Options "Build options".
- On Android and iOS the command line can not be entered, so it is instead read from the file Bin/Data/CommandLine.txt. By default the NinjaSnowWar example will be run.
- Currently eleven example application scripts exist:
- \section Running_NinjaSnowWar NinjaSnowWar
- A third-person action game. To start, run NinjaSnowWar.bat in the Bin directory, or use the command Urho3D Scripts/NinjaSnowWar.as
- Key and mouse controls:
- \verbatim
- WSAD Move
- Left mouse Attack
- Space Jump
- F1 Toggle AngelScript console
- F2 Toggle profiling display
- F3 Toggle physics debug geometry
- F4 Toggle octree debug geometry
- \endverbatim
- If a joystick is connected, it can also be used for controlling the player character.
- NinjaSnowWar also supports client/server multiplayer. To start the server, run the command NinjaSnowWar.bat server (-headless switch can optionally given so that the server will not open a graphics window.) To connect to a server, specify the server address on the command line, for example NinjaSnowWar.bat 127.0.0.1
- \section Running_TestScene TestScene
- Rendering, physics and serialization test. To start, run TestScene.bat in the Bin directory, or use the command Urho3D Scripts/TestScene.as
- Key and mouse controls:
- \verbatim
- WSAD Move
- Left mouse Create a new physics object; characters will ragdoll when hit
- Right mouse Hold and move mouse to rotate view
- Shift+LMB Paint a decal into the mouse cursor hit location
- Space Toggle debug geometry
- F1 Toggle AngelScript console
- F5 Save scene
- F7 Load scene
- 1 to 8 Toggle rendering options
- T Toggle profiling display
- O Toggle orthographic camera
- F Toggle FXAA edge filter
- B Toggle bloom post-process
- \endverbatim
- TestScene also includes a network replication test, where clients can connect, move around as invisible cameras, and create new physics objects. For this, a server needs to be started with the command TestScene.bat server (-headless switch can optionally given so that the server will not open a graphics window) and clients can connect by specifying the server address on the command line, for example TestScene.bat 127.0.0.1
- \section Running_Editor Editor
- %Scene and %UI layout editor application written in script. To start, run Editor.bat, or use the command Urho3D Scripts/Editor.as
- For details on how to use the editor, see \ref EditorInstructions "Editor instructions."
- \section Running_Terrain Terrain
- %Terrain rendering example. To start, run Terrain.bat, or use the command Urho3D Scripts/Terrain.as. %Controls are the same as in TestScene, and additionally:
- \verbatim
- L Toggle buoyant liquid volume
- \endverbatim
- \section Running_Vehicle Vehicle
- Simple vehicle physics example. To start, run Vehicle.bat, or use the command Urho3D Scripts/Vehicle.as.
- Key and mouse controls:
- \verbatim
- WSAD Steer vehicle
- Mouse Rotate camera around vehicle
- Space Toggle debug geometry
- F1 Toggle AngelScript console
- 1 to 8 Toggle rendering options
- T Toggle profiling display
- \endverbatim
- \section Running_Navigation Navigation
- A test of navigation mesh generation and path queries. Generates the same static scene as TestScene. To start, run Navigation.bat in the Bin directory, or use the command Urho3D Scripts\Navigation.as. %Controls are like in TestScene, except:
- \verbatim
- Left mouse Set path query end point
- Shift+LMB Set path query start point
- Middle mouse Create or delete object, which changes the navmesh
- Ctrl+LMB Set offmesh connection start point, press again to set end point
- \endverbatim
- \section Running_Physics Physics
- A stress test of 1000 moving physics objects, which also showcases the performance difference instancing can make. Run with Physics.bat, or use the command Urho3D Scripts/Physics.as. %Controls as in TestScene.
- \section Running_TestSceneOld TestSceneOld
- A variation of TestScene ported from Urho3D 1.0. It lacks networking features, but is provided for examining backward compatibility and performance. Run with TestSceneOld.bat or by using the command Urho3D Scripts/TestSceneOld.as. %Controls are like in TestScene, and additionally:
- \verbatim
- P Toggle scene animation
- L Toggle camera light detached/attached
- \endverbatim
- \section Running_LightTest LightTest
- %Light rendering performance test. To start, run LightTest.bat in the Bin directory, or use the command Urho3D Scripts\LightTest.as
- Key and mouse controls:
- \verbatim
- WSAD Move
- ZX Select model to use
- Arrows Add or remove lights and objects
- Pageup/down Add or remove 10 lights
- Right mouse Hold and move mouse to rotate view
- F1 Toggle AngelScript console
- 1 to 8 Toggle rendering options
- P Toggle renderpath (forward / prepass / deferred)
- T Toggle profiling display
- O Toggle orthographic camera
- V Toggle vertex lighting
- F Toggle FXAA edge filter
- R Re-randomize light and object positions
- \endverbatim
- \section Running_Chat Chat
- Simple client-server chat test application. To start, run Chat.bat or ChatServer.bat in the Bin directory, or use the command Urho3D Scripts/Chat.as
- On the client, first type the server address to the text edit box and click "Connect." After connecting successfully you can start typing messages;
- either press return or click "Send" to send them. Press ESC to exit.
- To connect automatically, the server address can also be given on the command line, for example Chat.bat 127.0.0.1
- \section Running_SpriteTest SpriteTest
- Simple example of using sprites in the user interface. To start, run SpriteTest.bat in the Bin directory, or use the command Urho3D Scripts\SpriteTest.as
- Key controls:
- \verbatim
- F1 Toggle AngelScript console
- T Toggle profiling display
- \endverbatim
- \section Running_Commandline Command line options
- The engine can be configured using the following command line options:
- \verbatim
- -x<res> Horizontal resolution
- -y<res> Vertical resolution
- -m<level> Enable hardware multisampling
- -v Enable vertical sync
- -t Enable triple buffering
- -w Start in windowed mode
- -s Enable resizing when in windowed mode
- -q Enable quiet mode which does not log to standard output stream
- -b<length> Sound buffer length in milliseconds
- -r<freq> Sound mixing frequency in Hz
- -headless Headless mode. No application window will be created
- -log<level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'
- -prepass Use light pre-pass rendering
- -deferred Use deferred rendering
- -lqshadows Use low-quality (1-sample) shadow filtering
- -noshadows Disable shadow rendering
- -nolimit Disable frame limiter
- -nothreads Disable worker threads
- -nosound Disable sound output
- -noip Disable sound mixing interpolation
- -sm2 Force SM2.0 rendering
- \endverbatim
- \page UsingLibrary Using Urho3D as external library
- This page shows how to create a new C++ project using Urho3D library as external library. This page assumes that you have already successfully build a static or shared library in the Urho3D project (separately from your own project). In order to find the external library in the Urho3D project build tree, specify an environment variable called "URHO3D_HOME" which points to the root directory of the Urho3D project.
- In your own project root directory, create a new CMakeLists.txt file and add the following lines:
- \code
- # Set project name
- project (MySuperDuperGame)
- # Set minimum version
- cmake_minimum_required (VERSION 2.8.6)
- if (COMMAND cmake_policy)
- cmake_policy (SET CMP0003 NEW)
- endif ()
- # Add cmake modules search path
- set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
- # Include Urho3D cmake module
- include (Urho3D-CMake-magic)
- # Find Urho3D library
- find_package (Urho3D REQUIRED)
- include_directories (${URHO3D_INCLUDE_DIR})
- link_directories (${URHO3D_LIBRARY_DIR})
- # Define target name
- set (TARGET_NAME Main)
- # Define source files
- file (GLOB CPP_FILES *.cpp)
- file (GLOB H_FILES *.h)
- set (SOURCE_FILES ${CPP_FILES} ${H_FILES})
- # Setup target with resource copying
- setup_main_executable ()
- \endcode
- Copy the "cmake" sub-directory from Urho3D project to your own project so that CMake can find the Urho3D-specific CMake modules in your project. Instead of copying, for platform that supports symbolic link, you can also create "cmake" symbolic link in your project build tree to point to "cmake" sub-directory from Urho3D project. Alternatively, you can just modify the CMAKE_MODULE_PATH search path above to "$ENV{URHO3D_HOME}/Source/cmake/Modules/".
- Since your CMake build script include the Urho3D-Cmake-magic module, your project also now has the cross-platform build capability.
- When both Urho3D static and shared library are built and available in the Urho3D project build tree, the Urho3D shared library takes precedence over static library to be linked against your own project. You can modify the CMAKE_FIND_LIBRARY_SUFFIXES global variable to change this behaviour. When linking statically against Urho3D static library, you must remember to additionally define "-DURHO3D_STATIC_DEFINE" in your compiler flag, especially on MSVC.
- \page Structure Overall structure
- Urho3D consists of several static libraries that are independent where possible: for example the Graphics library could be used without the Engine library, if only rendering capabilities were desired.
- The libraries are the following:
- - Container. Provides STL replacement classes and shared pointers.
- - Math. Provides vector, quaternion & matrix types and geometric shapes used in intersection tests.
- - Core. Provides the execution Context, the base class Object for typed objects, object factories, \ref Event "event handling", threading and profiling.
- - IO. Provides file system access, stream input/output and logging.
- - %Resource. Provides the ResourceCache and the base resource types, including XML documents.
- - %Scene. Provides Node and Component classes, from which Urho3D scenes are built.
- - %Graphics. Provides application window handling and 3D rendering capabilities.
- - %Input. Provides input device access in both polled and event-based mode.
- - %Network. Provides client-server networking functionality.
- - %Audio. Provides the audio subsystem and playback of .wav & .ogg sounds in either 2D or 3D.
- - %UI. Provides a 2D graphical user interface.
- - Physics. Provides physics simulation.
- - Navigation. Provides navigation mesh generation and pathfinding.
- - %Script. Provides scripting support using the AngelScript language.
- - %Engine. Instantiates the subsystems from the libraries above (except Script, which needs to be instantiated by the application) and manages the main loop iteration.
- Third-party libraries are used for the following functionality:
- - AngelScript: scripting language implementation
- - Bullet: physics simulation implementation
- - FreeType: font rendering
- - GLEW: OpenGL extensions handling
- - kNet: UDP networking
- - libcpuid: CPU properties detection
- - MojoShader: HLSL shader reflection after compiling
- - Open Asset Import Library: reading various 3D file formats
- - pugixml: parsing XML files
- - Recast/Detour: navigation mesh and pathfinding implementation
- - SDL: window and OpenGL context creation, input and sound output
- - StanHull: convex hull generation from triangle meshes, used for physics collision shapes
- - stb_image: image loading
- - stb_vorbis: Ogg Vorbis decoding
- \page Conventions Conventions
- Urho3D uses the following conventions and principles:
- - Left-handed coordinates. Positive X, Y & Z axes point to the right, up, and forward, and positive rotation is clockwise.
- - Degrees are used for angles.
- - Clockwise vertices define a front face.
- - %Audio volume is specified from 0.0 (silence) to 1.0 (full volume)
- - Path names use slash instead of backslash. Paths will be converted internally into the necessary format when calling into the operating system.
- - In the script API, properties are used whenever appropriate instead of %Set... and Get... functions. If the setter and getter require index parameters, the property will use array-style indexing, and its name will be in plural. For example model->SetMaterial(0, myMaterial) in C++ would become model.materials[0] = myMaterial in script.
- - Raw pointers are used whenever possible in the classes' public API. This simplifies exposing functions & classes to script, and is relatively safe, because SharedPtr & WeakPtr use intrusive reference counting.
- - No C++ exceptions. Error return values (false / null pointer / dummy reference) are used instead. %Script exceptions are used when there is no other sensible way, such as with out of bounds array access.
- - Feeding illegal data to public API functions, such as out of bounds indices or null pointers, should not cause crashes or corruption. Instead errors are logged as appropriate.
- - Third party libraries are included as source code for the build process. They are however hidden from the public API as completely as possible.
- For more details related to the C++ coding style, see also \ref CodingConventions "Coding conventions".
- \page ScriptQuickstart Quickstart in script
- In the following example, a minimal "Hello World" application with both 3D and user interface content will be built.
- We start by defining the Start() function required in all Urho3D script applications. When the Urho3D application executes it, all the engine subsystems are already in place, so any initialization that needs to be done is specific to the application itself.
- \code
- Scene@ helloScene;
- void Start()
- {
- helloScene = Scene();
- CreateObjects();
- CreateText();
- SubscribeToEvents();
- }
- \endcode
- Even before Start(), we define the object handle for the 3D scene we are going to create. This must be outside the function so that the Scene will remain after the function execution ends. Angelscript uses the @ symbol for object handles, which correspond to SharedPtr's on C++ side (ie. they keep alive the object pointed to.)
- In the Start() function itself, first of all we create the 3D scene. Note the lack of "new" keyword. Then we branch off to further initialization functions that will be defined below.
- Note that Urho3D has modified AngelScript to allow object handle assignment without the @ symbol, if the object in question does not support value assignment. None of the Urho3D reference-counted objects, such as Scene, support value assignment. In unmodified AngelScript the first line of Start() would have to read "@helloScene = Scene()".
- In CreateObjects(), which we define next, the scene will be filled with some content. The Urho3D scene model is basically a scene graph; the Scene object serves also as the root node.
- \code
- void CreateObjects()
- {
- helloScene.CreateComponent("Octree");
- Node@ objectNode = helloScene.CreateChild();
- Node@ lightNode = helloScene.CreateChild();
- Node@ cameraNode = helloScene.CreateChild();
- StaticModel@ object = objectNode.CreateComponent("StaticModel");
- object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
- object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
- Light@ light = lightNode.CreateComponent("Light");
- light.lightType = LIGHT_DIRECTIONAL;
- lightNode.direction = Vector3(-1, -1, -1);
- Camera@ camera = cameraNode.CreateComponent("Camera");
- cameraNode.position = Vector3(0, 0.3, -3);
- renderer.viewports[0] = Viewport(helloScene, camera);
- }
- \endcode
- First of all we need to create an Octree component into the root node. This is used for accelerated visibility queries to check what the camera "sees", and without it nothing would be visible.
- Three child nodes are then created: one for a 3D model object, one for a directional light, and one for the camera. The scene nodes themselves display nothing in the 3D world; components need to be created into them for the actual visible content.
- Child nodes can be created with or without names; uniqueness of names is not enforced. In this case we opt to not use names, as we do not need to find the nodes later after creation.
- As animation is not needed, we use a StaticModel component for the 3D model. Its scene node remains at the origin (default position of each scene node.) The ResourceCache subsystem is used to load the needed Model & Material resources.
- The light scene node also remains at the origin. Position does not matter for directional lights, but the node's forward direction is adjusted so that the light will shine down diagonally.
- The camera's scene node is pulled back along the Z-axis to be able to see the object.
- Finally we define a fullscreen Viewport into the Renderer subsystem so that the scene can be shown. The viewport needs Scene and Camera object handles. Note the indexing; multiple viewports could be defined (for example to use split screen rendering) if necessary.
- The 3D content is now finished. Next, we create the user interface content in CreateText().
- \code
- void CreateText()
- {
- Text@ helloText = Text();
- helloText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30);
- helloText.text = "Hello World from Urho3D";
- helloText.color = Color(0, 1, 0);
- helloText.horizontalAlignment = HA_CENTER;
- helloText.verticalAlignment = VA_CENTER;
- ui.root.AddChild(helloText);
- }
- \endcode
- We display a "Hello World" message on the screen with the help of a Text user interface element. We use the included Anonymous Pro font with point size 30. For the text to actually become visible, it needs to be added as a child of the user interface root element (the UI can be thought of as a 2D scene graph.) It is also centered both horizontally and vertically in relation to the parent element.
- Finally we subscribe to necessary Urho3D events in the SubscribeToEvents() function.
- \code
- void SubscribeToEvents()
- {
- SubscribeToEvent("Update", "HandleUpdate");
- }
- \endcode
- If no events would be responded to, the application would just be left running with no possibility to interact with it, until it was forcibly exited with Alt-F4. In this case, we are interested of the frame update event, which will be sent on each iteration of the main loop. When subscribing, we need to give the name of the event, and the name of the event handler function. We could also require the event to be sent by a specific sender, but in this case that is unnecessary.
- The event handler function needs to have a specific signature. If event type and parameters are not needed, "void HandleEvent()", or if they are, "void HandleEvent(StringHash eventType, VariantMap& eventData)". We might want to expand the application later, so we use the latter form.
- \code
- void HandleUpdate(StringHash eventType, VariantMap& eventData)
- {
- float timeStep = eventData["TimeStep"].GetFloat();
- if (input.keyPress[KEY_ESC])
- engine.Exit();
- }
- \endcode
- The current frame's delta time is sent in the update event's parameters, and that will be useful when animating the scene. For now the event handler simply checks from the Input subsystem if the ESC key has been pressed; if it is, it calls the Engine subsystem's \ref Engine::Exit "Exit()" function. This closes the Urho3D application window and causes an exit after the current main loop iteration finishes.
- Note that to get the ESC keypress without having to poll it for each frame, we could also subscribe to the "KeyDown" event sent by the Input subsystem.
- The example application is now complete. To try it out, save it as HelloWorld.as in the Bin/Data/Scripts directory, then change working directory to Bin where the Urho3D application resides and run `Urho3D.exe Scripts/HelloWorld.as` on Windows platform or `./Urho3D Scripts/HelloWorld.as` on Mac OS X and Linux platforms.
- \section Xcode_AngleScript_Info Mac OS X specific - How to view/edit AngelScript within Xcode
- By default Mac OS X recognizes file having extension .as as 'AppleSingle Archive'. So, even after associating this file type to always open with Xcode, Xcode is still not able to view/edit the content of the file correctly. In order to view/edit the scripts, after launching the Urho3D project in Xcode, select the .as file(s) in the Project Navigator and then in the %File Inspector (right panel) change the file type from 'Default - AppleSingle archive' to 'C++ Source' in the %File Type drop down list. The current editor view usually does not refresh its content after this change. Selecting another file in the Project Navigator then reselecting the .as file should force the editor to reload and show the .as file correctly afterwards.
- The drawback of the above approach is, Xcode does not remember it. The steps need to be carried out each time Xcode is relaunched.
- To solve this permanently, we need to 'hack' the system a little bit to 'fool' Xcode to always treat .as file as one of the C++ source files. Execute the following commands in a terminal as normal user. These commands have been verified on Lion.
- \code
- $ cd /System/Library/CoreServices/CoreTypes.bundle/Contents
- $ plutil -convert xml1 Info.plist -o /tmp/Info.plist.xml
- $ sed -i.bak "s/<string>cxx<\/string>/<string>cxx<\/string>\\`echo -e '\n\r'`<string>as<\/string>/g" /tmp/Info.plist.xml
- $ sudo cp -p Info.plist{,.ori}
- $ sudo plutil -convert binary1 /tmp/Info.plist.xml -o Info.plist
- $ find /System/Library/Frameworks -type f -name lsregister -exec {} -kill -r -domain local -domain system -domain user -domain network \;
- \endcode
- The last command resets the launch service database and rebuilds it, so the changes should take effect immediately when Xcode restarts.
- \page CppQuickstart Quickstart in C++
- Note: this page is deprecated. A set of sample C++ applications is being developed into the Samples directory.
- This example shows how to create an Urho3D C++ application from the ground up. The actual functionality will be the same as in \ref ScriptQuickstart "Quickstart in script"; it is strongly recommended that you familiarize yourself with it first.
- To start with, create a subdirectory "HelloWorld" into the Urho3D root directory, and add the following line to the end of the root directory's CMakeLists.txt %file:
- \code
- add_subdirectory (HelloWorld)
- \endcode
- Then, create the following CMakeLists.txt file into the HelloWorld directory (mostly copied from CMakeLists.txt of the Urho3D application):
- \code
- # Define target name
- set (TARGET_NAME HelloWorld)
- # Define source files
- file (GLOB CPP_FILES *.cpp)
- file (GLOB H_FILES *.h)
- set (SOURCE_FILES ${CPP_FILES} ${H_FILES})
- # Define dependency libs
- set (LIBS ../Engine/Container ../Engine/Core ../Engine/Engine ../Engine/Graphics ../Engine/Input ../Engine/IO ../Engine/Math ../Engine/Resource ../Engine/Scene ../Engine/UI)
- # Setup target with resource copying
- setup_main_executable ()
- \endcode
- Before recreating the build files with CMake, create an empty HelloWorld.cpp into the HelloWorld directory. Now you can re-run CMake. If using Visual Studio, the HelloWorld project should now appear in the Urho3D solution, and you can start writing the actual application into HelloWorld.cpp.
- First we need to include the header files for all the engine classes we are going to use, plus Main.h, which helps to create the main function in a cross-platform compatible way. Additionally, including DebugNew.h enables debug allocation in Visual Studio debug builds. This helps to track down memory leaks by adding file name and line number information to each heap memory allocation in our own code.
- \code
- #include "Camera.h"
- #include "Context.h"
- #include "CoreEvents.h"
- #include "Engine.h"
- #include "Font.h"
- #include "Input.h"
- #include "Light.h"
- #include "Material.h"
- #include "Model.h"
- #include "Octree.h"
- #include "ProcessUtils.h"
- #include "Renderer.h"
- #include "ResourceCache.h"
- #include "Scene.h"
- #include "StaticModel.h"
- #include "Text.h"
- #include "UI.h"
- #include "Main.h"
- #include "DebugNew.h"
- \endcode
- All Urho3D classes reside inside the namespace Urho3D, so a using directive is convenient:
- \code
- using namespace Urho3D;
- \endcode
- To be able to subscribe to events, we need to subclass Object (if we did not use events, we could do everything procedurally, for example directly in the main function we define, but that would be somewhat ugly.) We name the class HelloWorld, with functions that match the script version, plus a constructor. Note the shared pointers to the scene that we will create, and to the ResourceCache, which is perhaps the most often used subsystem, and therefore convenient to store here. Also note the OBJECT(className) macro, which inserts code for object type identification:
- \code
- class HelloWorld : public Object
- {
- OBJECT(HelloWorld);
- public:
- HelloWorld(Context* context);
- void Start();
- void CreateObjects();
- void CreateText();
- void SubscribeToEvents();
- void HandleUpdate(StringHash eventType, VariantMap& eventData);
- SharedPtr<Scene> helloScene_;
- SharedPtr<ResourceCache> cache_;
- };
- \endcode
- Before the actual HelloWorld implementation, we define the program entry point. The earlier included Main.h contains a DEFINE_MAIN macro which creates the platform-specific main function (on Windows it will be WinMain(), on Linux just main() etc.) It parses the command line and then returns control to our function.
- \code
- int Run()
- {
- SharedPtr<Context> context(new Context());
- SharedPtr<Engine> engine(new Engine(context));
- VariantMap engineParameters = Engine::ParseParameters(GetArguments());
- engineParameters["WindowTitle"] = "HelloWorld";
- engineParameters["LogName"] = "HelloWorld.log";
- engine->Initialize(engineParameters);
- SharedPtr<HelloWorld> helloWorld(new HelloWorld(context));
- helloWorld->Start();
- while (!engine->IsExiting())
- engine->RunFrame();
- return 0;
- }
- DEFINE_MAIN(Run())
- \endcode
- In our function, we first create the Context object, which holds all subsystems and object factories, and keeps track of event senders and receivers. All Object subclasses need to be supplied a pointer to that context. When using an object factory (such as when creating components) that is automatic, but when creating objects manually, the pointer also needs to be passed manually.
- With the context at hand, we create the Engine and initialize it. The engine accepts startup parameters in a VariantMap; these can be parsed from the command line arguments using the static helper function Engine::ParseParameters. Here we customize the window title and log file name to differentiate from the Urho3D application.
- After this, we instantiate the HelloWorld object, call its Start() function, and run the main loop until Engine tells that we should exit. The shared pointers will take care of deleting the objects in the correct order; the Context will be the last to be destroyed.
- Now we can start implementing HelloWorld.
- \code
- HelloWorld::HelloWorld(Context* context) :
- Object(context),
- cache_(GetSubsystem<ResourceCache>())
- {
- }
- \endcode
- During construction, we only store the ResourceCache subsystem pointer for later access.
- In the Start() function the Scene will be created:
- \code
- void HelloWorld::Start()
- {
- helloScene_ = new Scene(context_);
- CreateObjects();
- CreateText();
- SubscribeToEvents();
- }
- \endcode
- Like in the script example, CreateObjects() does the actual scene object creation and defines the viewport.
- \code
- void HelloWorld::CreateObjects()
- {
- helloScene_->CreateComponent<Octree>();
- Node* objectNode = helloScene_->CreateChild();
- Node* lightNode = helloScene_->CreateChild();
- Node* cameraNode = helloScene_->CreateChild();
- StaticModel* object = objectNode->CreateComponent<StaticModel>();
- object->SetModel(cache_->GetResource<Model>("Models/Mushroom.mdl"));
- object->SetMaterial(cache_->GetResource<Material>("Materials/Mushroom.xml"));
- Light* light = lightNode->CreateComponent<Light>();
- light->SetLightType(LIGHT_DIRECTIONAL);
- lightNode->SetDirection(Vector3(-1.0f, -1.0f, -1.0f));
- Camera* camera = cameraNode->CreateComponent<Camera>();
- cameraNode->SetPosition(Vector3(0.0f, 0.3f, -3.0f));
- GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, helloScene_, camera));
- }
- \endcode
- Unlike in script, where properties were used to set the component values and scene node transforms, here we must use setter functions instead. Also, whereas strings were used in script to identify the components to create, here it is most convenient to use the template form of \ref Node::CreateComponent "CreateComponent()":
- The text overlay creation is next. Again, setters are used throughout:
- \code
- void HelloWorld::CreateText()
- {
- SharedPtr<Text> helloText(new Text(context_));
- helloText->SetFont(cache_->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30);
- helloText->SetText("Hello World from Urho3D");
- helloText->SetColor(Color(0.0f, 1.0f, 0.0f));
- helloText->SetHorizontalAlignment(HA_CENTER);
- helloText->SetVerticalAlignment(VA_CENTER);
- GetSubsystem<UI>()->GetRoot()->AddChild(helloText);
- }
- \endcode
- Finally we get to event subscribing and handling.
- \code
- void HelloWorld::SubscribeToEvents()
- {
- SubscribeToEvent(E_UPDATE, HANDLER(HelloWorld, HandleUpdate));
- }
- \endcode
- The helper macro HANDLER is used to create pointers to the event handler member functions: it takes the class name followed by the function name. Note also that unlike script, where events and event parameters are identified with strings, in C++ precalculated hash constants are used instead. The frame update event is defined in CoreEvents.h.
- In C++ the event handler function must always have the signature "void HandleEvent(StringHash eventType, VariantMap& eventData)". Note that when accessing event parameters, the event's name is used as a namespace to prevent name clashes:
- \code
- void HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)
- {
- float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
- if (GetSubsystem<Input>()->GetKeyDown(KEY_ESC))
- GetSubsystem<Engine>()->Exit();
- }
- \endcode
- Now you should be ready to compile HelloWorld.cpp. The resulting executable will be placed in the Bin directory. It should be substantially smaller than the Urho3D application due to leaving out the scripting functionality.
- For a more complex C++ example, check out CharacterDemo in the Extras directory, which creates the same static scene as the TestScene script example, and demonstrates a 1st/3rd person controllable character. To enable it in the build, uncomment from the bottom of the root CMakeLists.txt.
- \page EditorInstructions Editor instructions
- The Urho3D editor is a script application that can be run with the Urho3D main executable. To start, execute either of these commands: (in the Bin directory) Editor.bat or Urho3D Scripts/Editor.as
- Hint: to get some content to look at, run the TestScene example, and press F5. This saves a scene file called TestScene.xml into the Data/Scenes subdirectory, which can be loaded in the editor. The NinjaSnowWar scene also exists in the Data/Scenes subdirectory, and the NinjaSnowWar object "prefabs" are in the Data/Objects subdirectory.
- \section EditorInstructions_Controls Controls
- \verbatim
- Left mouse - Select nodes or drag the node transform gizmo. Hold Shift to
- select components instead. Hold Ctrl to multiselect.
- Right mouse - Hold down and move mouse to rotate camera
- WSAD or arrows - Move
- Shift+WSAD - Move faster
- Ctrl+1,2,3 - Object manipulation mode: move/rotate/scale
- Ctrl+4 - Object selection mode, no manipulation
- Ctrl+5 - Toggle between world and local axes manipulation
- Ctrl+6,7 - Cycle through components to pick: geometries, lights, zones,
- collision shapes; and ui-elements
- Ctrl+arrows - Manipulate node in X & Z directions
- Ctrl+pgup/pgdn - Manipulate node in Y direction
- Ctrl+plus/minus - Scale node uniformly (scale mode only)
- Ctrl+Shift+N - New scene
- Ctrl+O - Open scene
- Ctrl+S - Save scene
- Ctrl+Shift+S - Save scene as
- Ctrl+A - Select/deselect all root level nodes
- Ctrl+X,C,V - Cut/copy/paste node or component
- Ctrl+E - Enable/disable node hierarchy or component
- Ctrl+U - Unparent scene node
- Ctrl+H - Open the scene hierarchy window
- Ctrl+I - Open the attribute inspector window
- Ctrl+P - Toggle scene update on/off
- Ctrl+W - Cycle through solid, wireframe and point rendering
- Ctrl+Z - Undo
- Ctrl+Y - Redo
- ESC - Close the file selector or editor settings window
- DEL - Delete node or component
- F1 - Toggle console
- F2 - Toggle rendering debug geometry
- F3 - Toggle physics debug geometry
- F4 - Toggle octree debug geometry
- \endverbatim
- Press right mouse button in the 3D view if you want to defocus the active window without changing the object selection.
- \section EditorInstructions_Workflow Workflow
- When you start with an empty scene, set the resource path first (%File -> %Set resource path). This is the base directory, under which the subdirectories Models, Materials & Textures will be created as you import assets.
- Scenes should be saved either into this base directory, or into its immediate subdirectory, named for example Scenes or Levels. When loading a scene, the resource path will be set automatically.
- Check the Editor settings window so that the camera parameters match the size of the objects you are using.
- The editor settings will be saved on exit to a file Urho3D\Editor\Config.xml in the My Documents directory. Delete this file if you want to revert the settings to defaults.
- \section EditorInstructions_Editing Editing
- New scene nodes and components are created from the Create menu at the top. Their attributes can then be edited in the attribute inspector window. Note that the node transform shown is the local transform (offset from parent.)
- As an alternative to using the transform gizmo, scene nodes can be moved/rotated/scaled by Ctrl + arrow keys and Page Up / Page Down. Press Ctrl+1,2,3 to change the manipulation mode, and Ctrl+4 to toggle between world relative and scene node relative movement.
- To reparent scene nodes, drag and drop them onto the new parent scene node in the scene hierarchy window. Reparenting should retain the effective world transform, so check afterwards from the component window that the local transform is what you expect it to be. Components can not be dragged between nodes, but can be duplicated with cut/copy/paste operations.
- Though Urho3D supports setting a non-identity transform on the root node (scene), it is still best to leave it at identity (position 0, 0, 0, rotation 0, 0, 0, scale 1, 1, 1.)
- To create a user variable into the current node, or delete it, type the variable name into the edit field below the node attributes, and press New or Del buttons next to it. The New button will prompt to choose the variable type.
- While editing, you can execute script files using the "Run script" item in the %File menu. These are AngelScript files that are executed in immediate mode ie. you do not need to define a function. The editor's scene will be accessible to the script as the global property "scene."
- Components of same type can be multi-edited. Where attribute values differ, the attribute field will be left blank, but editing the attribute will apply the change to all components.
- In addition to whole scenes, single scene nodes including all their components and child nodes can be loaded and saved (%File -> Load node, %File -> Save node as.) These can act as "prefabs" for speeding up scene construction. To save a node, it needs first to be selected in the hierarchy window.
- Primitive geometries (boxes, spheres, cylinders) can be instantiated from the Create menu. Note that these are just ordinary model files in the Bin/Data/Models directory; their Blender format source files are in the SourceAssets directory.
- \section EditorInstructions_Importing Importing
- The editor can import models or scenes from all the formats that the Open Asset Import Library supports, see http://assimp.sourceforge.net/main_features_formats.html
- %Model and scene import work differently: model import will take everything in the source file (for example a Collada scene), and combine it into a single model, with possibly many subgeometries. %Scene import on the other hand will export each source scene node separately, creating multiple models as necessary.
- When a model is imported, it will also be instantiated into the scene as a new scene node with a StaticModel component.
- To do the actual importing, the editor will invoke AssetImporter from the same directory where the Urho3D application was run from, so be sure both are built.
- If the imported scene has no lights, a single directional light is created, so that you can at least see something.
- */
- }
|