What

Recently I had to create a system to make materials remember several input parameters that are changed at runtime.
For infrastructure reasons, the project needed this to be implemented without involving any “Save Game” systems, to capture all parameters from existing dynamic material instances on scenes and restore them exactly like they were left when the application quit.
It had to serialize Scalar parameters, Vector parameter, and Texture2D reference parameters without care about saving or loading back any level or info about the actors using those material instances.

So I put together a plugin that captures and restores all dynamic materials of a scene that can later be restored, for persistent game worlds and interactive ArchViz projects.
The idea was to make it feel like a “save game” system, but without using any actual save game system with dependencies to the “Game World”.
There’s a “Capture Snapshots” and a “Restore from Snapshots” node that can be used to save and restore all runtime material states from a scene.

The materials must be “Dynamic Material Instances” to work. No workflow changes or changes to existing materials are required, the target meshes just have to properly use a Dynamic Material Instance to make it work.
Scalar Parameters, Vector Parameters, Texture Param2Ds are supported by the system. I decided to make it public and publish on Marketplace, Epic Games should have it available online in their store soon.


 

How To Use

This is extremely simple to use even for non programmers.

  • Step #1, your materials assigned to the meshes must be dynamic material instances, it’s an internal shader requirement of Unreal Engine due to how materials work.
    From within your Blueprint’s Constructor Script you can do something like this to create and apply a dynamic material instance to your mesh:
  • Step #2, the base material, the one you edit in Material Editor, it should contain dynamic parameters you’re willing to be changed at runtime and that the plugin will later record and restore recorded values from.
    A very simple base material as example. “Color” vector, “Diffuse” texture, “NormalMap” texture, “Metallic” param, and “Roughness” param, are all parameters from the material below that can be changed at runtime and restored back to their changed values by the plugin even after the application was closed and then later executed again:
  • Step #3, to capture or restore material data. You just need to execute a variation of these nodes to do so.
    Capture Material Snapshots” will record every dynamic material instances and their parameters in scene.
    Restore Materials from Snapshots” will revert them instantly back to the state they were captured:

 

Note

Keep in mind that this system doesn’t make distinction of “levels” or “maps”, this is by design. A material named “MyCoolestMatInstance01” in multiple levels will be treated as one same material to be captured and restored.


 

This is now published to Unreal’s Marketplace:
https://www.unrealengine.com/marketplace/en-US/slug/persistent-dynamic-materials

Persistent Dynamic Materials (Programming)

Unreal “Magic Nodes” (Programming)

 

What:

I’ve put together a system which I call “Magic Nodes” where we can write some C++ functions in-place on any Blueprint Graph and that node will “morph” to match the input and output parameters of the function we wrote within the node itself. Reasons behind why I built this is, in part, because there’s numerous tasks where dragging wires on Blueprint Editor slows down productivity and this tool could be useful to address that, sometimes it’s simply faster to type a few lines of code instead of dealing with wire spaghetti!

With this I also hope, with time, Blueprint developers have a first contact with C++ code and slowly become comfortable moving to Visual Studio workflow later on, if wanted.

 

mgc_1

 

We can type some code, compile (hot-reload), and the node will “morph” its pins to accommodate and execute the function we wrote inside of it.
This can be very handy for developers missing something in-between Blueprints and pure C++ code… Also it’s very useful to actually “read” right there what exactly that one node is doing.

 

mgc_2

 

While coding our functions in this node, we can have some basic auto-complete functionality as well. However keep in mind that I have no previous experience with any of this, turns out making an auto-complete feature is a beast of a complex task and I’ve implemented only the very basics!
For example, in this screenshot the node detected I am trying to invoke a function from a ACharacter class, so while I was typing an auto-complete panel will popup, showing me functions and properties members of ACharacter class:

 

mgc_3

 


 

Workflow:

Here a quick intro of how these nodes are setup and how to make them work correctly for you…
Because this is “real C++” (encapsulated into a safer environment), but still C++, these nodes require your Unreal Project to be a C++ project in order to execute.
Magic Nodes rely on Unreal’s Hot-reload feature to be useful. The basic workflow:

