Skip to content

Latest commit

 

History

History
507 lines (414 loc) · 34.3 KB

Architecture.md

File metadata and controls

507 lines (414 loc) · 34.3 KB

rbfx-script architecture

Script support for rbfx. It uses Hot++ for hot reload.

Layout

  • hotpp/: Hot++ submodule.
  • Plugins/Rbfx.Script.Core/: script core Rbfx.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 editor RbfxScriptEditor.
  • Source/Application/: demo main plugin RbfxScript.Main. It is not a part of the scripting system.
  • Source/Launcher/: demo player RbfxScriptPlayer.
  • Tests/ScriptSmokeTest/: end-to-end test of the game plugin.
  • Project/: editor demo project. Project/Data/Scripts/ has the sample scripts.

Build

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.

IDE (hot-ls)

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. Thus hot-ls finds Urho3D.Object and the other engine types.
  • The scripts in Project/Data/Scripts and the prelude file.
  • The prelude Rbfx.prelude.hot. hot-ls gives it to each script, as the ScriptSystem does at run time. Thus it knows ReflectedObject and the engine handle rules.
  • The suffix .prelude.hot of the user preludes (PRELUDE_SUFFIX). At each analysis, hot-ls finds these files in Project/Data/Scripts and 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.

Architecture

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 an IScriptSource. A script has the backend name /rbfx-script-source/<name>. So a using line or an #include between 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 that using "x.hot" gives in the import list of the importer. LoadScript, ReloadScript and LoadAllScripts compile 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. LoadAllScripts loads 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 base T. 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 as args. Errors go to the log with URHO3D_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).

The prelude

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 is eastl::vector<int>, and std.vector<int> is std::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 a std::string. For an eastl.string, write "${x}".c_str().
  • A class that derives from Urho3D::RefCounted is a Urho3D::SharedPtr handle. Urho3D.Node n = new Urho3D.Node(ctx); holds a Urho3D::SharedPtr<Urho3D::Node>.
  • [weak] Urho3D.Node w is a Urho3D::WeakPtr<Urho3D::Node>. A read gives null when the object is gone.
  • A script class with a RefCounted native base, such as Urho3D.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.

Preludes: library defaults and user overrides

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, handle and intrusive are the storage. A stated storage replaces the full earlier storage.
  • weak_handle and default_handle replace the earlier value. A new storage without a handle removes the weak handle. A new handle needs a new weak_handle, or weak_handle("").
  • cpp_prelude text adds up: the later text comes after the earlier text.
  • cpp_overrides names add up.
  • native, self and checked_index add up. A later stub cannot remove them.
  • An empty string removes an inherited value, for example weak_handle("") or cpp_prelude("").
  • A merged rule that is not valid, for example value with an inherited weak_handle, is an error at the later stub.
  • A later prelude overrides std and array of an earlier prelude. lib adds 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.

Reflected script types

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 ScriptSystem registers each new class with this attribute.
  • The engine factory makes the class by its name: Context::CreateObject and Node::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 Load returns. Thus the types exist before a scene loads, also after a plugin reload of the editor.
  • The destructor of the ScriptSystem unregisters 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 below Urho3D::Object. This applies to all such classes, also to classes without ReflectedObject.
  • So GetType, GetTypeName, GetTypeInfo and IsInstanceOf give the script type. A script cannot override these four functions.
  • The engine registers the static TypeInfo of the shell. An object and its registered type have the same TypeInfo. 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 second TypeInfo. 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. Use GetDerivedComponent<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 an UnknownComponent. 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 is AM_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 an int of 4 bytes. The engine attribute is an int with these names. A scene saves the name, and a load accepts the name.
  • After each load, the ScriptSystem removes 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 ApplyAttributes for an update after a load.
  • A property with the tag works the same way: [Attribute("Armor")] int Armor { get { ... } set { ... } }. The property needs get and set. 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::get and set) and finds the row by name at each access. The thunks run the script accessors, so the setter code runs on a SetAttribute and 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 .cpp script 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.

Hot reload

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.

