chore(shaders): call draw canvases from the draw command and gate met… (#12489) afccc14a00
chore(shaders): call draw canvases from the draw command and gate methods to ensure they are not called from other contexts

Co-authored-by: hernan <hernan@rive.app>
diff --git a/.rive_head b/.rive_head
index 35e5bee..0ad027a 100644
--- a/.rive_head
+++ b/.rive_head
@@ -1 +1 @@
-a53f08a914c857ab7a54788e9b854da8cb418859
+afccc14a00df430d075bd60c35bed1422d126eab
diff --git a/include/rive/artboard.hpp b/include/rive/artboard.hpp
index 136ce88..8a7e336 100644
--- a/include/rive/artboard.hpp
+++ b/include/rive/artboard.hpp
@@ -22,6 +22,7 @@
 #include "rive/virtualizing_component.hpp"
 #include "rive/input/focus_node.hpp"
 #include "rive/semantic/semantic_node.hpp"
+#include "rive/lua/scripting_vm.hpp"
 
 #include <queue>
 #include <unordered_set>
@@ -91,6 +92,9 @@
     std::vector<ScriptedObject*> m_ScriptedObjects;
     std::vector<AdvancingComponent*> m_advancingComponents;
     rcp<DataContext> m_DataContext = nullptr;
+#ifdef WITH_RIVE_SCRIPTING
+    ScriptingVM* m_scriptingVM = nullptr;
+#endif
     bool m_JoysticksApplyBeforeUpdate = true;
 
     unsigned int m_DirtDepth = 0;
@@ -333,6 +337,7 @@
     void addScriptedObject(ScriptedObject* object);
 
     void drawCanvases();
+    void internalDrawCanvases();
 
     /// Poll async work (image decodes, etc.) so promises resolve before
     /// script callbacks run. Called at the top of advance().
@@ -372,6 +377,9 @@
         return m_ComponentLists;
     }
     rcp<DataContext> dataContext() { return m_DataContext; }
+#ifdef WITH_RIVE_SCRIPTING
+    void scriptingVM(ScriptingVM* value) { m_scriptingVM = value; }
+#endif
     NestedArtboard* nestedArtboard(const std::string& name) const;
     NestedArtboard* nestedArtboardAtPath(const std::string& path) const;
 
diff --git a/include/rive/file.hpp b/include/rive/file.hpp
index c90376e..77149a7 100644
--- a/include/rive/file.hpp
+++ b/include/rive/file.hpp
@@ -255,6 +255,7 @@
 
 private:
     ImportResult read(BinaryReader&, const RuntimeHeader&);
+    std::unique_ptr<ArtboardInstance> instanceArtboard(Artboard* ab) const;
 
     /// The file's backboard. All Rive files have a single backboard
     /// where the artboards live.
diff --git a/include/rive/lua/rive_lua_libs.hpp b/include/rive/lua/rive_lua_libs.hpp
index 1a5674e..ffb5148 100644
--- a/include/rive/lua/rive_lua_libs.hpp
+++ b/include/rive/lua/rive_lua_libs.hpp
@@ -1417,6 +1417,11 @@
     void setOreFrameOpen(bool open) { m_oreFrameOpen = open; }
     bool oreFrameOpen() const { return m_oreFrameOpen; }
 
+    // True while Artboard::drawCanvases() is actively walking scripted
+    // objects to invoke their drawCanvas() Lua callbacks.
+    void setCanvasDrawingPhase(bool value) { m_canvasDrawingPhase = value; }
+    bool canvasDrawingPhase() const { return m_canvasDrawingPhase; }
+
     // WebGL/WASM only: GL context handle saved at riveGPUBeginFrame so
     // riveGPUEndFrame can restore the caller's context afterwards.
     void setPrevGLContext(intptr_t h) { m_prevGLContext = h; }
@@ -1441,6 +1446,7 @@
     void* m_renderContext = nullptr;
     uint64_t m_ownerId = 0;
     bool m_oreFrameOpen = false;