mgc_nodeusage

  1. Just like regular C++, you have a Header field (H) and a CPP field (CPP) where you can declare and define you node’s functions, respectively. Alternatively there’s also a Type field (T) where you can declare any additional types such as enums, structs or classes that your node will use at runtime to execute the code you create.
  2. Before compiling your changes, you have to save your node, that will update the “root source”, the source which stores your code and shares it with all the instances of your node. You can place on Blueprints multiple instances of your node, the source code to execute will be the same for all of the instances executed.
    “Ctrl+S” works as a shortcut for this save button.
  3. Once you’re happy with your code, you need to compile the node, this first button from the Node toolbar. This will run a pre-compilation system that will examine your code… If everything seems correct the this pre-compiler will do all the work necessary to generate (or update) a native C++ class which is what is going to be executed at runtime once your game is packaged. That means that this node is just a “shell” holding the entry point of where and when your C++ code will execute within your Blueprint Graph. The node itself is purely visual and in reality doesn’t do anything besides display to you what it is going to execute.
    If the pre-compiler is happy with what it sees in your code you should hear a “success” beep sound confirming that it indeed generated the native node correctly.
  4. If the pre-compiler is happy with your code, next step is to tell Unreal Engine to incorporate the node runtime into the Blueprint’s Graph execution flow. We do that by hitting the Hot-reload button from the main editor’s toolbar.
    This step is where the actual C++ compiler kicks in and catch any deeper defective code you might be trying to compile; If you can’t get past this stage, it’s a good idea to ask C++ veterans on Unreal’s forums, usually they can point out what exactly is wrong with your code.
  5. Once Hot-reload compilation is complete, this is where the “magic” part comes in… Click the refresh button and the node, now properly compiled to binary library, shall update its input and output pins to reflect the entry function in your code (“FSelf::Execute” function). Once pins are generated and/or updated, you can proceed to link your target variables to it and/or set default values of your pins.

 


 

Example:

Let’s create a node which takes a reference to our Character Blueprint, subscribes a native (node’s internal) function to Character’s “Jump” event and then tells the Character actor instance in game world to jump… This example characterizes as a “Persistent Node”, it keeps running like an Async Function such as Delay Nodes.
Of course, you could simply call the the “Jump” node instead and be done with it, but the point here is to exemplify how you can do that same action from Native C++ with magic nodes instead of calling one new Blueprint Virtual Machine‘s function for every single node you need to call (VM function calls in the end have heavy performance implications, they are orders of magnitude slower than native code and many developers end up converting good portions of their code to C++ because of that). The fact that we can add hundreds of functions to a Magic Node’s source and a call to that node is going to be just ONE call from the Virtual Machine, that’s a performance boost to be considered while at same time we don’t have to deal much with complex plugin modules setup (lot’s of boilerplate code) just to run our functions is also a workflow improvement, there’s much less support code to write on Magic Nodes…

So, make sure that you have Magic Node plugin installed and properly activated:

mgc_guide_0

 

First we will need to create our “source”. We can do this from File -> Project -> “New Magic Node Class…“; That will create a new Magic Node pack in your content browser:

mgc_guide_1

 

Once the source is created and named, let’s forget about it for now. Let’s go to our Character Blueprint and add a new Magic Node to its Graph:

mgc_guide_2mgc_guide_3

 

We now have a “shell” to execute our node. By default it is empty, if you try to compile the Character Blueprint you’ll see Unreal’s Blueprint Compiler to complain about it:

mgc_guide_4

 

So, that source pack we have created before, we need to tell our shell to use that source we have created, for that we use the asset picker right below that error message on the node, it will bind this shell node to our source so we can start coding our functions in it:

mgc_guide_5

 

Now we have our source and the node shall become editable. If we try to compile our Character Blueprint once again, you might notice that it now recognizes our Magic Node as valid, however it will now complain it can’t allocate the entry point “Execute” function even though we can see it is there in our source. The reason why it is that way is because the runtime C++ only cares about compiled binaries, it doesn’t care or interact with any components of the Blueprint’s Virtual Machine:

mgc_guide_6

 

We don’t have to care about that right now, let’s proceed and create our node’s code.
To make it work, we’re going to directly use two member classes of Unreal’s Game Framework, Character class and Input Component class. To use them, we have to include the path to their respective header files; if you’re not sure where those headers are located you can type their types in your script ( ACharacter, UInputComponent ) then Ctrl+LMB them: The Magic Node will launch your browser and search Unreal’s API website for your looking for those classes pages. If the page exists, you should be redirected to these pages, at the bottom of the pages you can find the paths to their headers, here:

GameFramework/ACharacter/
Components/UInputComponent/

Click the “+” sign of # Includes row to include their paths:

mgc_guide_7

 

Done that, we now need to type some code to achieve our goal.
Let’s add this functionality to our H section and CPP section of the node
(don’t worry about the “Character” pin already visible here, that is only there because I have already compiled this node).
Code to the left goes within the Header (H), right one goes within the CPP section:

mgc_guide_8


FIX:

Epic Games team added the same “Subscribe()” function to Unreal Engine on 4.24 and above. To avoid problems then we have to use now “Enroll()” macro inside of Execute function, instead of the “Subscribe()” you see above.


 

Done that, let’s now save and pre-compile our node, from the node’s toolbar:

mgc_guide_9

Then tell Unreal to compile the binary version of our node.
Clicking the Hot-reload button:

mgc_guide_10

 

Once Hot-reload compilation is complete, let’s head back to our node’s toolbar and click the “Refresh” button:

mgc_guide_11

 

Done that, we shall now see that your Magic Node now displays an input pin called “Character”. Let’s attach to it a variable of our Character’s self Blueprint:

mgc_guide_12

 

If you did everything correctly, now compile the Character Blueprint (Blueprint toolbar, not Hot-Reload) and then your Character Blueprint should now be happy and understand what have just made; When playing in editor, if you press the space key the character will jump (make sure you have input settings setup on project settings panel):