RmlUI scripts

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.rml is one unit with the name X.rml.hot. The unit text is one prefix line, then the .rml text. The prefix line is Prelude/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)" or onclick='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 is rml_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: the Rml.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: the RmlUIComponent* of the document. It is null for a document without a component. A use of a null component throws NullReference. A handler that does not use it works.
    • context: the Urho3D.Context*.
  • The unit has the functions getElementById(id) and querySelectorAll(selector). getElementById returns null when no element has the id. querySelectorAll(".item") returns an Rml.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 with sound: or event: 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")'. &quot; in a double-quoted value also works: onclick="Add(1, &quot;Clicks&quot;)". 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 to SetInnerRML get no stub. A click on such a handler logs the 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 event script in each RmlUIComponent data 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>, because data-for does not work with data-model on <body>.
  • A function named OnLoad() runs when the document opens. A function named OnUnload() runs when it closes. Both take no parameter.
  • ScriptSystem::OnScriptsCommitted sends the committed script names after each commit. A handler can call LoadScript or ReloadScript. 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 call OnLoad() again.
  • A new .rml file is unknown at its first open. The bridge calls LoadScript one 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() and getElementById(id). ThisEvent() is valid only during the dispatch of the event.
  • <script src="x.hot"></script> adds the normal unit x.hot to the document. The engine resolves the path against the document path (UI/A.rml with ../Scripts/X.hot or /Scripts/X.hot gives Scripts/X.hot). The unit name is that resolved path without .hot. The unit must be in Scripts/ or UI/. 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"; and using Urho3D; for markup calls. The lookup order is the inline unit, then the src units in header order. A src that is not .hot gives one error and adds no unit.
  • Listen(id, eventName, fn) and Subscribe(eventType, fn) keep the document of the call. The host pushes the saved frame (document, element, event, owner) before it calls fn, so ThisDocument() in fn is the document that made it. The record of the document owns each listener and the one subscription host. A listener is an Rml::EventListener. An element that dies first detaches it, and the unload deletes it.
  • The unload removes all listeners and subscriptions before OnUnload() runs. No fn runs 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 Listen and Subscribe again after any reload of any unit. An exception of fn is caught and logged.
  • RmlInvoker is 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 .rml file.
  • A compile error goes to the log as cannot compile 'UI/X.rml.hot', with the clang text. The line in UI/X.rml.hot:LINE:COLUMN is the line in the .rml file. The old code keeps running.

Rules:

  • The name X.rml.hot is reserved. Do not use it for a script in the Scripts folder.
  • 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. Use getElementById at each use.

Subscriptions after a reload

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 calls OnSubscribe from Start() or from the constructor.
  • OnSubscribe uses the helpers of Rbfx.Script.Core/ScriptSubscribe.h. The script writes using "Rbfx.Script.Core/ScriptSubscribe.h";. A .cpp script includes the header. A prelude holds only stubs, so the prelude cannot include it.
  • Rbfx.Connect(this, signal, fn) calls signal.Subscribe with 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) and Rbfx.Subscribe(this, sender, eventType, fn) call SubscribeToEvent. 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 thunk Cls::__native gives the object from its shell. The subsystem removes the recorded events of the object. It releases the token, then it calls OnSubscribe again through the thunk Cls::OnSubscribe.
  • The objects that a script makes with new subscribe again too.

Limits:

  • A plain SubscribeToEvent or signal.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.
  • OnSubscribe must 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 Object at offset zero of the native base, as in all rbfx types.
  • A script error in OnSubscribe goes to the log, as for each call from the host. The other objects go on.
  • The rule is not for HOT_AOT_OPTIMIZED code: that code does not reload.
  • The smoke test CheckResubscribe (Tests/ScriptSmokeTest/Data/Scripts/SubscribeProbe.hot) shows the replay with the class SubscribeProbe.

Rules

  • Call LoadScript and ReloadScript on 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 needs clang++ and its resource folder.
  • The process must have one copy of the Hot++ runtime state. With a shared engine, Rbfx.Script.Core is a shared library, and all plugins link it. Each plugin calls ScriptSystem::GetOrCreateShared. It registers a ScriptSystem only 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 of ScriptSystem are 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 plugin STATIC_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.

Editor demo

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.

Play mode

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.

Smoke test

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.

Embedding

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::AddIncludeDir and ScriptSystem::AddCompilerFlag before the first load.
  • Call ScriptSystem::SetCacheDir before 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::SetCompileCommandsDir before the first load to write compile_commands.json for the IDE. The database needs the cache.
  • ScriptSystem::GetCacheStats returns 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>.inl with the arrays kEngineIncludeDirs and kEngineDefines. Include the file in one source file of the host and give the arrays to the ScriptSystem.

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.

Script layers, mods and the user folder

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).

  • ListScripts returns the union of the names. Each name is in the list one time.
  • ReadText and Exists use the top-most layer that has the name.
  • GetModificationStamp comes 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.

Pack the scripts into a .pak file

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.

No run-time compile platforms

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.Core links hot::runtime and not hot::backend. Hot++ builds no clang or JIT backend. The build still makes hotc for the AOT step.
  • The compile definition RBFX_SCRIPT_RUNTIME_COMPILE=0 is PUBLIC on Rbfx.Script.Core. The game code sees it.
  • The ScriptSystem never creates the backend. No process starts. No file is polled for a reload.
  • LoadPrecompiled runs 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.
  • LoadScript and ReloadScript for a script that needs a compile give an error.
  • rbfx_script_add_aot works 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.