+    bool m_canvasDrawingPhase = false;
     intptr_t m_prevGLContext = 0;
 #ifdef __EMSCRIPTEN__
     int m_glHandle = 0;
@@ -1513,6 +1519,32 @@
     ScriptedObject* m_previous;
 };
 
+class ScopedCanvasDrawingPhase
+{
+public:
+    ScopedCanvasDrawingPhase(ScriptingContext* context) :
+        m_context(context),
+        m_previous(context == nullptr ? false : context->canvasDrawingPhase())
+    {
+        if (m_context != nullptr)
+        {
+            m_context->setCanvasDrawingPhase(true);
+        }
+    }
+
+    ~ScopedCanvasDrawingPhase()
+    {
+        if (m_context != nullptr)
+        {
+            m_context->setCanvasDrawingPhase(m_previous);
+        }
+    }
+
+private:
+    ScriptingContext* m_context;
+    bool m_previous;
+};
+
 class ScriptedDataValue
 {
 public:
diff --git a/src/artboard.cpp b/src/artboard.cpp
index 8c7241c..fda2df9 100644
--- a/src/artboard.cpp
+++ b/src/artboard.cpp
@@ -48,6 +48,9 @@
 #include "rive/layout/layout_data.hpp"
 #include "rive/profiler/profiler_macros.h"
 #include "rive/scripted/scripted_object.hpp"
+#ifdef WITH_RIVE_SCRIPTING
+#include "rive/lua/rive_lua_libs.hpp"
+#endif
 #include "rive/async/work_pool.hpp"
 
 #include <set>
@@ -891,6 +894,25 @@
 
 void Artboard::drawCanvases()
 {
+#ifdef WITH_RIVE_SCRIPTING
+    if (m_scriptingVM)
+    {
+        auto* L = m_scriptingVM->state();
+        if (L != nullptr)
+        {
+            auto* context =
+                static_cast<ScriptingContext*>(lua_getthreaddata(L));
+            ScopedCanvasDrawingPhase phase(context);
+            internalDrawCanvases();
+            return;
+        }
+    }
+#endif
+    internalDrawCanvases();
+}
+
+void Artboard::internalDrawCanvases()
+{
     for (auto obj : m_ScriptedObjects)
     {
         obj->scriptDrawCanvas();
@@ -902,7 +924,7 @@
             auto* nested = artboardHost->artboardInstance(i);
             if (nested != nullptr)
             {
-                nested->drawCanvases();
+                nested->internalDrawCanvases();
             }
         }
     }
@@ -1570,6 +1592,7 @@
 void Artboard::draw(Renderer* renderer)
 {
     sm_frameId++;
+    drawCanvases();
     drawInternal(renderer);
 }
 
diff --git a/src/file.cpp b/src/file.cpp
index a268afb..e218702 100644
--- a/src/file.cpp
+++ b/src/file.cpp
@@ -793,22 +793,35 @@
     return ab ? ab->name() : "";
 }
 
+std::unique_ptr<ArtboardInstance> File::instanceArtboard(Artboard* ab) const
+{
+    if (ab)
+    {
+        auto artboardInstance = ab->instance();
+#ifdef WITH_RIVE_SCRIPTING
+        artboardInstance->scriptingVM(m_scriptingVM.get());
+#endif
+        return artboardInstance;
+    }
+    return nullptr;
+}
+
 std::unique_ptr<ArtboardInstance> File::artboardDefault() const
 {
     auto ab = this->artboard();
-    return ab ? ab->instance() : nullptr;
+    return instanceArtboard(ab);
 }
 
 std::unique_ptr<ArtboardInstance> File::artboardAt(size_t index) const
 {
     auto ab = this->artboard(index);
-    return ab ? ab->instance() : nullptr;
+    return instanceArtboard(ab);
 }
 
 std::unique_ptr<ArtboardInstance> File::artboardNamed(std::string name) const
 {
     auto ab = this->artboard(name);
-    return ab ? ab->instance() : nullptr;
+    return instanceArtboard(ab);
 }
 
 rcp<BindableArtboard> File::bindableArtboardNamed(std::string name) const