mgc_guide_13

 

And that’s it, a quick example of how to run native C++ code on Blueprint Graphs without leaving the Blueprint Editor to work on external applications such as Visual Studio!
If you leave the game running for a while though, the code will stop working…
That will happen because Unreal will run a Garbage Collection operation and our Magic Node running will be destroyed. It’s simple to avoid that, because our node is latent (Persistent Node), we don’t want it to be garbage collected, so we just have to change the declaration and definition body of our “Execute” to output a self-reference, like this:

mgc_out

Then we save the script, pre-compile again, Hot-reload again and now after Refresh our node has an output pin. We promote the output to a variable (here named “Controller Script“) and make the Character Blueprint hold a reference to it, so while our Character Blueprint exists the Magic Node will never be garbage collected:

mgc_guide_14

When we are done with it and want the node to be destroyed, all we have to do is set the variable “Controller Script” to null pointer. The next time Garbage Collector runs it will collect the remains of our node and destroy it as expected!

 

But what if we don’t need a persistent node?
In this case it’s way simpler. We can write the whole functionality within the entry point “Execute” function. Doing so will NOT generate any garbage and the Magic Node will be a “Fire & Forget” type of node, it will be destroyed right after execution flow (white wires) leaves the Magic Node, just like any regular Blueprint nodes!
Like this example node shown previously:

mgc_2

So, I’m running out of time for now, this should illustrate how the general workflow is meant to be when you create Magic Nodes. If you have doubts and questions, feel free to ask in the Unreal Engine’s public forums (link below).


 

Note:
When you want your C++ classes to reference and use Magic Node classes from the Source/MagicNodes/  directoy, besides including a node’s respective class header, make sure you add the “MagicNodeRuntime” module dependency to your project as well:

magicnoderuntimemodule

 

-We don’t make mistakes, just happy little accidents!”  — Bob Ross
Happy coding!

 


 

You can find more about this tool and contribute feedback on Unreal Engine’s forums here: https://forums.unrealengine.com

This is a simple Editor Plugin for Unreal Engine.

It helps to batch transfer Blueprint Properties (variables) between any number of Blueprints selected on Asset Browser.

 

 

It’s very simple to use:

  • Pick a ‘Source’ Blueprint.
  • Pick Target(s) from Asset Browser.
  • Pick which variables to copy.
  • Click ‘Apply’ and save.

Property Picker supports keyboard modifiers:

  • Alt + Click: Pick variable under cursor right away.
  • Ctrl + Click: Unselect selected variable.
  • Shift + Click: Multi-selection.

Property Transfer Tool for Unreal (Programming)

This is my implementation of SQLite API for Unreal Engine 4.
This is one of most complex and useful Unreal Engine extensions I’ve built so far.
This system empowers developers to save and load any data to and from SQLite Databases in Unreal Engine 4 without forcing them to write a single line of SQL Code
(or Blueprint Spaghetti).
If you’re developing a Game that heavily relies on persistent data that must be reliably saved and loaded all the time, such as RPG Games, your best bet is implementation of a Database such as SQLite to record Player’s progress, instead of relying on binary or text files to save your Game…

But learning SQL programming may become a daunting and lengthy process for you to achieve that goal. With this system in place, you can create reliable Databases for your Games, and never care less about SQL syntax.

Making use of a powerful custom serializer engine that I’ve built after a lot of research, based on Unreal Engine’s Code Reflection System, this system is capable of helping you to do amazing and unique data persistence in runtime that otherwise would be impossible.
For example: Unreal Engine’s “SaveGame” system can’t easily save Actor References and restore them to your Properties in real time, but with this system you can:

  • Execute Multi-Threaded SQLite Functions!
  • Create & Edit Database Assets in Unreal Editor!
  • Auto Generate SQL Code through Property Reflection!
  • Setup Property Versioning to support old Game Versions!
  • Save & Load Object References (Pointers) and easily restore them!
  • Save & Load data without conflicts across multiple streamed Levels!
  • Save & Load Actors or Component References and even Arrays of References!
  • Save & Load any kind of Struct as well as basic types like Ints, Strings, Vectors, etc!
  • Save & Load from Background Thread, while players sill interac with Game World!
  • (Optional) Progress Bar System can accurately report loading status without freezing the Game!
  • (Optional) HUD System can automatically generate and show Loadscreens when saving or loading the Game.

9V1HbGi

Continue reading “USQLite (Programming)”

USQLite (Programming)

 

 

WHAT

SPB Sound Occlusion is a plugin for Unreal Engine 4 that implements a complex sound occlusion function in C++ which generates real-time collisions from line traces to physical bodies then calculates volume and pitch variations to the audio source relative to the listener’s position.
The function takes into consideration the physical material attached to the render material used by the shapes the audio source’s traces hit as well as how much direct sound the listener receives to finally calculate the volume output an audio source should play.
Each audio source traces its own path to the listener and multiple collision channels can be traced at the same time.
Any kind of physical body is supported: Static meshes, dynamic meshes, characters, physics volumes and etc, all can be traced against an audio source depending on collision channel settings.
Many occlusion presets for physical materials are included to streamline workflow when creating occlusion effects; For wood, metal, plastic, concrete, so on and so forth.

 

