GettingStarted.dox 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /**
  2. \page Building Building Urho3D
  3. \section Building_Prerequisites Building prerequisites
  4. 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:
  5. - For Windows, the DirectX SDK needs to be installed and its include and library directories set as Visual Studio global directories (Tools -> Options -> Projects and Solutions -> VC++ Directories in VS2008.)
  6. - For Linux, the following development packages need to be installed: libx11-dev, libxrandr-dev, libasound2-dev. Also install the package libgl1-mesa-dev if your GPU driver does not include OpenGL headers & libs.
  7. - For Mac OS X, the Xcode developer tools package should include everything necessary.
  8. \section Building_BuildProcess Build process
  9. Urho3D uses CMake (http://www.cmake.org) to build. The process has two steps:
  10. 1) Run CMake in the root directory with your preferred toolchain specified to generate the build files. You can use the batch files or shell scripts provided: cmake_vs2008.bat or cmake_vs2010.bat on Windows, and cmake_gcc.sh on Linux and Mac OS X.
  11. 2) For Visual Studio, open Urho3D.sln and build the configuration(s) you like. For gcc, execute make (by default, cmake_gcc.sh specifies to make a RelWithDebInfo build.)
  12. The build process will also compile models and shaders from the Source_Asset directory into Bin/Data/Models & Bin/Data/Shaders. After the build is complete, the programs can be run from the Bin directory.
  13. When using Xcode on Mac OS X, select Project -> %Set Active Architecture -> i386 before building. Compiling Urho3D as 64-bit is not supported.
  14. To run Urho3D from the Visual Studio debugger, set it as a 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.
  15. To actually make Urho3D.exe 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/TestScene.as -w
  16. \page Running Running Urho3D
  17. For Windows & Direct3D9 mode, Urho3D requires Windows XP or newer, DirectX 9.0c, and a display adapter with SM2.0 support. SM3.0 is highly recommended. For OpenGL mode, an OpenGL 2.0 capable display adapter with EXT_framebuffer_object, EXT_packed_depth_stencil and EXT_texture_filter_anisotropic extensions is required.
  18. The main executable Urho3D.exe in the Bin directory contains all the engine runtime functionality. However, it does not contain any inbuilt logic or application, and therefore must be supplied with the name of the application script file it should run:
  19. Urho3D.exe <scriptfilename> [options]
  20. The scripting language used is AngelScript (http://www.angelcode.com/angelscript); the script files have .as extension and need to be placed under either the Data or CoreData subdirectories so that Urho3D.exe 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.
  21. Currently, five example application scripts exist:
  22. \section Running_TestScene TestScene
  23. Rendering, physics and serialization test. To start, run TestScene.bat in the Bin directory, or use the command Urho3D.exe Scripts/TestScene.as
  24. Key and mouse controls:
  25. \verbatim
  26. WSAD Move
  27. Left mouse Create a new physics object
  28. Right mouse Hold and move mouse to rotate view
  29. Space Toggle debug geometry
  30. F1 Toggle AngelScript console
  31. F5 Save scene
  32. F7 Load scene
  33. 1 to 9 Toggle rendering options
  34. T Toggle profiling display
  35. C Toggle orthographic camera
  36. F Toggle FXAA edge filter
  37. B Toggle bloom post-process
  38. \endverbatim
  39. 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
  40. There is also a variation of TestScene ported from Urho3D 1.0, TestSceneOld. It lacks networking features, but is provided for examining backward compatibility and performance. It can be run with TestSceneOld.bat or by using the command Urho3D.exe Scripts/TestSceneOld.as
  41. \section Running_NinjaSnowWar NinjaSnowWar
  42. A third-person action game. To start, run NinjaSnowWar.bat in the Bin directory, or use the command Urho3D.exe Scripts/NinjaSnowWar.as
  43. Key and mouse controls:
  44. \verbatim
  45. WSAD Move
  46. Left mouse Attack
  47. Space Jump
  48. F1 Toggle AngelScript console
  49. F2 Toggle physics debug geometry
  50. F3 Toggle profiling display
  51. F4 Toggle octree debug geometry
  52. \endverbatim
  53. 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
  54. \section Running_Chat Chat
  55. Simple client-server chat test application. To start, run Chat.bat or ChatServer.bat in the Bin directory, or use the command Urho3D.exe Scripts/Chat.as
  56. On the client, first type the server address to the text edit box and click "Connect." After connecting successfully you can start typing messages;
  57. either press return or click "Send" to send them. Press ESC to exit.
  58. To connect automatically, the server address can also be given on the command line, for example Chat.bat 127.0.0.1
  59. \section Running_Editor Editor
  60. %Scene editor application written in script. To start, run Editor.bat, or use the command Urho3D.exe Scripts/Editor.as
  61. For details on how to use the editor, see \ref EditorInstructions "Editor instructions."
  62. \section Running_LightTest LightTest
  63. %Light rendering performance test. To start, run LightTest.bat in the Bin directory, or use the command Urho3D.exe Scripts\LightTest.as
  64. Key and mouse controls:
  65. \verbatim
  66. WSAD Move
  67. ZX Select model to use
  68. Arrows Add or remove lights and objects
  69. Pageup/down Add or remove 10 lights
  70. Right mouse Hold and move mouse to rotate view
  71. F1 Toggle AngelScript console
  72. 1 to 9 Toggle rendering options
  73. T Toggle profiling display
  74. V Toggle vertex lighting
  75. C Toggle orthographic camera
  76. F Toggle FXAA edge filter
  77. R Re-randomize light and object positions
  78. \endverbatim
  79. \section Running_Commandline Command line options
  80. Urho3D.exe understands the following command line options:
  81. \verbatim
  82. -x<res> Horizontal resolution
  83. -y<res> Vertical resolution
  84. -m<level> Enable hardware multisampling
  85. -v Enable vertical sync
  86. -t Enable triple buffering
  87. -w Start in windowed mode
  88. -b<length> Sound buffer length in milliseconds
  89. -r<freq> Sound mixing frequency in Hz
  90. -headless Headless mode. No application window will be created
  91. -logdebug Display debug level log messages also in release mode
  92. -prepass Use light pre-pass rendering
  93. -deferred Use deferred rendering
  94. -lqshadows Use low-quality (1-sample) shadow filtering
  95. -noshadows Disable shadow rendering
  96. -nolimit Disable frame limiter
  97. -nothreads Disable worker threads
  98. -nosound Disable sound output
  99. -noip Disable sound mixing interpolation
  100. -sm2 Force SM2.0 rendering
  101. \endverbatim
  102. \page Structure Overall structure
  103. 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.
  104. The libraries are the following:
  105. - Container. Provides STL replacement classes and shared pointers.
  106. - Math. Provides vector & quaternion types and geometric shapes used in intersection tests.
  107. - Core. Provides the execution Context, the base class Object for typed objects, object factories, \ref Event "event handling", threading and profiling.
  108. - IO. Provides file system access, stream input/output and logging.
  109. - %Resource. Provides the ResourceCache and the base resource types, including XML documents.
  110. - %Scene. Provides Node and Component classes, from which Urho3D scenes are built.
  111. - %Graphics. Provides application window handling and 3D rendering capabilities.
  112. - %Input. Provides mouse & keyboard input in both polled and event-based mode.
  113. - %Network. Provides client-server networking functionality.
  114. - %Audio. Provides the audio subsystem and playback of .wav & .ogg sounds in either 2D or 3D.
  115. - Physics. Provides physics simulation.
  116. - %Script. Provides scripting support using the AngelScript language.
  117. - %Engine. Instantiates the subsystems from the libraries above, and manages the main loop iteration.
  118. Urho3D.exe uses just the Engine & Script libraries to start up the subsystems and to load the script file specified on the command line; however all of the libraries above get automatically linked as Engine library depends on all of them.
  119. Although Urho3D.exe itself is geared towards running a scripted application, it is also possible to use the engine through C++ only. When the scripting subsystem initialization is completely skipped, the resulting executable will also be significantly smaller.
  120. The third-party libraries are used for the following functionality:
  121. - AngelScript: scripting language implementation
  122. - Bullet: physics simulation implementation
  123. - FreeType: font rendering
  124. - GLee: OpenGL extensions handling
  125. - GLFW: low-level windowing and input on Linux and Mac OS X, and on Windows when running in OpenGL mode
  126. - kNet: UDP networking
  127. - libcpuid: CPU properties detection
  128. - Open Asset Import Library: reading various 3D file formats
  129. - PortAudio: audio playback on Linux and Mac OS X
  130. - pugixml: parsing XML files
  131. - Squish: decompressing DXT images when not supported by hardware
  132. - StanHull: convex hull generation from triangle meshes, used for physics collision shapes
  133. - stb_image: image loading
  134. - stb_vorbis: Ogg Vorbis decoding
  135. \page Conventions Conventions
  136. Urho3D uses the following conventions and principles:
  137. - Left-handed coordinates. Positive X, Y & Z axes point to the right, up, and forward, and positive rotation is clockwise.
  138. - Degrees are used for angles.
  139. - Clockwise vertices define a front face.
  140. - %Audio volume is specified from 0.0 (silence) to 1.0 (full volume)
  141. - Path names use slash instead of backslash. Paths will be converted internally into the necessary format when calling into the operating system.
  142. - 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.
  143. - 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.
  144. - 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.
  145. - 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.
  146. - For threading and multi-instance safety, no mutable static data (including singletons) or function-static data is allowed.
  147. - Third party libraries are included as source code for the build process. They are however hidden from the public API as completely as possible.
  148. For more details related to the C++ coding style, see also \ref CodingConventions "Coding conventions".
  149. \page ScriptQuickstart Quickstart in script
  150. In the following example, a minimal "Hello World" application with both 3D and user interface content will be built.
  151. We start by defining the Start() function required in all Urho3D script applications. When Urho3D.exe executes it, all the engine subsystems are already in place, so any initialization that needs to be done is specific to the application itself.
  152. \code
  153. Scene@ helloScene;
  154. void Start()
  155. {
  156. helloScene = Scene();
  157. CreateObjects();
  158. CreateText();
  159. SubscribeToEvents();
  160. }
  161. \endcode
  162. 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.)
  163. 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.
  164. 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()".
  165. 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.
  166. \code
  167. void CreateObjects()
  168. {
  169. helloScene.CreateComponent("Octree");
  170. Node@ objectNode = helloScene.CreateChild();
  171. Node@ lightNode = helloScene.CreateChild();
  172. Node@ cameraNode = helloScene.CreateChild();
  173. StaticModel@ object = objectNode.CreateComponent("StaticModel");
  174. object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  175. object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  176. Light@ light = lightNode.CreateComponent("Light");
  177. light.lightType = LIGHT_DIRECTIONAL;
  178. lightNode.direction = Vector3(-1, -1, -1);
  179. Camera@ camera = cameraNode.CreateComponent("Camera");
  180. cameraNode.position = Vector3(0, 0.3, -3);
  181. renderer.viewports[0] = Viewport(helloScene, camera);
  182. }
  183. \endcode
  184. 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.
  185. 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.
  186. 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.
  187. 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.
  188. 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.
  189. The camera's scene node is pulled back along the Z-axis to be able to see the object.
  190. 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.
  191. The 3D content is now finished. Next, we create the user interface content in CreateText().
  192. \code
  193. void CreateText()
  194. {
  195. Text@ helloText = Text();
  196. helloText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30);
  197. helloText.text = "Hello World from Urho3D";
  198. helloText.color = Color(0, 1, 0);
  199. helloText.horizontalAlignment = HA_CENTER;
  200. helloText.verticalAlignment = VA_CENTER;
  201. ui.root.AddChild(helloText);
  202. }
  203. \endcode
  204. 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.
  205. Finally we subscribe to necessary Urho3D events in the SubscribeToEvents() function.
  206. \code
  207. void SubscribeToEvents()
  208. {
  209. SubscribeToEvent("Update", "HandleUpdate");
  210. }
  211. \endcode
  212. 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.
  213. 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.
  214. \code
  215. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  216. {
  217. float timeStep = eventData["TimeStep"].GetFloat();
  218. if (input.keyPress[KEY_ESC])
  219. engine.Exit();
  220. }
  221. \endcode
  222. 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 application window and causes Urho3D.exe to exit after the current main loop iteration finishes.
  223. 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.
  224. The example application is now complete. To try it out, save it as HelloWorld.as in the Bin/Data/Scripts directory, then run Urho3D.exe Scripts/HelloWorld.as
  225. \page CppQuickstart Quickstart in C++
  226. 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.
  227. For simplicity, the application is assumed to be compiled on Windows and therefore defines the WinMain() function; look at the file Urho3D.cpp in the Urho3D subdirectory on how to handle cross-platform startup. Basically, when not on Windows, you would define a main() function instead.
  228. To start with, create a subdirectory "HelloWorld" into the Urho3D root directory, and add the following line to the root directory's CMakeLists.txt %file:
  229. \code
  230. add_subdirectory (HelloWorld)
  231. \endcode
  232. Then, create the following CMakeLists.txt file into the HelloWorld directory (mostly copied from CMakeLists.txt of Urho3D.exe):
  233. \code
  234. # Define target name
  235. set (TARGET_NAME HelloWorld)
  236. # Define source files
  237. file (GLOB CPP_FILES *.cpp)
  238. file (GLOB H_FILES *.h)
  239. set (SOURCE_FILES ${CPP_FILES} ${H_FILES})
  240. # Include directories
  241. include_directories (
  242. ../Engine/Container ../Engine/Core ../Engine/Engine ../Engine/Graphics ../Engine/Input ../Engine/IO
  243. ../Engine/Math ../Engine/Resource ../Engine/Scene ../Engine/UI
  244. )
  245. # Define target & libraries to link
  246. add_executable (${TARGET_NAME} WIN32 ${SOURCE_FILES})
  247. target_link_libraries (${TARGET_NAME} Container Core Engine Graphics Input IO Math Resource Scene UI)
  248. finalize_exe ()
  249. \endcode
  250. 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.
  251. To start with, we need the include files for all the engine classes we are going to use, plus Windows.h for the WinMain function:
  252. \code
  253. #include "Camera.h"
  254. #include "Context.h"
  255. #include "CoreEvents.h"
  256. #include "Engine.h"
  257. #include "Font.h"
  258. #include "Input.h"
  259. #include "Light.h"
  260. #include "Material.h"
  261. #include "Model.h"
  262. #include "Octree.h"
  263. #include "ProcessUtils.h"
  264. #include "Renderer.h"
  265. #include "ResourceCache.h"
  266. #include "Scene.h"
  267. #include "StaticModel.h"
  268. #include "Text.h"
  269. #include "UI.h"
  270. #include <Windows.h>
  271. \endcode
  272. 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 WinMain, 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:
  273. \code
  274. class HelloWorld : public Object
  275. {
  276. OBJECT(HelloWorld);
  277. public:
  278. HelloWorld(Context* context);
  279. void Start();
  280. void CreateObjects();
  281. void CreateText();
  282. void SubscribeToEvents();
  283. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  284. SharedPtr<Scene> helloScene_;
  285. SharedPtr<ResourceCache> cache_;
  286. };
  287. \endcode
  288. Before the actual HelloWorld implementation, we define WinMain.
  289. \code
  290. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
  291. {
  292. SharedPtr<Context> context(new Context());
  293. SharedPtr<Engine> engine(new Engine(context));
  294. engine->Initialize("HelloWorld", "HelloWorld.log", ParseArguments(GetCommandLineW()));
  295. SharedPtr<HelloWorld> helloWorld(new HelloWorld(context));
  296. helloWorld->Start();
  297. while (!engine->IsExiting())
  298. engine->RunFrame();
  299. return 0;
  300. }
  301. \endcode
  302. First, we 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.
  303. With the context at hand, we create the Engine and initialize it. The arguments for the \ref Engine::Initialize "Initialize()" function are the initial window title, the log file name, and command line parameters, which are parsed using the ParseArguments() helper function.
  304. 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.
  305. Now we can start implementing HelloWorld.
  306. \code
  307. OBJECTTYPESTATIC(HelloWorld);
  308. HelloWorld::HelloWorld(Context* context) :
  309. Object(context),
  310. cache_(GetSubsystem<ResourceCache>())
  311. {
  312. }
  313. \endcode
  314. Note the OBJECTTYPESTATIC(className) macro, which creates the static type name and type name hash for object type identification. For each OBJECT macro, a matching OBJECTTYPESTATIC must appear in a .cpp file.
  315. During construction, we only store the ResourceCache subsystem pointer for later access.
  316. In the Start() function the Scene will be created:
  317. \code
  318. void HelloWorld::Start()
  319. {
  320. helloScene_ = new Scene(context_);
  321. CreateObjects();
  322. CreateText();
  323. SubscribeToEvents();
  324. }
  325. \endcode
  326. Like in the script example, CreateObjects() does the actual scene object creation and defines the viewport.
  327. \code
  328. void HelloWorld::CreateObjects()
  329. {
  330. helloScene_->CreateComponent<Octree>();
  331. Node* objectNode = helloScene_->CreateChild();
  332. Node* lightNode = helloScene_->CreateChild();
  333. Node* cameraNode = helloScene_->CreateChild();
  334. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  335. object->SetModel(cache_->GetResource<Model>("Models/Mushroom.mdl"));
  336. object->SetMaterial(cache_->GetResource<Material>("Materials/Mushroom.xml"));
  337. Light* light = lightNode->CreateComponent<Light>();
  338. light->SetLightType(LIGHT_DIRECTIONAL);
  339. lightNode->SetDirection(Vector3(-1.0f, -1.0f, -1.0f));
  340. Camera* camera = cameraNode->CreateComponent<Camera>();
  341. cameraNode->SetPosition(Vector3(0.0f, 0.3f, -3.0f));
  342. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(helloScene_, camera));
  343. }
  344. \endcode
  345. 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()":
  346. The text overlay creation is next. Again, setters are used throughout:
  347. \code
  348. void HelloWorld::CreateText()
  349. {
  350. SharedPtr<Text> helloText(new Text(context_));
  351. helloText->SetFont(cache_->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30);
  352. helloText->SetText("Hello World from Urho3D");
  353. helloText->SetColor(Color(0.0f, 1.0f, 0.0f));
  354. helloText->SetHorizontalAlignment(HA_CENTER);
  355. helloText->SetVerticalAlignment(VA_CENTER);
  356. GetSubsystem<UI>()->GetRoot()->AddChild(helloText);
  357. }
  358. \endcode
  359. Finally we get to event subscribing and handling.
  360. \code
  361. void HelloWorld::SubscribeToEvents()
  362. {
  363. SubscribeToEvent(E_UPDATE, HANDLER(HelloWorld, HandleUpdate));
  364. }
  365. \endcode
  366. 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.
  367. 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:
  368. \code
  369. void HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)
  370. {
  371. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  372. if (GetSubsystem<Input>()->GetKeyDown(KEY_ESC))
  373. GetSubsystem<Engine>()->Exit();
  374. }
  375. \endcode
  376. 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 Urho3D.exe due to leaving out the scripting functionality.
  377. \page EditorInstructions Editor instructions
  378. The Urho3D scene 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.exe Scripts/Editor.as
  379. Hint: to get some content to look at, run the TestScene example, and press F5. This saves a scene file called Scene.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.
  380. \section EditorInstructions_Controls Controls
  381. \verbatim
  382. Left mouse - Select nodes or drag the node transform gizmo. Hold Shift to
  383. select components instead. Hold Ctrl to multiselect.
  384. Right mouse - Hold down and move mouse to rotate camera
  385. WSAD or arrows - Move
  386. Shift+WSAD - Move faster
  387. Ctrl+1,2,3 - Select manipulation mode: move/rotate/scale
  388. Ctrl+4 - Toggle between world and local axes manipulation
  389. Ctrl+5,6 - Cycle through components to pick: geometries, lights, zones,
  390. collision shapes
  391. Ctrl+arrows - Manipulate node in X & Z directions
  392. Ctrl+pgup/pgdn - Manipulate node in Y direction
  393. Ctrl+plus/minus - Scale node uniformly (scale mode only)
  394. Ctrl+O - Open scene
  395. Ctrl+S - Save scene
  396. Ctrl+Shift+S - Save scene as
  397. Ctrl+A - Select/deselect all root level nodes
  398. Ctrl+X,C,V - Cut/copy/paste node or component
  399. Ctrl+U - Unparent scene node
  400. Ctrl+H - Open the scene hierarchy window
  401. Ctrl+N - Open the node / component edit window
  402. Ctrl+P - Toggle scene update on/off
  403. Ctrl+R - Reload scene resources
  404. ESC - Close the file selector or editor settings window
  405. DEL - Delete node or component
  406. F1 - Toggle console
  407. F2 - Toggle rendering debug geometry
  408. F3 - Toggle physics debug geometry
  409. F4 - Toggle octree debug geometry
  410. \endverbatim
  411. Press right mouse button in the 3D view if you want to defocus the active window without changing the object selection.
  412. \section EditorInstructions_Workflow Workflow
  413. 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.
  414. 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.
  415. Check the Editor settings window so that the camera parameters match the size of the objects you are using.
  416. 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.
  417. \section EditorInstructions_Editing Editing
  418. New scene nodes and components are created with the buttons at the bottom of the hierarchy window. Their attributes can then be edited in the node / component edit window. Note that the node transform shown is the local transform (offset from parent.)
  419. %Scene nodes can also 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.
  420. 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.
  421. 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.)
  422. 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.
  423. 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."
  424. Automatic resource reloading when changed (for example editing a texture in a paint program while the scene editor is running) is currently supported on Windows only. On other platforms you need to manually reload scene resources (Ctrl+R) after editing to make the changes visible.
  425. 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.
  426. 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.
  427. \section EditorInstructions_Importing Importing
  428. 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
  429. %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.
  430. When a model is imported, it will also be instantiated into the scene as a new scene node with a StaticModel component.
  431. To do the actual importing, the editor will invoke AssetImporter.exe from the same directory as where Urho3D.exe resides, so be sure both are built.
  432. Importing lights is not properly supported yet. Instead, when a scene is imported, a zone for ambient lighting and a single directional light are created, so that you can at least see something.
  433. */