diff --git a/src/lua/lua_artboards.cpp b/src/lua/lua_artboards.cpp
index dd83eff..7c5011a 100644
--- a/src/lua/lua_artboards.cpp
+++ b/src/lua/lua_artboards.cpp
@@ -72,7 +72,15 @@
     auto scriptedRenderer = lua_torive<ScriptedRenderer>(L, 2);
 
     auto renderer = scriptedRenderer->validate(L);
-    scriptedArtboard->artboard()->draw(renderer);
+    scriptedArtboard->artboard()->drawInternal(renderer);
+
+    return 0;
+}
+
+static int artboard_draw_canvas(lua_State* L)
+{
+    auto scriptedArtboard = lua_torive<ScriptedArtboard>(L, 1);
+    scriptedArtboard->artboard()->internalDrawCanvases();
 
     return 0;
 }
@@ -148,6 +156,8 @@
         {
             case (int)LuaAtoms::draw:
                 return artboard_draw(L);
+            case (int)LuaAtoms::drawCanvas:
+                return artboard_draw_canvas(L);
             case (int)LuaAtoms::advance:
                 return artboard_advance(L);
             case (int)LuaAtoms::instance:
diff --git a/src/lua/renderer/lua_gpu.cpp b/src/lua/renderer/lua_gpu.cpp
index 04ab02e..1d23fdf 100644
--- a/src/lua/renderer/lua_gpu.cpp
+++ b/src/lua/renderer/lua_gpu.cpp
@@ -2637,6 +2637,14 @@
         luaL_error(L, "GPU context not initialized");
     }
 
+    auto* scriptingContext =
+        static_cast<ScriptingContext*>(lua_getthreaddata(L));
+    if (scriptingContext == nullptr || !scriptingContext->canvasDrawingPhase())
+    {
+        luaL_error(L,
+                   "GPUCanvas:beginRenderPass() called outside drawing phase");
+    }
+
     RenderPassDesc passDesc{};
     passDesc.colorCount = 1;
     // Default: if the canvas has an MSAA color texture, render into it and
@@ -3150,6 +3158,12 @@
     {
         luaL_error(L, "Canvas: renderCtx not initialized");
     }
