warmUp method

Future<void> warmUp(
  1. List<RenderView> views, {
  2. bool includeOffscreen = false,
  3. Duration? sliceBudget,
  4. bool allShadingTiers = false,
  5. List<Node> extraNodes = const [],
})

Compiles the render pipelines and uploads the GPU resources this scene needs, by encoding one frame offscreen and discarding it, so the first visible frame does not stall while shaders compile or textures upload.

Pass the same views the scene will be shown with: their cameras, anti-aliasing, render targets, and this scene's lights and post-process settings determine which pipeline variants compile, so a warm-up frame must match the real one (the offscreen frame is rendered tiny, since a pipeline's identity does not depend on resolution). Populate the scene first; warm-up encodes whatever is attached when it runs.

A SceneView with warmUp: true calls this before it reveals the scene. Awaiting it is optional and safe to repeat. It awaits initializeStaticResources first, and whatever on-demand shaders and tables the scene and views have started loading (see preload). On backends that compile pipelines lazily on first draw (the common case) this front-loads that cost. On a backend that compiles in parallel (WebGL2 with KHR_parallel_shader_compile), it starts every compile before drawing with any, then waits for them without blocking, so the warm-up takes about as long as the slowest one rather than their sum.

Set includeOffscreen to encode every render item once. This costs more during loading, but avoids later pipeline stalls as a moving camera first reaches parts of a large scene.

With sliceBudget, the warm-up builds new pipelines for at most that long per offscreen frame, skips the draws that still need one, and yields to the event loop before the next, until nothing is left. A slow device then keeps answering input and animating its loading screen instead of blocking for the whole compile (Android declares an app that ignores input for ten seconds not responding). A single build longer than the budget still runs whole.

Lit materials draw with a lean shader while the scene uses none of the features it leaves out (ambient occlusion, rect area lights, the irradiance field, environment cross-fades, parallax reflection boxes, and point-light shadows), and with the full shader otherwise. Set allShadingTiers to compile both now, so turning one of those features on or off later does not stall a frame on its first draw. It roughly doubles the lit pipelines warm-up compiles.

extraNodes draw in the warm-up frames as if the scene held them, so content added later (a spawned prefab, an editor's new primitive) compiles now. Each frame attaches them in front of the first view's camera and detaches them before it ends, so they never show in a visible frame. Pass nodes no scene holds.

Implementation

Future<void> warmUp(
  List<RenderView> views, {
  bool includeOffscreen = false,
  Duration? sliceBudget,
  bool allShadingTiers = false,
  List<Node> extraNodes = const [],
}) async {
  _checkNotDisposed('warmUp');
  await initializeStaticResources();
  if (views.isEmpty || _disposed) {
    return;
  }
  // A frame held for on-demand shaders compiles nothing.
  await deferredResourcesSettled(views);
  // On GLES the engine compiles a pipeline on the raster thread and blocks
  // this thread on the result
  // (`flutter::gpu::RenderPass::GetOrCreatePipeline`), so a raster thread
  // parked in `eglSwapBuffers` would freeze Dart for the whole swap. Await
  // it first so the compiles find it idle.
  await awaitRasterThread();
  if (_disposed) return;
  // Encode real frames into a scratch surface that is never presented, so
  // the live surface keeps its targets. A small area is enough because
  // pipeline identity is resolution-independent.
  final warmUpRegion = resolveWarmUpRegion(
    lastSwapchainWidth: surface.lastSwapchainColorTexture(0)?.width ?? 0,
    lastSwapchainHeight: surface.lastSwapchainColorTexture(0)?.height ?? 0,
  );
  final warmUpSurface = Surface();
  void encode() {
    _warmUpIncludeOffscreen = includeOffscreen;
    _inWarmUp = true;
    // The tier frames follow the first while its GPU work still runs, and a
    // paced frame encodes nothing, so pacing is off while they encode.
    final framesInFlight = maxGpuFramesInFlight;
    if (allShadingTiers) maxGpuFramesInFlight = 0;
    final holder = extraNodes.isEmpty
        ? null
        : (Node(
            name: 'warm-up',
            localTransform: _warmUpPlacement(views.first.camera),
          )..addAll(extraNodes));
    if (holder != null) add(holder);
    try {
      // With allShadingTiers, the frame encodes once under each lit tier
      // (one of them is the frame's own), so a later feature toggle that
      // switches tiers finds its pipelines built.
      for (final tier
          in allShadingTiers ? const [true, false] : const [null]) {
        shadingTierOverride = tier;
        // A zero step, so warm-up frames never move the scene's clock
        // before the first real frame (render then skips its wall-clock
        // tick).
        update(0.0);
        _renderViewGroupsInternal(
          [
            for (final view in views) RenderViewGroup([view]),
          ],
          null,
          region: warmUpRegion,
          pixelRatio: 1.0,
          surfaceOverride: warmUpSurface,
        );
      }
    } finally {
      if (holder != null) {
        remove(holder);
        extraNodes.forEach(holder.remove);
      }
      shadingTierOverride = null;
      maxGpuFramesInFlight = framesInFlight;
      _warmUpIncludeOffscreen = false;
      _inWarmUp = false;
    }
  }

  try {
    // Draws whose pipeline is still compiling are skipped, so one frame
    // starts every compile it needs before any draw waits on one; the next
    // frame, after they finish, draws with them.
    if (sliceBudget == null) {
      for (var frame = 0; frame < 100; frame++) {
        if (frame > 0) await awaitRasterThread();
        if (_disposed) return;
        final paced = _pacedFrameCount;
        final held = withUnreadyPipelinesHeld(encode);
        if (held.isEmpty && _pacedFrameCount == paced) return;
        await awaitPipelinesReady(held);
      }
      return;
    }
    // Each slice is a whole offscreen frame; stop once one encodes every view
    // and skips nothing, or after a generous cap if something never finishes
    // building. A view paced by GPU backpressure re-presents its last image
    // and resolves no pipelines, so it proves nothing.
    for (var slice = 0; slice < 1000; slice++) {
      // Each slice compiles pipelines after a yield, so rendezvous again.
      if (slice > 0) await awaitRasterThread();
      if (_disposed) return;
      final paced = _pacedFrameCount;
      final held = withUnreadyPipelinesHeld(
        () => withPipelineBuildBudget(sliceBudget, encode),
      );
      if (_pacedFrameCount == paced && deferredPipelineBuilds == 0) return;
      if (held.isNotEmpty) await awaitPipelinesReady(held);
      await Future<void>.delayed(const Duration(milliseconds: 16));
    }
  } finally {
    warmUpSurface.dispose();
    _warmUpTaaState?.dispose();
    _warmUpTaaState = null;
    if (_warmUpSsgiHistoryColor != null) {
      gpu.gpuHost.releaseTexture(_warmUpSsgiHistoryColor!);
      _warmUpSsgiHistoryColor = null;
    }
  }
}