HOW TO USE

Physical Material Setup:

 

First we need a physical material to be attached to render material of a mesh we wish audio occlusion to consider.
To do this, on the asset browser select or create a new physical material used by the mesh:

 

Now on Project Settings panel, look for “Sound Occlusion” and the SPB plugin settings will show up in the panel. There are several Material Presets;
Click on the “Physical Materials” list on the top of the panel to register the Material you’ve created earlier:


 

Because “concrete” is a preset, the plugin will automatically assign ‘concrete’ values to your physical materials, if you name them with that word, when you pick it from the drop-down list.
If you wish to just use your own custom values for this particular occlusion material, just keep the “override” checkbox active and you will be able to edit all values:

 

Then on your render material, base or instance of a material, open it up with Unreal’s Material Editor and set its “Phys Material” to the physical material you have assigned as “concrete” in Project Settings panel.
After that any meshes using such material will react to the occlusion system accordingly with the values of that material we’ve set previously:

 

Listener Component Setup:

 

Now, we need to setup a Listener Component, usually attached to the main Character so this is the focus of this example.
Open the Character Blueprint and from the “+Add Component” button add a “SPB Listener” Component attached to the Capsule Component.
Done that you can click the newly created “SPB Listener” Component to check it’s properties.
On the SPB section of properties there’s a checkbox “Is Player Listener”, in this case we want it set to true because then the plugin will automatically override the origin point of audio spatialization to match the location of our SPB Listener in the game world:

 

After we’re happy with local position of our SPB Listener Component, relative to the Character’s Capsule Component, the Listener needs two complementary elements; add twice an “LLR Component” to the Character Blueprint… Then an important step that can’t be missed: click the LLR Components and drag them to be children of the SPB Listener Component.
By dragging the LLR Components into the SPB Listener, they are registered as children and from there in C++ land the Listener does some voodoo to keep track of them when we actually run the game. So, again, this is important! Attach LLR Components to SPB Listener, two of them, no more no less!
If you did this right, your Character Blueprint would now look like this:

I should highlight that in big red text, but I really want you to read the whole guide instead of dragging your attention to bold areas of the text while you miss the rest 🙂

 

Speaker Component Setup:

 

So the only step missing now is actually creating our SPB Cue or adding an SPB Speaker Component to some Actor that we want to emit sounds and be occluded by the line tracing system.
You will notice that this look alike the default Audio Component, but in this case with an SPB section on its properties:

 

After we created the SPB Speaker Component and attached to our mesh, just like the process with the Listener, we need two sub-components attached to the Speaker; But this time we need “CLR Component”.
We add twice a CLR Component then drag it as a child of the SPB Speaker Component, if you did it right then when you check the properties panel of a Speaker in the Level you should see that the “None” values for “CL Component” and “CR Component” are now updated to reflect the fact that the plugin, in C++ land, have registered the newly created CLR Components and now they have their properties exposed to the SPB Speaker Component:

 

Now, by default the Speaker will trace for occlusion on the “World Static” and “World Dynamic” collision channels.
You can edit this list at will, remove or add channels to fit your project accordingly; for maximized performance is good to trace only one channel, the more channels your SPB Speaker traces the more performance impact is caused.
Still, I believe there’s no need to stress too much about it, the heavy code is all executed entirely in C++ so it’s very very fast even while running line traces for hundreds of Speakers on the same Level:

 

So, done the steps above, the occlusion is ready and you can play-test it! If you click the “Debug” checkbox will can see some of the calculations while ‘Playing in Editor’.
The other settings are very intuitive to use and have detailed tooltips on what they do. Later on I will explain what are “SPB Gates” and what they do, enjoy! Cheers!

 

 

 

(UPDATE) Common Mistakes:

 

This plugin has been live for a while now and many developers use it daily.
From time to time new developers seem to get confused by a few common mistakes I want to outline here in hopes for these occurrences to disappear. There are usually these few common complaints I receive from new users:

#1: “I have followed all steps, but there’s no rays following my character!”
A: What happens is you actually forgot to mark your Listener as ‘Player’. This mistake is so common that I have decided to push an update and make this setting be marked by default when a new Listener Component is created…
islistener

#2: “For some reason it still doesn’t work!”
A: You don’t have a Game Mode set in your level. SPB Listener accesses variables from your Character that are members of Player Controller class, spawned by your Game Mode class. When you do not properly setup a Game Mode for your Map/Level, SPB cannot find the Spatialization component stored in the Player Controller class…
spb_nogamemode

#3: “Still nothing… I can’t see anything happening *angry face*”
A: If your Speaker is using attenuation settings you have to make sure the falloff area is large enough for the player with a Listener attached to move in. When attenuation is activated on the Speaker, it will only trace occlusion until the limits of the falloff area, once the Listener leaves its area the Speaker stops tracing occlusion against that Listener.
spb_attenuation

