{"id":168,"date":"2020-04-05T08:16:20","date_gmt":"2020-04-05T08:16:20","guid":{"rendered":"https:\/\/sgarces.com\/?p=168"},"modified":"2020-04-05T08:16:20","modified_gmt":"2020-04-05T08:16:20","slug":"the-forest","status":"publish","type":"post","link":"https:\/\/sgarces.com\/?p=168","title":{"rendered":"The Forest"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1000\" height=\"476\" loading=\"lazy\" src=\"https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/forest_for_the_trees.jpg?resize=1000%2C476&#038;ssl=1\" alt=\"\" class=\"wp-image-184\" srcset=\"https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/forest_for_the_trees.jpg?w=1000&amp;ssl=1 1000w, https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/forest_for_the_trees.jpg?resize=300%2C143&amp;ssl=1 300w, https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/forest_for_the_trees.jpg?resize=768%2C366&amp;ssl=1 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">When I started using <em>Unreal<\/em> I had experience with several in-house engines as well as <em>Unity<\/em>. There are a number of concepts that are common to almost all engines and, once you understand them, you come to expect them and rely on them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I couldn&#8217;t find a good resource that would break down how <em>Unreal<\/em> implements these common concepts. Often, people talk about how to do simple things (like getting a character up on screen) or describe the parts <em>Unreal<\/em> consists of, without explaining how they typically get used.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What I want to do here is to write the high-level view of how I&#8217;m using <em>Unreal<\/em>&#8216;s architecture. It&#8217;s important to play nice with the engine (fitting a round peg in a square box is a bad idea) while building an architecture that will scale to the scope of your game. This article forgets the trees and focuses on the <em>forest<\/em>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Starting from the Top<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There is a big difference between a <em>tech demo<\/em> and a <em>game<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your project doesn&#8217;t have multiple screens, if it doesn&#8217;t have a way to save game state, if it doesn&#8217;t have many different game modes, if it doesn&#8217;t have loading screens or streaming, then it&#8217;s a tech demo and you have a lot of work ahead of you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Almost every game has an object (often a Singleton) that represents the entire game. This object persists across screens and modes and serves as the connective tissue for the entire experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In <em>Unreal<\/em> the easiest way to fulfill this role is to subclass <em><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/API\/Runtime\/Engine\/Engine\/UGameInstance\/index.html\" target=\"_blank\">UGameInstance<\/a><\/em>. This object is created early when the game boots, and the function <em>Init()<\/em> gets called. It will survive through level changes and can be easily accessed from the World object.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><em>Note that the simple examples that come with Unreal <strong>don&#8217;t<\/strong> do this. They just set up a Game Mode (which we&#8217;ll discuss later) because they are tech demos.<\/em><\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">After you create your <em>Game Instance<\/em>, you want to be able to access it easily. A nice way to do it is to create a static function in C++ and expose it to Blueprints are a Pure function:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">UFUNCTION(BlueprintPure, Category=\"Game\", meta=(WorldContext=\"WorldContextObject\"))\nstatic UMyGameInstance* GetMyGameInstance(const UObject* WorldContextObject);\n\nUMyGameInstance* UMyGameInstance::GetMyGameInstance(const UObject* WorldContextObject)\n{\n\tUGameInstance* gameInstance = UGameplayStatics::GetGameInstance(WorldContextObject);\n\treturn Cast<UMyGameInstance>(gameInstance);\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This will give you the same interface <em>Unreal<\/em> <a href=\"https:\/\/docs.unrealengine.com\/en-US\/BlueprintAPI\/Game\/GetGameInstance\/index.html\" target=\"_blank\" rel=\"noreferrer noopener\">provides<\/a>: <img data-recalc-dims=\"1\" decoding=\"async\" width=\"200\" height=\"89\" loading=\"lazy\" class=\"wp-image-172\" style=\"width: 200px;\" src=\"https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/image-1.png?resize=200%2C89&#038;ssl=1\" alt=\"\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s some of the functionality I have in the <em>Game Instance<\/em> (and therefore accessible to the entire game):<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Load levels, including holding information the level will need<\/li><li>Keep user&#8217;s game state (including saving and restoring)<\/li><li>Control screen transitions and history<\/li><li>Expose configuration from <em><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/Gameplay\/DataDriven\/index.html\" target=\"_blank\">DataTables<\/a><\/em> and <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/Engine\/Blueprints\/Editor\/UIBreakdowns\/DataOnlyUI\/index.html\" target=\"_blank\"><em>Data-only<\/em> <em>Blueprints<\/em><\/a><\/li><li>Remember whether a Gamepad is being used or not<\/li><li>Collect telemetry for data analysis and replays<\/li><li>Manage shared <em><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/Engine\/Rendering\/RenderTargets\/index.html\" target=\"_blank\">Render Targets<\/a><\/em> (thumbnails used throughout the game)<\/li><li>Provide deterministic random numbers for procedural generation<\/li><li>Whatever else is convenient<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Not all of this functionality lives on the one <em>Game Instance<\/em> class. You can easily create individual classes that you then access through the <em>Game Instance<\/em> pointer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One note about the <em>Game Instance<\/em> in <em>Unreal<\/em> is that it&#8217;s not a true Singleton, in the typical C++ sense of a static object. In fact, if you run in PIE (play-in-editor) mode, there will be one per PIE instance. Keep this in mind as you will need a trail to be able to access it from <em>UObject<\/em>&#8216;s that don&#8217;t live in the World: either pass a World context as a parameter in a function call, or establish a relationship with an Actor or Widget that has access to the World.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Another implication of how <em>Game Instances<\/em> work is that if you end up storing something in a static variable, it will survive across PIE runs, which is probably not what you want. If it must be static, set it during <em>Init() <\/em>and reset it during <em>Shutdown()<\/em>, but expect that multiple PIE instances will still share it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Managing Screens<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now that we have a way to control the flow from one screen to the next, the question is: what&#8217;s in a screen? To answer that question let&#8217;s talk about how <em>Unreal<\/em> does UI (user interface).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Unreal<\/em>&#8216;s preferred way to do UI is by using <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/Engine\/UMG\/index.html\" target=\"_blank\">UMG<\/a> (<em>Unreal Motion Graphics<\/em>) which is a wrapper around their native system, called <em>Slate<\/em>. UMG provides visual tools to structure your UI screens and if you&#8217;re using <em>Unreal Editor<\/em> to create UI, you&#8217;re using UMG.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A big difference between <em>Unreal<\/em> and <em>Unity<\/em> relates to how UI is structured. In <em>Unity<\/em> everything is a <em>GameObject<\/em>, whether it&#8217;s a character running around on screen or a UI button. On the other hand, while both the character and the button will be <em>UObject<\/em>s in <em>Unreal<\/em>, the first one will be an <em>AActor<\/em> while the second one will be a <em>UWidget<\/em>. <em>AActor<\/em>s and <em>UWidget<\/em>s effectively live in two different contexts (actors in the level, widgets in the viewport) which means you can combine them however you want. One disadvantage is that passing information from one context to the other can be cumbersome.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For my purposes, I consider a screen is a UI Blueprint (derived from <em>UUserWidget<\/em>) which will include all the functionality of the screen and control the widgets contained within. For instance, if I need an inventory screen I&#8217;d derive a C++ class from <em>UUserWidget<\/em> (e.g. <em>UInventoryScreen<\/em>), add references to its parts using <em><a href=\"http:\/\/benhumphreys.ca\/unreal\/ui-bindwidget\/\" target=\"_blank\" rel=\"noreferrer noopener\">BindWidget<\/a><\/em> and write code to populate it and handle events like selecting one of the items.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With this in mind, let&#8217;s consider two scenarios and see how we could approach them:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>The UI covers the entire screen<\/strong>, the gameplay world is only visible during a mission. A sensible structure would be to have a single empty level for all the UI and swap screens by changing the UI Blueprint that sits on the viewport. Note you can still present 3D assets using Render to Texture.<\/li><li><strong>The UI lives in a 3D world<\/strong> or lets the player see the 3D world through it. If switching screens means going from a 3D environment to another, you&#8217;ll need to have multiple levels (unless you want to use sublevels) and changing screens will typically involve changing both the level and the UI Blueprint on the viewport.<\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The second approach is more flexible, but will lead to longer waits when going from screen to screen, so if having the UI feel very fast and responsive is a priority consider limiting the amount of level switching involved.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll imaginatively call the system responsible to control screen flow the <em>UScreenManager<\/em>. It contains the definitions of all the screens (level name, UI Blueprint) as well as a stack of screens, to support transitions as well as going back. Pushing a screen from code is as simple as using the id of that screen and passing some (optional) contextual information. This is roughly what the code looks like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">void UScreenManager::Push(EScreen screen, const FScreenData&amp; data)\n{\n\tScreenStack.Emplace(screen, data);\n\tconst FScreenDef* screenDef = Find(screen);\n\tUGameplayStatics::OpenLevel(this, screenDef-&gt;LevelName); \/\/ this is asynchronous\n}\n\n\/\/ registered with FCoreUObjectDelegates::PostLoadMapWithWorld.AddUObject(this, &amp;UScreenManager::PostLevelLoad);\nvoid UScreenManager::PostLevelLoad(UWorld* World)\n{\n\tconst FScreenDef* screenDef = GetTopScreenDef();\n\tUUserWidget* screenWidget = UWidgetBlueprintLibrary::Create(World, screenDef-&gt;Widget, World-&gt;GetFirstPlayerController());\n\tscreenWidget-&gt;AddToViewport();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Some notes about this code. First, it&#8217;s not production-ready: error checking is missing. Second, I haven&#8217;t found a robust way to store general information for the screen (<em>FScreenData<\/em>). A possible approach is to encode it in a string (maybe using JSON) but that can be inefficient, so for my game I add individual pieces of content as needed to that struct.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also there is a problem we discussed earlier: if we need to pass information from the level to the screen, the only way is for the screen to pull it doing global searches, which is not ideal. A possible solution is to use the Level Blueprint (in <em>BeginPlay<\/em>) to create the screen widget, then pass the information as needed. The downside is that it&#8217;s not a very good general approach and it requires switching maps to edit the Blueprint.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, because we get notified when the level is finished loading, we can add a loading screen and then remove it when loading completes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Show Me the Game<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The main piece and the one most people think about when they consider <em>Unreal <\/em>is the gameplay piece. As we said earlier, objects that exist in a 3D world are a type of <em>Actor<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you come from <em>Unity<\/em>, it&#8217;s theoretically possible to build the game entirely using Actor Blueprints with the right combination of components, and creating new components as necessary. That&#8217;s not the <em>Unreal way<\/em>, however. <em>Unreal<\/em> provides a <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.unrealengine.com\/en-US\/Gameplay\/Framework\/index.html\" target=\"_blank\">Gameplay Framework<\/a>, that will be extremely useful, especially if your game resembles <em>Fortnite<\/em> or <em>Gears of War<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In a nutshell, the rules for winning or losing the game belong in the <em>Game Mode<\/em> and <em>Game State<\/em> objects. All the spaceships and monsters and heroes are a <em>Pawn<\/em> or even a <em>Character<\/em> (if you want a mesh, collision and movement logic). It&#8217;s a good idea to build those so they can be driven equally by the player or the AI, so <em>Unreal <\/em>externalizes the logic that controls them into a <em>Player Controller <\/em>and an <em>AI Controller<\/em>. There are a lot more details but that&#8217;s the general idea.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each level has default types for all of these things (you can see them in the <em>World Settings<\/em> window). One can almost picture having single player levels and multiplayer levels, with different <em>Game Modes<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Another important consideration, especially if you&#8217;re used to <em>Unity<\/em>, is where the functionality lives. In <em>Unity<\/em> all the code belongs in <em>Behaviors<\/em> that attach to generic <em>GameObjects<\/em>. While this is possible in <em>Unreal<\/em> as well using <em>Components<\/em>, you can also subclass <em>AActor <\/em>(or <em>APawn<\/em> or <em>ACharacter<\/em>) and add functionality directly in that subclass. The approach you choose will depend on the type of game you&#8217;re making. If you expect a large variety of actors with different combinations of characteristics (movement, health, damage, others), then build those pieces as components. If, on the other hand, you only have a few stereotypes, you&#8217;ll avoid some overhead by writing that code in a subclass. Note that it&#8217;s not possible to use <em>Unreal<\/em> in a fully data-oriented way like <em>Unity<\/em>&#8216;s <em><a rel=\"noreferrer noopener\" href=\"https:\/\/unity.com\/dots\" target=\"_blank\">DOTS<\/a><\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I&#8217;m working on a tactics game, so I&#8217;ve deviated slightly from how a typical action game would be structured. I don&#8217;t need any of the fidelity of an action game so I don&#8217;t need the built-in movement or physics collision. But the most important difference has to do with being able to run combat simulations outside of the <em>Unreal <\/em>world. I use this to show predictions to the player so they understand their options, as well as to search for the best course of action for the AI.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The main impact of this difference is that my <em>Pawns<\/em> don&#8217;t know anything about hit points or any of the combat logic. They are simply visual puppets. The real logic lives in a separate <em>UObject<\/em> (not an <em>Actor<\/em>) that exists in a separate logic world and is extremely lightweight. I call them <em>UUnit<\/em>. They can be created, modified and destroyed quickly and frequently during simulations. To be honest, the only reason they are a <em>UObject<\/em> to begin with is to be able to expose them to Blueprints.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>UUnit<\/em>s get registered with an actor that bridges the simulation and the visual world (I call it <em>AGrid<\/em>). In this way, when the level is unloaded and the actor is destroyed all <em>UUnit<\/em>s get garbage-collected.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">More to Come<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This was an introductory overview to how I am structuring my game in <em>Unreal<\/em>. There&#8217;s a lot more to cover, and I&#8217;ll be writing about it in future posts, specifically:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>What is the right division between C++ and Blueprints<\/li><li>How to manage input: mouse, keyboard and gamepad<\/li><li>Ways of storing configuration data<\/li><li>Special considerations for making a multiplayer game<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>When I started using Unreal I had experience with several in-house engines as well as Unity. There are a number of concepts that are common to almost all engines and, once you understand them, you come to expect them and rely on them. I couldn&#8217;t find a good resource that would break down how Unreal&#8230;<\/p>\n<p class=\"more-link\"><a href=\"https:\/\/sgarces.com\/?p=168\" class=\"themebutton3\">Read More<\/a><\/p>\n","protected":false},"author":1,"featured_media":184,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[10],"tags":[2],"class_list":["post-168","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-unreal-engine","tag-ue4"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/i0.wp.com\/sgarces.com\/wp-content\/uploads\/2020\/04\/forest_for_the_trees.jpg?fit=1000%2C476&ssl=1","_links":{"self":[{"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/posts\/168","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sgarces.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=168"}],"version-history":[{"count":5,"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/posts\/168\/revisions"}],"predecessor-version":[{"id":200,"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/posts\/168\/revisions\/200"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sgarces.com\/index.php?rest_route=\/wp\/v2\/media\/184"}],"wp:attachment":[{"href":"https:\/\/sgarces.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=168"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sgarces.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=168"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sgarces.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=168"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}