+    auto* scriptingContext =
+        static_cast<ScriptingContext*>(lua_getthreaddata(L));
+    if (scriptingContext == nullptr || !scriptingContext->canvasDrawingPhase())
+    {
+        luaL_error(L, "Canvas:beginFrame() called outside drawing phase");
+    }
     if (self->m_state != CanvasState::Idle)
     {
         luaL_error(L, "Canvas:beginFrame() called during an active frame");
diff --git a/tests/unit_tests/runtime/scripting/scripting_canvas_drawing_phase_test.cpp b/tests/unit_tests/runtime/scripting/scripting_canvas_drawing_phase_test.cpp
new file mode 100644
index 0000000..82058f5
--- /dev/null
+++ b/tests/unit_tests/runtime/scripting/scripting_canvas_drawing_phase_test.cpp
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2026 Rive
+ */
+
+// Tests for the canvasDrawingPhase gate.  The flag is set by
+// `Artboard::drawCanvases()` via `ScopedCanvasDrawingPhase` and is checked by
+// the Lua bindings that start canvas-level GPU work — `Canvas:beginFrame()`
+// and `GPUCanvas:beginRenderPass()` — so a script can't begin a canvas draw
+// from a non-draw callback (state-machine input handler, Coop event, async
+// completion, …).
+//
+// `Canvas` and `GPUCanvas` are gated behind `RIVE_CANVAS` / `RIVE_ORE` build
+// flags that aren't enabled in the unit-test build, so we can't exercise
+// those bindings directly here.  Instead we cover the gate at the C++ level
+// via the `ScopedCanvasDrawingPhase` RAII helper, and verify that the
+// non-gated `Artboard:drawCanvas()` binding (which has no GPU dependency)
+// continues to be callable from any phase.
+
+#include "catch.hpp"
+#include "scripting_test_utilities.hpp"
+#include "rive/lua/rive_lua_libs.hpp"
+#include "rive_file_reader.hpp"
+
+using namespace rive;
+
+TEST_CASE("ScopedCanvasDrawingPhase toggles the flag and restores it",
+          "[scripting]")
+{
+    ScriptingTest vm("function noop():() end");
+    lua_State* L = vm.state();
+    auto* context = static_cast<ScriptingContext*>(lua_getthreaddata(L));
+    REQUIRE(context != nullptr);
+
+    // Default state: not in a drawing phase.
+    CHECK(context->canvasDrawingPhase() == false);
+
+    {
+        ScopedCanvasDrawingPhase phase(context);
+        CHECK(context->canvasDrawingPhase() == true);
+
+        // Nested scopes preserve the previous (true) value when they unwind,
+        // so reentrant draws don't accidentally clear the outer phase.
+        {
+            ScopedCanvasDrawingPhase nested(context);
+            CHECK(context->canvasDrawingPhase() == true);
+        }
+        CHECK(context->canvasDrawingPhase() == true);
+    }
+
+    // Restored to the original false after the outer scope unwinds.
+    CHECK(context->canvasDrawingPhase() == false);
+}
+
+TEST_CASE("ScopedCanvasDrawingPhase tolerates a null context", "[scripting]")
+{
+    // Some host code paths (e.g. early init / teardown) may not have a
+    // ScriptingContext yet.  The RAII helper has to be a no-op in that case
+    // rather than crash, since `Artboard::drawCanvases()` constructs it
+    // unconditionally.
+    ScopedCanvasDrawingPhase phase(nullptr);
+    SUCCEED("ScopedCanvasDrawingPhase(nullptr) did not crash");
+}
+
+TEST_CASE("Artboard:drawCanvas() is callable regardless of drawing phase",
+          "[scripting]")
+{
+    // `Artboard:drawCanvas()` itself is not gated — only the canvas-level GPU
+    // entry points (`Canvas:beginFrame()`, `GPUCanvas:beginRenderPass()`) are.
+    // Verify the binding succeeds both inside and outside the drawing phase.
+    // `coin.riv` has no scripted objects so internalDrawCanvases() walks an
+    // empty list and returns cleanly in either case.
+    ScriptingTest vm("function callDrawCanvas(artboard:Artboard):()\n"
+                     "  artboard:drawCanvas()\n"
+                     "end\n");
+    lua_State* L = vm.state();
+    auto* context = static_cast<ScriptingContext*>(lua_getthreaddata(L));
+    REQUIRE(context != nullptr);
+    REQUIRE(context->canvasDrawingPhase() == false);
+
+    auto file = ReadRiveFile("assets/coin.riv", vm.serializer());
+    auto artboard = file->artboard();
+    REQUIRE(artboard != nullptr);
+    lua_newrive<ScriptedArtboard>(L,
+                                  L,
+                                  file,
+                                  artboard->instance(),
+                                  nullptr,
+                                  nullptr);
+
+    // Outside the drawing phase: still succeeds.
+    lua_getglobal(L, "callDrawCanvas");
+    lua_pushvalue(L, -2);
+    CHECK(lua_pcall(L, 1, 0, 0) == LUA_OK);
+
+    // Inside the drawing phase: also succeeds.
+    {
+        ScopedCanvasDrawingPhase phase(context);
+        CHECK(context->canvasDrawingPhase() == true);
+        lua_getglobal(L, "callDrawCanvas");
+        lua_pushvalue(L, -2);
+        CHECK(lua_pcall(L, 1, 0, 0) == LUA_OK);
+    }
+
+    // Phase restored to false after the scope.
+    CHECK(context->canvasDrawingPhase() == false);
+}