#4: “But I disabled attenuation or increased falloff distance and still doesn’t work!”
A: In this case one or more of the following things are wrong in your setup:

  • Your components are not activated.
    spb_autoactivate
  • Your Speaker has no sound to play.
    spb_nosound
  • Your Speaker has volume set to zero.
    spb_novolume
  • Your list of channels to trace is empty.
    spb_channels
  • Your Speaker isn’t debugging or is marked with ‘No Trace’.
    spb_debug

 

 

Make sure you have those mistakes above fixed and everything will work correctly.
spb_fixresult

 

 

 

** This plugin is now release on Unreal Marketplace **

UE4 SPB Sound Occlusion (Programming)

MONEYTALKS PLUGIN — UNREAL ENGINE 4

  • This Plugin implements for you accurate data types to represent Decimals and Money values compatible with the Unreal Engine environment.
  • All Currency types introduced are IEEE 754 compliant, C++ Classes to represent accurate world currencies defined by ISO 4217.
  • The FDecimal type can store up to 10^24 (29 signed digits): 99.999.999.999.999.999.999.999.999.999;
  • The FDecimal type can be used on both C++ and Blueprint objects and actors.
  • Replication and Serialization are handled by converting from Decimal to a subset of TCHAR* packs to maintain absolute precision.
  • The FDecimal type introduced is optionally compatible with the FSafe Structs from the SCUE4 Anti-Cheat system: https://www.unrealengine.com/marketplace/scue4-anti-cheat-solution
  • Implementation is based on Intel RDFP Math Library: Copyright(C) 2011, Intel Corporation. All rights reserved.

Why not use Float or Double to store in-game currency?

  • Because floats and doubles cannot accurately represent the ‘Base 10’ multiples used for money representation. The problem with floats is that the majority of money-like numbers don’t have exact representation as integer times power of two. Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications, divisions on inexact numbers, you’ll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money values, where perfect accuracy for multiples of Base 10 is required. While using Int32 or Int64 you are limited by size and cannot accurately represent real-world monetary numbers. The FDecimal have large precision of 128 Bits to guarantee your players will not lose any in-game currency during regular transactions. This is invaluable for games where the player must be able to store large amounts of money, such as RPG tiles.

Why Intel’s Decimal Floating-Point Math Library?

  • Decimal floating-point operations were a necessity from the beginnings of the modern age of computing. However, the lack of a good standard for decimal computations has led to the existence of numerous proprietary software packages for decimal or decimal-like computation, most based on fixed-point decimal types, and each with its own characteristics and capabilities. A turning point for decimal computation is the revision of the IEEE Standard 754-2008 for Binary Floating-Point Arithmetic as an important addition to it is the definition of decimal floating-point arithmetic. The primary motivation was that decimal arithmetic makes numerical calculations more human-friendly. Results will be as people expect them, identical to what would be obtained using pencil and paper. Decimal arithmetic also provides a robust, reliable framework for financial applications that are often subject to legal requirements concerning rounding and precision of the results in the areas of banking, telephone billing, tax calculation, currency conversion, insurance, or accounting in general. The binary floating-point arithmetic that computers use does not always satisfy the existing accuracy requirements. For example, (7.00 / 10000.0) * 10000.0 calculated in single precision is 6.9999997504, and not 7.00. Similar examples can be found for double precision, or any other binary floating-point format. The underlying cause is that most decimal fractions, such as 0.1, cannot be represented exactly in binary floating-point format. The IEEE 754 standard proposal attempts to resolve such issues by defining all the rules for decimal floating-point arithmetic in a way that can be adopted and implemented on all computing systems in software, hardware, or a combination of the two. Intel’s implementation will run on any platform based on Linux™, Windows™, HP-UX™, Solaris™, or OSX™.

The Library is available at GitHub:
https://github.com/BrUnOXaVIeRLeiTE/MoneytalksUE4

UE4 Decimals (Programming)

I will in this post explain a bit the general usage of the UFSM Plugin and how to use it for your advantage when developing complex character behaviors for your UE4 game projects.
For this guide, we will focus on control inputs and how to encapsulate them inside FSM States to easily achieve different movement modes for our pawn.
The character at the end of this process shall be able to respond input commands by walking, running, jumping, double jumping, climbing a ladder; or ignore all inputs:


 

Very well, let’s begin…

 

Installing the UFSM Plugin:
In order to achieve what is accomplish in this tutorial, you have to have access to the UFSM Plugin which you find at Gumroad, or at UE4 Marketplace on a later date when released.
The reason why this plugin is needed is because UE4 has Finite State Machine system available only for the Animation System, but not for programming; Blueprint environment wasn’t really designed with the necessary tools to help you accomplish a proper Finite State Machine system by itself, so a bit of customization via C++ code was needed thus the existence of UFSM, which is a robust C++ component designed to fulfill our requirements.
Before proceeding with installation, let’s keep in mind first two important notes:

