Script support for rbfx. It uses Hot++ for hot reload.
hotpp/: Hot++ submodule.Plugins/Rbfx.Script.Core/: script coreRbfx.Script.Core. It is a shared library when the engine is shared.Plugins/Rbfx.Script/: game plugin (Plugin.Rbfx.Script).Plugins/Rbfx.Script.Editor/: editor plugin (Plugin.Rbfx.Script.Editor, a static library for the custom editor).Source/Editor/: custom editorRbfxScriptEditor.Source/Application/: demo main pluginRbfxScript.Main. It is not a part of the scripting system.Source/Launcher/: demo playerRbfxScriptPlayer.Tests/ScriptSmokeTest/: end-to-end test of the game plugin.Project/: editor demo project.Project/Data/Scripts/has the sample scripts.
git submodule update --init --recursive
cmake -S . -B cmake-build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
The default engine path is ../rbfx/CMake.
Set -DCMAKE_PREFIX_PATH=<path> to use a different engine.
The Hot++ language server hot-ls gives diagnostics, completion and F12 for the scripts.
The configure step writes the script host file .cache/hot/hosts/Rbfx.Script.json (hot_script_host in Plugins/Rbfx.Script.Core/CMakeLists.txt).
The file has these parts:
- The engine include folders, definitions and options of the target
Rbfx.Script.Core. Thushot-lsfindsUrho3D.Objectand the other engine types. - The scripts in
Project/Data/Scriptsand the prelude file. - The prelude
Rbfx.prelude.hot.hot-lsgives it to each script, as theScriptSystemdoes at run time. Thus it knowsReflectedObjectand the engine handle rules. - The suffix
.prelude.hotof the user preludes (PRELUDE_SUFFIX). At each analysis,hot-lsfinds these files inProject/Data/Scriptsand gives them after the library prelude. A new user prelude works at once, with no new configure step.
Run the configure step one time before you open the scripts. hot-ls finds the file in the workspace folder.
Open the repository root as the workspace folder.
Use the hot-ls of the same build. An older hot-ls does not know the newer attributes, for example cpp_overrides.
The VS Code extension of Hot++ (hotpp/editors/vscode) finds hot-ls in PATH. Else, set its path in the workspace settings:
"hot.server.path": "${workspaceFolder}/cmake-build/dll/bin/hot-ls"
Change cmake-build/dll to your build folder.
Rbfx.Script.Core has no plugin entry point. It has these parts:
IScriptSource: the origin of the scripts. It lists the scripts, reads a file and gives a modification stamp.ScriptSourceFileSystem: the Hot++ file system (hot::FileSystem) over anIScriptSource. A script has the backend name/rbfx-script-source/<name>. So ausingline or an#includebetween scripts also reads through the source.ScriptSystem: an engine subsystem. It owns the Hot++ backend and the Hot++ loader. Each script is one Hot++ unit. The unit name is the backend path of the script. It is the name thatusing "x.hot"gives in the import list of the importer.LoadScript,ReloadScriptandLoadAllScriptscompile on the calling thread and commit at once. They wait for a background compile first. The system keeps the import graph (ScriptStatus::imports_) and the interface hash of each script.LoadAllScriptsloads all scripts in one batch. A script that imports an unloaded script loads it in the same batch. A body change reloads one script. An interface change compiles again only the dependents that the rule of Hot++ (importer_is_stale) marks stale. HOT_STRICT_IFACE=1 compiles all dependents again. They commit in the same generation, in one batch and in one background job.CreateObject<T>(className)makes an object of a script class with the native baseT. It calls the constructor(Urho3D.Context* context)when the class has one. Else it calls the default constructor. The engine factory of a[ReflectedObject]class uses the same rule.CreateObjectWithArgs<T>(className, args...)calls the constructor with the same parameter types asargs. Errors go to the log withURHO3D_LOGERROR.
The engine include folders and definitions come from the Urho3D target at configure time.
CMake writes them to a generated file. The script compile uses them.
The game plugin Plugin.Rbfx.Script registers the ScriptSystem subsystem in Load.
Its source is ResourceScriptSource: the .hot and .cpp files of the Scripts resource folder.
The plugin loads all these scripts in Load.
The editor plugin has the source DiskScriptSource: one folder on the disk, without the ResourceCache.
It adds the "Scripts" tab to the editor.
The tab shows the script folder, the scripts, their classes, the generation and the compile errors.
It shows "compiling..." next to a script while its background compile runs.
The Reload button compiles all scripts of the folder again.
The default folder is <project data folder>/Scripts.
Type a folder relative to the project folder and click "Apply Folder" to change it.
The project ui.ini keeps the folder (entry ScriptDir).
Plugins/Rbfx.Script.Core/Prelude/Rbfx.prelude.hot configures the scripts.
CMake embeds the file in the core library, so the game needs no file for it.
The ScriptSystem gives it to the Hot++ backend (hot::DefaultBackendOptions::preludes).
[lib("eastl")]: EASTL is a library namespace next to the C++ standard library.eastl.vector<int>in a script iseastl::vector<int>, andstd.vector<int>isstd::vector<int>. A script can use both in one class. The EASTL containers get the bounds check of an index and the reload rules of the std containers. An interpolated string"${x}"is astd::string. For aneastl.string, write"${x}".c_str().- A class that derives from
Urho3D::RefCountedis aUrho3D::SharedPtrhandle.Urho3D.Node n = new Urho3D.Node(ctx);holds aUrho3D::SharedPtr<Urho3D::Node>. [weak] Urho3D.Node wis aUrho3D::WeakPtr<Urho3D::Node>. A read gives null when the object is gone.- A script class with a
RefCountednative base, such asUrho3D.LogicComponent, uses the same handles. - A raw pointer
Urho3D.Node*stays a raw pointer.
A script class without a native base uses std::shared_ptr.
In such a class, this as a handle is not supported.
Give the class a native base that derives from RefCounted instead.
The library prelude sets the default rules. A user prelude extends them or overrides them.
A user prelude is a file *.prelude.hot in the script folder or in a subfolder.
The ScriptSystem finds the user preludes through the script source: the Scripts resource folder in the game, the disk folder in the editor.
It gives them to the backend after the library prelude, sorted by path.
It does not compile them as scripts.
A stub in a later prelude with the key of an earlier stub merges into the earlier rule:
value,handleandintrusiveare the storage. A stated storage replaces the full earlier storage.weak_handleanddefault_handlereplace the earlier value. A new storage without a handle removes the weak handle. A new handle needs a newweak_handle, orweak_handle("").cpp_preludetext adds up: the later text comes after the earlier text.cpp_overridesnames add up.native,selfandchecked_indexadd up. A later stub cannot remove them.- An empty string removes an inherited value, for example
weak_handle("")orcpp_prelude(""). - A merged rule that is not valid, for example
valuewith an inheritedweak_handle, is an error at the later stub. - A later prelude overrides
stdandarrayof an earlier prelude.libadds up. - A stub in a script merges in the same way, for that script only.
The key is the form and the name of the stub: class Urho3D.RefCounted;, class : Urho3D.Object;, class *;, struct *; or a pattern.
A refining exact stub still needs native.
A change, an addition or a removal of a user prelude compiles all scripts again in the background. The old code of a script runs until its new compile succeeds. A broken prelude gives a compile error for each script. The old code stays, and the Scripts tab and the log show the error.
The prelude declares the Hot++ script attribute ReflectedObject.
Put it on a .hot script class to register the class with the engine:
[ReflectedObject]
class Rotator : Urho3D.LogicComponent { ... }
A .cpp script cannot use the .hot attribute syntax.
Include Rbfx.Script.Core/ScriptReflection.h and write RBFX_SCRIPT_REFLECTED after class:
#include <Rbfx.Script.Core/ScriptReflection.h>
class RBFX_SCRIPT_REFLECTED Rotator2 : public Urho3D::LogicComponent { ... };The macro is the Hot++ macro HOT_ATTRIBUTE("ReflectedObject"), a clang annotation.
RBFX_SCRIPT_REFLECTED also names URHO3D_OBJECT as a shell macro (HOT_SHELL_MACRO).
A .cpp class keeps URHO3D_OBJECT(Name, Base); in its body, as in a normal C++ file.
Hot++ copies the call into the shell and hides its members from the script.
The script has no slot for GetType, GetTypeName, GetTypeInfo and IsInstanceOf (HOT_NO_SLOT).
The two forms give the same result.
- After each script load, the
ScriptSystemregisters each new class with this attribute. - The engine factory makes the class by its name:
Context::CreateObjectandNode::CreateComponent. - The engine attributes of the native base are copied to the script type.
- A component type gets the category
Component/User. The editor lists it in the "User" group of its component menus. - The primary native base must be an engine type, for example
LogicComponent. - The script system loads the scripts in name order. It registers the types before the plugin
Loadreturns. Thus the types exist before a scene loads, also after a plugin reload of the editor. - The destructor of the
ScriptSystemunregisters its types (UnregisterReflectedTypes). So a plugin unload removes the types, and a new plugin instance registers them again. - Here, "attribute" is a Hot++ tag. An "engine attribute" is a reflected rbfx property.
Script type identity:
- The prelude puts
URHO3D_OBJECT(ScriptClass, Base)in the shell of each script class belowUrho3D::Object. This applies to all such classes, also to classes withoutReflectedObject. - So
GetType,GetTypeName,GetTypeInfoandIsInstanceOfgive the script type. A script cannot override these four functions. - The engine registers the static
TypeInfoof the shell. An object and its registered type have the sameTypeInfo. A hot reload keeps it. A new plugin instance registers a new one. Exception: after a reload that changes the constructors of a class, new objects have a secondTypeInfo. It has the same name and type hash, so a scene save and the engine factory still work. - A scene save writes the script type, and a scene load makes the script class again.
Node::GetComponent<LogicComponent>()does not find a script component, because it compares the exact type. UseGetDerivedComponent<LogicComponent>()or the script type name.- A scene that was saved before this change has the base type (for example
LogicComponent) for its script components. Such a component loads as anUnknownComponent. Remove it and add the script component again.
Engine attributes of script fields:
- The prelude declares the Hot++ tag
Attribute. A field with the tag in a[ReflectedObject]class is an engine attribute. Example:[Attribute("Max Health", "AM_DEFAULT")] int maxHealth = 100;. Both strings are optional. The default name is the field name. The default mode isAM_DEFAULT. - Hot++ gives the tags in the field row of the state layout (
hot::FieldInfo::attributes). - The accessor finds the field by name at each access, because the state block moves on a reload. A missing field or a changed field type gives the default value.
- The default value is the field value of a temporary object after its constructor.
- The supported types are the Variant types of the prelude comment. A field of another type gets one warning.
- A third string gives the enum names:
[Attribute("Team", "AM_DEFAULT", "T, CT")] Team team = Team.T;. The names are in the order of the values from 0. The field is an enum or anintof 4 bytes. The engine attribute is anintwith these names. A scene saves the name, and a load accepts the name. - After each load, the
ScriptSystemremoves the script attributes of each registered class and adds the current ones. A hot reload keeps the field values, so the attribute values stay. - A class that a reload removes, or that loses
ReflectedObject, leaves the engine. Its live objects stay, but a scene cannot save their script attributes. - A change of a value does not call a script function. Override
ApplyAttributesfor an update after a load. - A property with the tag works the same way:
[Attribute("Armor")] int Armor { get { ... } set { ... } }. The property needsgetandset. Hotc gives an error for a read-only property with the tag. A property of a script parent is not an attribute of the child yet. - Hot++ gives the tagged properties in the property table of the state layout (
hot::StateLayout::props). The accessor calls the generated thunks of the row (hot::PropertyInfo::getandset) and finds the row by name at each access. The thunks run the script accessors, so the setter code runs on aSetAttributeand on a scene load. No runtime reflection is necessary: the table works in an AOT build. - A property attribute has no enum names. A third string gives a warning, and the property is not an attribute.
- A
.cppscript has no field tags yet. - The smoke test uses
Tests/ScriptSmokeTest/Data/Scripts/AttributeProbe.hot.
Rotator.hot and Rotator2.cpp in Project/Data/Scripts are the samples.
The smoke test checks that the engine knows them and makes them by name.
The subsystem polls the stamp of each loaded script every 500 ms, in the E_ENDFRAME handler.
The game source uses the modification time of the resolved file on the disk.
A file in a package has the stamp zero and does not reload.
A changed script compiles again on a worker thread, so the frames do not stop.
The objects keep the old code and run it during the compile.
At the end of the first frame after the compile, the new code goes live. The objects keep their fields.
New script classes with the attribute ReflectedObject become engine types at that time.
A compile error keeps the old code. The error goes to the log and to the "Scripts" tab.
One compile runs at a time. No commit runs during a compile.
A script that changes again during its compile compiles again with the newest text. The old result is dropped.
The destructor of the subsystem waits for a running compile, also at a plugin reload.
A changed header does not start a reload. Call ReloadScript for it.
A .rml document can hold a <script> block with Hot++ code.
The demo is Project/Data/UI/ScriptDemo.rml. The scene Sample.scene opens it with an RmlUIComponent.
- Each
X.rmlis one unit with the nameX.rml.hot. The unit text is one prefix line, then the.rmltext. The prefix line isPrelude/RmlUnit.prefix.hot. The text outside the<script>block is masked, so the line numbers stay. - A handler is an
on*attribute with a Hot++ expression:onclick="Add(10)"oronclick='element.SetId("x")'. The host does not parse the expression. Each unique expression gets one stub function after the script blocks of the unit (Prelude/RmlHandler.stub.hot). The stub name isrml_on_and the FNV-1a hash of the text. A click calls the stub. A document with handlers and no<script>block also gets a unit with the stubs only. - The stub has six locals:
event: theRml.Event*of the call.element: the element that has the attribute.target: the target element of the event.document: the document of the element.component: theRmlUIComponent*of the document. It is null for a document without a component. A use of a nullcomponentthrowsNullReference. A handler that does not use it works.context: theUrho3D.Context*.
- The unit has the functions
getElementById(id)andquerySelectorAll(selector).getElementByIdreturns null when no element has the id.querySelectorAll(".item")returns anRml.ElementList. - A
;outside single quotes splits a value into parts, as before. Each part is one expression with its own stub. A part that starts withsound:orevent:keeps its old meaning and gets no stub. - Quotes: put the value in single quotes and use double quotes for strings:
onclick='Add(1, "Clicks")'."in a double-quoted value also works:onclick="Add(1, "Clicks")". A'x'in Hot++ is a char, not a string. - A handler must be valid Hot++. One bad handler fails the compile of the inline unit of its document, with its script block. The error has the stub text.
- Handlers in
<template>files and in text given toSetInnerRMLget no stub. A click on such a handler logsthe handler has no stub: the text must be in the .rml file of the document. - A data model event calls a script function too:
data-event-click="script('select', it.id)". The first argument is the function name. The other arguments are the values. The engine binds the eventscriptin eachRmlUIComponentdata model. It uses the call path of the markup handlers, so the errors are the same. The data model must be on an element inside<body>, becausedata-fordoes not work withdata-modelon<body>. - A function named
OnLoad()runs when the document opens. A function namedOnUnload()runs when it closes. Both take no parameter. ScriptSystem::OnScriptsCommittedsends the committed script names after each commit. A handler can callLoadScriptorReloadScript. The nested signal waits in a queue.- A unit that was not loaded at the first open gets its
OnLoad()after the commit that loads it. A plain reload does not callOnLoad()again. - A new
.rmlfile is unknown at its first open. The bridge callsLoadScriptone time at the end of that frame. A failed unit is not tried again.
In an optimized AOT build (hotc --aot --aot-optimized) a unit with [fn_invoker("MACRO")] keeps its function table and @call entries. The .rml units have the attribute from the prefix line.
A plain .hot script that markup calls needs its own [fn_invoker("RBFX_RML_INVOKER")];. Optimized units stay locked for reload and cannot declare an interface.
The option RBFX_SCRIPT_AOT_OPTIMIZED builds the units of rbfx_script_add_aot in this form. ScriptSystem::LoadPrecompiled accepts an optimized table only with run-time compile off (RBFX_SCRIPT_RUNTIME_COMPILE=0). It then runs the table with no override and no reload.
With run-time compile on, it drops an optimized table and compiles the scripts. If the machine has no compiler, an ON build loads no script from an optimized table.
Limits of optimized code:
- A reflected class has no layout, so its script attributes do not register.
- A unit without
[fn_invoker]has no function table. The bridge then says that the unit is not loaded. This message is not exact. - The host must release the script objects before
~ScriptSystem. The smoke test does this. - The unit has the ambient helpers
ThisDocument(),ThisElement(),ThisEvent()andgetElementById(id).ThisEvent()is valid only during the dispatch of the event. <script src="x.hot"></script>adds the normal unitx.hotto the document. The engine resolves the path against the document path (UI/A.rmlwith../Scripts/X.hotor/Scripts/X.hotgivesScripts/X.hot). The unit name is that resolved path without.hot. The unit must be inScripts/orUI/. All documents with the same unit share its functions and globals. A plain unit has no prefix: it must start with[fn_invoker("RBFX_RML_INVOKER")];,using "Rbfx.Script.Core/RmlScript.h";andusing Urho3D;for markup calls. The lookup order is the inline unit, then thesrcunits in header order. Asrcthat is not.hotgives one error and adds no unit.Listen(id, eventName, fn)andSubscribe(eventType, fn)keep the document of the call. The host pushes the saved frame (document, element, event, owner) before it callsfn, soThisDocument()infnis the document that made it. The record of the document owns each listener and the one subscription host. A listener is anRml::EventListener. An element that dies first detaches it, and the unload deletes it.- The unload removes all listeners and subscriptions before
OnUnload()runs. Nofnruns during or after the unload. - A call outside a document call, an unknown id, or a document that unloads gives one error line and adds nothing.
- A commit of any script unit drops the listeners and subscriptions of all documents at the commit, while the old code is mapped, and logs one error for each document that had some. A script must call
ListenandSubscribeagain after any reload of any unit. An exception offnis caught and logged. RmlInvokeris the call form that the prelude makes for each public free function and stub. The host calls the stub with no arguments.- A runtime error goes to the log as
RmlScript: UI/X.rml:LINE: 'expression': cause. LINE is the line of the handler in the.rmlfile. - A compile error goes to the log as
cannot compile 'UI/X.rml.hot', with the clang text. The line inUI/X.rml.hot:LINE:COLUMNis the line in the.rmlfile. The old code keeps running.
Rules:
- The name
X.rml.hotis reserved. Do not use it for a script in theScriptsfolder. - The text
</script>inside a string ends the block. Write<\/script>or build the text in parts. - Class names are global. All units share one namespace, so two units cannot define the same class name. Function names and globals are local to the unit.
- A global keeps its value after the document closes and opens again. Set start values in
OnLoad(). The smoke test checks this: the counter continues after a close. - A reload of the script body keeps the globals, by the state rules of the unit. A markup edit outside the block does not change the unit text, so no compile runs and the globals stay.
- Do not keep an
Rml.Element*in a global. It can dangle after a reload of the document. UsegetElementByIdat each use.
A plain subscription reloads. A native signal or an event can keep a lambda or a method group of a script.
After a reload, Hot++ gives the stored closure the new body. The key of the lambda, its signature and its captures must agree
(see "Lambdas and reload" in the Hot++ documentation).
So a script can write signal.Subscribe(this, (int v) => { ... }), signal.Subscribe(this, HandleChanged),
SubscribeToEvent(eventType, () => { ... }) and SubscribeToEvent(eventType, HandleUpdate) with no helper.
The smoke test CheckResubscribe checks this with the class PlainProbe in Tests/ScriptSmokeTest/Data/Scripts/SubscribeProbe.hot.
The replay in the subsystem is only for a change of the subscriptions themselves. A closure does not follow such a change, because it keeps its old subscription:
- a new, a removed or a retargeted subscription (another event, signal or sender),
- a lambda that has a new signature or other captures (Hot++ detaches it, and a call is a stale call).
The replay runs the subscription code again, so each object gets the new set of subscriptions. It is not necessary for a change of a body.
- A script puts the subscriptions of an object in
void OnSubscribe(). It callsOnSubscribefromStart()or from the constructor. OnSubscribeuses the helpers ofRbfx.Script.Core/ScriptSubscribe.h. The script writesusing "Rbfx.Script.Core/ScriptSubscribe.h";. A.cppscript includes the header. A prelude holds only stubs, so the prelude cannot include it.Rbfx.Connect(this, signal, fn)callssignal.Subscribewith a receiver token of the object. The subsystem holds the token. A signal drops a handler when its receiver token expires.Rbfx.Subscribe(this, eventType, fn)andRbfx.Subscribe(this, sender, eventType, fn)callSubscribeToEvent. The subsystem records the sender and the event type.- After the commit of a reload, the subsystem walks the live objects of the changed classes (
hot::Loader::each_object). The thunkCls::__nativegives the object from its shell. The subsystem removes the recorded events of the object. It releases the token, then it callsOnSubscribeagain through the thunkCls::OnSubscribe. - The objects that a script makes with
newsubscribe again too.
Limits:
- A plain
SubscribeToEventorsignal.Subscribe(this, ...)is not recorded. The replay does not drop it and does not call it again. It keeps its closure, and the closure runs the new body. OnSubscribemust have no parameters and no return value. A changed signature gets a warning, and no call. The thunk of the first signature has no signature key, so the subsystem cannot check the first signature.- The primary native base must be an
Objectat offset zero of the native base, as in all rbfx types. - A script error in
OnSubscribegoes to the log, as for each call from the host. The other objects go on. - The rule is not for
HOT_AOT_OPTIMIZEDcode: that code does not reload. - The smoke test
CheckResubscribe(Tests/ScriptSmokeTest/Data/Scripts/SubscribeProbe.hot) shows the replay with the classSubscribeProbe.
- Call
LoadScriptandReloadScripton the main thread, and not from script code. - The factory of a script class uses the constructor
(Urho3D::Context*)when the class has it. Else it uses the default constructor. - Release all script objects before the plugin unloads.
- The plugin opens its own library again with
RTLD_GLOBAL. This lets the script modules find the Hot++ runtime in the plugin. - A GCC build compiles the scripts with the
clang++of the system. The run-time compile needsclang++and its resource folder. - The process must have one copy of the Hot++ runtime state.
With a shared engine,
Rbfx.Script.Coreis a shared library, and all plugins link it. Each plugin callsScriptSystem::GetOrCreateShared. It registers aScriptSystemonly when the context has none. The plugin that makes the subsystem removes it. The other plugin uses it. With a static engine, link the core into one module only. The operations ofScriptSystemare virtual, so a module with only the header calls the code of the core. - Linux: the Hot++ runtime compiles with
-ftls-model=initial-exec. This marks the pluginSTATIC_TLS. So glibc gives the plugin static TLS when the engine opens it. The script modules read the call depth of Hot++ from static TLS.
cmake --build cmake-build --target RbfxScriptEditor
cmake-build/bin/RbfxScriptEditor "$PWD/Project"
The editor build needs URHO3D_EDITOR (the EditorLibrary target).
The project folder is a positional argument of the editor.
The "Scripts" tab loads the scripts of Project/Data/Scripts/.
Rotator.hot and Rotator2.cpp are LogicComponent classes that turn their node.
Project/Project.json also loads the game plugin Plugin.Rbfx.Script, for the play mode.
The game plugin then uses the ScriptSystem of the tab. So the editor has one script system.
The play mode needs a main plugin. The main plugin loads the scene and makes the viewport.
Plugin.Rbfx.Script is generic, so it is not a main plugin.
The demo main plugin is RbfxScript.Main (Source/Application/).
It loads the scene of the SceneName engine parameter and uses the first camera.
If the scene has no camera, it creates a camera.
It moves the camera to the editor camera position and rotation.
Project/Project.json loads Plugin.Rbfx.Script first and RbfxScript.Main second.
Thus the script types exist when the scene loads.
The scene also stops before the scripts stop.
The player runs the same plugins without the editor:
cmake --build cmake-build --target RbfxScriptPlayer
cd cmake-build/bin && ./RbfxScriptPlayer --scene Scenes/Sample.scene
The player needs ResourceRoot.ini in its directory or in a parent directory.
cmake -S . -B cmake-build -DRBFX_SCRIPT_BUILD_TESTS=ON
cmake --build cmake-build --target Rbfx.Script.SmokeTest
cp -r Project/Data /tmp/script-data
cmake-build/bin/Rbfx.Script.SmokeTest cmake-build/bin/libPlugin.Rbfx.Script.so /tmp/script-data
Give an absolute data folder. The test changes Scripts/Rotator2.cpp in the copy and restores it.
It loads two scripts where one imports the other. A body change reloads one script, and an interface change reloads both.
It also adds, changes and removes user preludes. It checks the merge of the preludes and the compile after a prelude change.
The test does not link Rbfx.Script.Core. It uses the ScriptSystem of the plugin.
A host project can build rbfx-script with add_subdirectory.
The host does find_package(Urho3D) first and owns the output folders and the C++ standard.
When the project is not the top-level project, or the target Urho3D exists,
rbfx-script skips this setup.
The option RBFX_SCRIPT_BUILD_DEMO is OFF then. It builds the editor plugin, the demo application,
the launcher and the editor.
find_package(Urho3D REQUIRED)
add_subdirectory(extern/rbfx-script rbfx-script)
target_link_libraries(MyPlugin PRIVATE Rbfx.Script.Core)
The host plugin needs the include folders of its own headers in the script compile. There are two ways to give them to the script compile.
- Call
ScriptSystem::AddIncludeDirandScriptSystem::AddCompilerFlagbefore the first load. - Call
ScriptSystem::SetCacheDirbefore the first load to reuse the object files after a restart. A call after the first load logs a warning and changes nothing. - Call
ScriptSystem::SetCompileCommandsDirbefore the first load to writecompile_commands.jsonfor the IDE. The database needs the cache. ScriptSystem::GetCacheStatsreturns the hits and the misses of the cache. Each batch logs its own numbers.- Generate the values from a target. Call
rbfx_script_build_config(TARGET <t> OUTPUT_DIR <dir> NAME <n>). It writes<dir>/<n>.inlwith the arrayskEngineIncludeDirsandkEngineDefines. Include the file in one source file of the host and give the arrays to theScriptSystem.
The engine opens a plugin library without RTLD_GLOBAL.
Call ScriptSystem::PromoteModuleSymbols(symbol) with the address of a symbol of the host plugin.
It opens that plugin again with RTLD_GLOBAL, so the script modules find its symbols.
OverlayScriptSource joins an ordered list of script sources (layers). A later layer wins for the same name.
Example: layer 0 is the game scripts in the ResourceCache (read-only, can be AOT-precompiled).
The next layers are the mod folders and the user folder on the disk (writable).
ListScriptsreturns the union of the names. Each name is in the list one time.ReadTextandExistsuse the top-most layer that has the name.GetModificationStampcomes from the winning layer. The stamp includes the index of this layer. So a switch of the winning layer changes the stamp, and the poll sees it.
The AOT rule does not change. The script system compares the hash of the text of the winning layer with the hash of the AOT text. A script that a higher layer hides has a different text: it compiles at run time. The other scripts run the AOT code. A script that only a higher layer has compiles as a new unit. When the higher file goes away, the lower text is visible again. If its hash equals the AOT hash, the poll returns the unit to the AOT code and does not compile.
The game plugin has the function RbfxScriptSetLayerFolders(folders, count).
The game calls it before the plugin loads. Each folder holds names like Scripts/Rotator.hot.
The folders go above the game scripts, from the lowest to the highest. Count zero gives no layers.
DiskScriptSource (in Rbfx.Script.Core) reads such a folder.
Call rbfx_script_pack(TARGET game SCRIPT_DIR Scripts [PAK file] [RESOURCE_DIR Scripts]) from cmake/RbfxScriptAot.cmake.
The function wraps create_pak of rbfx, which runs the PackageTool.
It copies the .hot, .prelude.hot and enabled.txt files to a staging folder.
Build products are not copied.
The tool packs the staging folder, so the resource path of a file is Scripts/<path>.
This is the path that the ResourceScriptSource reads.
The game adds the .pak file to the ResourceCache.
The AOT code stays valid, because the hash of the packed text is the hash of the source text.
Some platforms have no compiler at run time: web, iOS, Android, UWP and consoles. These platforms run precompiled (AOT) scripts only.
The CMake option RBFX_SCRIPT_RUNTIME_COMPILE controls this.
The default is ON on desktop Linux, Windows and macOS.
The default is OFF for Emscripten, iOS, Android and UWP.
Set the option by hand to change the default.
When the option is OFF:
Rbfx.Script.Corelinkshot::runtimeand nothot::backend. Hot++ builds no clang or JIT backend. The build still makeshotcfor the AOT step.- The compile definition
RBFX_SCRIPT_RUNTIME_COMPILE=0is PUBLIC onRbfx.Script.Core. The game code sees it. - The ScriptSystem never creates the backend. No process starts. No file is polled for a reload.
LoadPrecompiledruns the AOT units from the table.- A script with a different source hash keeps its AOT code. The log has one warning for this script.
- A script that the table does not hold does not load. The log has one error for this script.
LoadScriptandReloadScriptfor a script that needs a compile give an error.rbfx_script_add_aotworks as before. It compiles the scripts at build time.
The game must call SetPrecompiledScripts(&hot::aot_table) before LoadAllScripts.
The test is in Tests/ScriptSmokeTest. Configure a build with -DRBFX_SCRIPT_RUNTIME_COMPILE=OFF
and -DRBFX_SCRIPT_BUILD_TESTS=ON. The smoke test then runs only the check CheckNoRuntimeCompile.
It checks that the AOT units run, that a changed script gives one warning and keeps the AOT code,
and that no child process starts.
A header in a layer folder works for the scripts of the layers. A using "Header.h" line searches the folder of the script
in the overlay, so a header of a higher layer is visible to a script of a lower layer in the same folder name.