flutter3d
Showcase Changelog 62 packages API reference

Eighty sparks in one draw, fire and smoke in two

since 0.8.3 The Flame bridge

A Flame game with many small things of one shape does not need a scene node for each. InstancedObject3dComponent is an ordinary Flame component that takes a slot in a shared InstancedMeshNode while it is in the game, and the batch is one draw however many are in it. Blasts come from Particles3dComponent, a particle pool on Flame's clock.

Step 1: One batch for every spark #

The mesh and the material are the batch's. It grows if it has to.

/// Every spark's mesh and material, drawn in one call however many there
/// are; each spark takes a slot in it while it is in the game.
late final InstancedMeshNode batch = InstancedMeshNode(
  DeviceMesh.upload(device, CuboidShape(size: Vector3.all(0.12)).build()),
  RenderMaterial(
    name: 'spark',
    baseColor: LinearColor.fromSrgb(1.0, 0.8, 0.4, 1.0),
    emissive: LinearColor(1.0, 0.6, 0.2),
    emissiveStrength: 3.0 * RenderMaterial.defaultEmissiveStrength,
  ),
  capacity: _sparks,
  name: 'sparks',
);

Step 2: Sparks as Flame components #

Each spark sets its own position as any Flame component would, and writes it into its slot only when it moved. Removing one gives its slot back at once, and the last spark in the batch moves into the hole.

@override
void onOpen3d() {
  addAll(<Component>[
    for (var i = 0; i < _sparks; i++)
      _Spark(batch, i * 2.0 * math.pi / _sparks, 1.5 + (i % 4) * 0.5),
    _fire,
    _smoke,
  ]);
}

Step 3: Fire adds light, smoke takes it away #

The fire pool draws additively. The smoke pool uses the darkening blend, which multiplies what is behind a puff by one minus its colour, so smoke can be dark without the particles being sorted.

/// Fire adds light and smoke takes it away: two pools, two draws.
final Particles3dComponent _fire = Particles3dComponent(
  system: ParticleSystem(capacity: 256),
  plane: BridgePlane.ground(),
);
final Particles3dComponent _smoke = Particles3dComponent(
  system: ParticleSystem(capacity: 128),
  plane: BridgePlane.ground(),
);

Both are drawn once the game has the renderer, in onRenderer3d.

@override
void onRenderer3d(Renderer renderer) {
  _fire.drawWith(renderer, _shard);
  _smoke.drawWith(renderer, _puff, blend: MeshParticleContributor.darkening);
}