1#  UE4 can’t compile plugins if your project is pure Blueprint project. I will explain how to convert the project if that is your case.
2# If your project is Blueprint only, you have to convert the project before you add a Plugins folder with code to the project.

So, let’s begin by creating a new project, using the 3rd Person template as a basis:

FsmT_Step1

It comes with the character we need and input configuration out of the box so in this case it’s a good place to start.
After creating the project and UE4 finish loading… Close the Editor and let’s open the project folder.
Copy and extract the downloaded UFSM Plugin inside the project folder (this is not needed if you install plugins from the Marketplace):

FsmT_Step2

After extracting, if you try to open the Editor you may see an error message like this:

FsmT_Step3

It means your project is Blueprint only and it has no configuration setup to access and compile C++ source files, which is needed to install code plugins that are not pre-compiled and/or shares C++ source.
To fix this, delete the “Plugins” folder which was created, removing all source files… Then open the Editor again and after it loads, create an empty C++ class just to make the Editor configure C++ compiler for your project:

FsmT_Step4

After you’ve created your class, Editor will launch C++ compiler and open Visual Studio for you; now your project is a C++ compatible project.
After loading of Visual Studio is complete… Close it, we don’t need it here. Let’s close again the Editor as well.
Go back to the project folder, extract again the UFSM Plugin to the folder, right click the project file hit “Generate Visual Studio project files”:

FsmT_Step5

Now left click the project file to open it; You now should see this, click “Yes” and Editor will use VS C++ compiler to build the UFSM Plugin for you:

FsmT_Step6

After compilation is done, Editor will launch your project with the new UFSM Plugin installed.
If you right click Content Browser, you will see a new section in the popup menu of (fancy) name “Synaptech”. In that menu you can see buttons to create FSM classes for your project:

FsmT_Step7

And the plugin is installed successfully, read for you to use!


 

Creating a Finite State Machine Component:
Let’s right click Content Browser, ‘Synaptech -> FSM Component’, to create an FSM. Let’s name it “FSM_Input” for easy identification of the new created asset.
Most of our logic for player inputs and character responses will be processed inside this component:

FsmT_Step8

Double click FSM_Input, Blueprint graph for your new component  will popup.
At the Blueprint graph toolbar section, check the “Class Defaults” button; In Details Panel now you shall see ‘FSM’, ‘Activation’ and ‘Events’ sections.
Make sure that “Auto Activate” box is checked:

FsmT_Step9

That is because if an FSM Component is not active, it will not ‘Tick’. And we want this one to tick since it will process all of our player input logic for us.
You can also enable/disable FSM Components and tell one another who disabled who to transition between independent FSMs, but that is a topic out of the focus here.
Now our FSM Component is marked active, let’s also open our Character Blueprint and add to it our newly created component, FSM_Input (under the ‘Custom’ section):

FsmT_Step10

FsmT_Step11


 

Programming our FSM:
Now that our character has the FSM Component attached, before we proceed, there’s an important note about Blueprint owners and Blueprint Components to keep in mind:

Note: If you see a message like this, while trying to save a Blueprint:

FsmT_Note1

It means your FSM Component Blueprint must be fixed before you save the Blueprint which owns it as a Component attached.
To fix it do the following:

1# Compile the FSM Component Blueprint, and save it.
2# Compile the owner Blueprint, in this case our Character Blueprint, then save it.
3# Now you can freely save your Map.

So, back to the Blueprint programming, let’s delete our FSM_Input’s Begin Play and Tick functions because here we won’t need them:

FsmT_Step12

Back to FSM_Input’s ‘Class Defaults’, let’s add to the “STATES” list three new States, like these:

FsmT_Step13

The States are what we will use to control different movement behaviors when our character is using an UI Inventory, moving freely or in ladder movement mode.
If you click the “Visualize STATES’ green button, you should see now something like this indicating the system understands your FSM States declarations:

FsmT_Step14

So, under the ‘FSM’ section there’s an Events section; Let’s click its “+” buttons to add our ‘On Begin’, ‘On Update’, and ‘On Exit’ events.
Those events are fired by the FSM system automatically based on changes between States, so here all we have to do is react to each State to program our input behaviors.
An easy and readable way to react to those State changes, is using a Switch command, so let’s use it here. We will take State by name and switch functions based on its name.
So On Begin State, in case the State that just began to run is the one we are waiting for, then we call some specific functions:

FsmT_Step15

FsmT_Step17

Let’s create, inside our FSM_Input’s graph, a new pair of functions; called ‘On Begin Locked’ and ‘On Exit Locked’.
Inside the On Begin, we can simply disable control inputs for now; And for the On Exit, we enable Inputs again, like this:

FsmT_Step18

Assign the new functions to their lead State Events, from the main graph:

FsmT_Step19

And later if we want to lock input for any reason, but still make Character receive input commands, will be as simple as setting FSM State to “Locked”.
To test that, we quickly setup a new input command for the “i” key in project settings for bindings:

FsmT_Step20

In the Character Blueprint, we transfer the input signal received to the FSM_Input Component, like this:

FsmT_Step21

Now to the bigger part of our graph, the ‘Normal’ State; Let’s create inside FSM_Input’s graph three new functions.
‘On Begin Normal’, ‘On Update Normal’, and ‘On Exit Normal’; then attach them to their lead State Events:

FsmT_Step22

From the Character Blueprint, let’s copy its variables; ‘Base Turn Rate’ and ‘Base Look Up Rate’:

FsmT_Step23

And create two new floats, ‘AxisYaw’ and ‘AxisPitch’; Also copy the ‘AxisForward’ and ‘AxisRight’ from Character Blueprint to FSM_Input.
After copying them, you can delete those from Character Blueprint, they won’t be needed there anymore; from the On Update, we get Owner, cast to our Character Blueprint then call the ‘Add Yaw Input’ and ‘Add Pitch Input’ functions:

FsmT_Step24

FsmT_Step26

FsmT_Step29

Back to the the Character Blueprint, now its input commands are simply feeding float values to the FSM_Input component:

FsmT_Step27

FsmT_Step28

FsmT_Step30

And then our Character Blueprint’s movement FSM is complete and isolated from external behaviors. It will only respond to walk/run commands if FSM_Input is running the ‘Normal’ State.
Now to have FSM based Jump and Double Jump methods, add a new ‘Jump’ State to the FSM list:

FsmT_Step33

Then we repeat the same pattern, create a new ‘On Begin’, ‘On Update’, and ‘On Exit’ for the Jump State:

FsmT_Step34

Back to our Character Blueprint, let’s change the InputAction Jump to this:

FsmT_Step35

It will just tell the FSM to enter Jump State instead of calling Jump function itself. This will be useful later.
Let’s add to it also a custom event. ‘On Double Jump’ which will launch character into the air when triggered:

FsmT_Step36

Implementing our ‘On Begin Jump’ State; this State will call the Character Blueprint’s Jump function and, if the character is already jumping, then it will prepare the necessary steps and allow character to perform a (bug free) double jump action:

FsmT_Step37


 

Setup Character Blueprint and Double Jump Animation:
To make the double jump be more visible while testing, let’s make in a animation program (such as Maya or 3dsMax) a double jump animation and import it into the engine:

FsmT_Step38

Let’s modify the default animation blueprint to include a new double jump state:

FsmT_Step39

Make sure transition follows this rule:

FsmT_Step40

FsmT_Step42

In Animation’s DoubleJump state, set it to run the new double jump clip:

FsmT_Step41

Then check for FSM_Input State in Animation’s Graph:

FsmT_Step43

Back to FSM_Input, we include a ‘Double Jump’ State to the FSM and make ‘On Begin Jump’ transition to it if player is trying to jump again while already jumping:

FsmT_Step45

FsmT_Step44

FsmT_Step46


 

Implementing Ladder Movement:
This is something real simple to implement when using Finite State Machines, but a lot of new UE4 game developers struggle with (mainly because they aren’t using FSMs at all).
Since we have our inputs implemented inside FSM States, to setup a ladder movement mode all we have to do is change how our character receives input when entering the ‘Ladder’ States; No boolean chains, no if then elses, just change the State.
First we of course need a ladder Blueprint with a trigger volume attached to it:

FsmT_Step47

In the FSM_Input Component, let’s add a new flag; it will be set by the ladder volume when Character enters it and press Jump key:

FsmT_Step48

Inside the Ladder Blueprint, we setup it’s trigger to set the flag based on the fact that Character has entered or left the volume:

FsmT_Step50

Back to the FSM_Input Component, we then modify the On Begin Jump function; If player is inside a ladder volume, then attach it to the ladder and change input mode else just perform a normal jump:

FsmT_Step49

In the main FSM_Input’s graph, we add the functions to their lead States as well:

FsmT_Step51

In the ‘On Update Ladder’ function, we do almost the same movement functions from the Normal movement, but now Character can move only up or down.
The best thing about this is the modularity of FSMs; it really will never interfere with Normal movement mode or vice-versa:

FsmT_Step52

Then in our ‘On Begin Ladder’, we setup required Movement Component changes; it must be set to ‘flying’ otherwise the collision capsule will never move away from the floor:

FsmT_Step53

Then in ‘On Exit Ladder’ function, we set Movement Component’s mode to ‘Walking’ again; and reset Gravity as well:

FsmT_Step54


 

And the final result Blueprint Graphs for Character Blueprint and FSM_Input Component:

FsmT_Result_CharacterBP

FsmT_Result_FsmBP


 

And that is it! There you have it; Walk/Run, Jump, Double Jump, Ladder climb up or down, Inventory display all with simple functions and very solid behavior!
And the more important part: No Blueprint spaghetti !!! All the graphs super clean, no wire nightmares and very little use of conditional variables 🙂

DOWNLOAD DEMO PROJECT
(plugin not included)

FSM Based Character in UE4

UE4: Finite State Machine (Programming)

I’ve developed a new  UE4 Plugin. Simple, yet powerful, Finite State Machine system which allows you to manipulate Actor States through Animation Graph’s State Machines, Behavior Tree Tasks, Blueprint Graphs, or C++ Native Code.
Finite State Machines allows for more logic encapsulation and cleaner code architecture in general, drawing systems design and debugging easier on the long run.

 

Some Features:

* Blueprintable Finite State Machine System.
* Blueprint Actor Component Based.
* Event-Based Tasks/Actions can be Broadcasted.
* Supports Enumerators as State ID.
* Supports Runtime State-Machine Creation/Deletion.
* Supports Runtime State-Machine Event Bindings.
* State Machines can Tick and Track Update Time.
* FSM Properties can be Replicated.
* Get/Set States from C++, Blueprints, Animation Graphs, Behavior Trees.

 

How to use:

* First, get the Plugin (not published yet :p) for your compatible Unreal Engine 4 version and install it. After successful installation, you’ll be able to use the FSM Component and its link interfaces. Add to your Actor a FSM Component and you’re good to go.

 

The  Component:

* Launch UEditor and pick an Actor which you want to use FSM with;
From the default Details panel, click ‘Add Component’ drop-down and from the ‘Custom’ group select ‘Finite State Machine’ component; Give it a name.
FSM_Comp1

 

Blueprint Graph Usage:

* From your Blueprint’s Graph, Component tab, select the State Machine and then you can see in Details panel under the ‘Events’ group there’s now three items: ‘On Begin’, ‘On Update’ and ‘On Exit’.
FSM_Bp1

Clicking one of those Events, then you can attach Blueprint Functions to execute bound to each of them and query for current State ID or Name. The buttons adds a custom Event attached the the FSM Component, since State IDs are unsigned bytes, you can create Blueprint Enumerators and compare against IDs for good code readability.
FSM_Bp2FSM_Bp4

* Blueprints that have the FSM Component attached also have access to all its Get/Set/Remove State functions as well. You can Add/Remove States any time, in running game, not just in Editor.
FSM_Bp5

 

Animation Graph Usage:

* If you wish so, you can make a FSM Component reflect a State Machine inside an Animation Blueprint. This however applies only to Skeletal Characters.
Animation Graph’s State Machine Editor is great to setup a FSM and keep a complete visual reference of how your FSM behaves. To do so, you create an Animation Blueprint as usual for your Skeletal Asset, but instead of choosing AnimInstance as Parent Class, pick ‘StateMachineABP’.
FSM_Anim0
FSM_Anim1

* That way your Character can set FSM States based on its Animation States while you react to State changes from your Character Blueprint easily. Once you have your new Animation Blueprint set, in ‘Class Defaults’ you can dictate which FSM Component syncs to Graph and which Animation’s State Machine you want to link.
FSM_Anim2FSM_Anim3

* Once ‘Override FSM’ in Details panel is enabled, the FSM Component attached to your Character Blueprint will automatically replicate and follow the States from Animation Graph every time it changes. This requires you to use in Character Blueprint the Animation Blueprint Class you have your State-Machines, of course; But you can create multiple State-Machines inside Animation Blueprints for a variety of purposes so this doesn’t affect workflow for the actual Animation States, simply create a dull Machine for FSM Graphs without any code affecting the skeletal entity.
FSM_Anim5
FSM_Anim6

 

Behavior Trees Usage:

* You can also manipulate FSM States within an AI Controller’s Behavior Tree Board. Using the custom Task nodes: ‘Add State’, ‘Set State’, ‘Check State’, and ‘Remove State’, you can easily make your AI dictate FSM Component’s States based on AI decisions. This is also an awesome way to easily make your AI react to changes within an Animation Blueprint’s State or react to changes within a Character Blueprint’s Events.
FSM_Bt1FSM_Bt2

 

Native Code Usage:

* So you are more of a C++ guy?! No problem, setting up a complex FSM within a C++ Class is as simple as creating sub-objects. An additional power you have from Native Code is you can bind Functions to FSM States, directly.
FSM_Cpp1

You can bind a new Function to States during runtime, or unbind Functions from it while the game is running as well. You can also easily manipulate States by State Name, State IDs or even directly compare against Enumerator types, with very simple lines of code, such as:
FSM_Cpp2

[At 1.3+: StateMachine->SetActive(true,false); is required to activate FSM]

 

C++ Character Class example, using the API from UFSM 1.6.0+ :

https://wiki.unrealengine.com/FSM#FSM:_.28C.2B.2B.29_Native_API

 

Final Note:

* With a little bit of imagination, this little tool provides unlimited possibilities! Thanks to the awesome environment provided by Epic Games and their Unreal Engine 4.
If you’re used to work with State Machines, such as Unity PlayMaker, you’ll quickly adapt to the workflow proposed by this Plugin; You can really encapsulate all code logic into Finite State rules. If you never tried FSMs before to build game logic, it will set you free of infinite spaghetti piles of code on the long run, give it a try!