flutter3d
Showcase Changelog 62 packages API reference

Sharing runs and racing ghosts

since 1.0.0-rc.1 Simulation, audio and XR

A player finishes a level and wants a friend to try to beat the run. What has to travel is the level, which version of it this is, and the run itself as a .f3drun, the starting state plus a tape of what the player did. ShareBundle holds those three. RunService files a bundle with a sharing service and gets a short code back, and opens a bundle again from its code. On the friend's side, the tape is played back through the same simulation, and where the runner went becomes a pose track to race against as a ghost.

On this page the translucent ball is the ghost of a shared run, weaving down the strip. The orange ball is you, running straight and a little slower. Switch on Open it in the longer track and the same run is opened in an edited version of the level. It is refused there, and no ghost appears.

Step 1: A game with a level in it #

The game is a runner on a strip, steered by the stick and stopped at the far end of the track. The finish is read from the level's one brush, so lengthening the track changes the level's hash and changes what a run through it means.

/// A runner on a strip, steered by the stick. The run is won past the far
/// end of the level's track, so the level is part of the run.
final class _Runner extends HeadlessRun {
  _Runner(this.input, this.finish);

  final InputState input;
  final double finish;
  final Vector3 _at = Vector3.zero();

  @override
  RunOutcome outcome = RunOutcome.playing;

  @override
  void step(double dt) {
    if (outcome.isOver) return;
    _at
      ..x += input.moveAxis.x * 4.0 * dt
      ..z += input.moveAxis.y * 4.0 * dt;
    if (_at.x >= finish) outcome = RunOutcome.won;
  }

  @override
  Snapshot save() => Snapshot(<String, Object?>{
    'x': _at.x,
    'z': _at.z,
    'outcome': outcome.name,
  });

  @override
  WorldPosition get position => _at.toWorldPosition();

  @override
  WorldPosition get eye => _at.toWorldPosition();

  @override
  void aim(Vector3 out) => out.setValues(1.0, 0.0, 0.0);

  @override
  String get summary => 'at ${_at.x.toStringAsFixed(2)}';

  @override
  Map<String, Object?> get reading => <String, Object?>{'x': _at.x};
}

/// The track, as a level document: one brush, whose far end is the finish.
Level _track({double length = 16.0}) => Level(
  name: 'strip',
  materials: <String, LevelMaterial>{'stone': LevelMaterial()},
  brushes: <Brush>[
    Brush(
      center: WorldPosition(length / 2, -0.25, 0.0),
      size: Vector3(length, 0.5, 4.0),
      material: 'stone',
    ),
  ],
);

_Runner _start(Level level, InputState input) {
  final Brush strip = level.brushes.first;
  return _Runner(input, strip.center.x + strip.size.x / 2);
}

Step 2: Record the run #

A run is recorded the way a game records it. The input goes on the tape before each step, a digest of the state is taken every ten steps after it, and the level's hash is stored with them. The page also writes down where the runner was after every step, to compare the ghost with later.

/// Plays [level] the way a person might — weaving down the strip — and
/// writes it down as a game does: the tape before each step, a checkpoint
/// after it. [steps] gets where the runner was after each step.
Demo _record(Level level, List<Vector3> steps) {
  final input = InputState();
  final run = _start(level, input);
  final start = run.save();
  final recorder = InputTapeRecorder(seed: 1);
  final trace = DigestTrace(every: 10);
  steps.add(run.position.toVector3Relative(WorldPosition.origin));
  for (var step = 1; !run.outcome.isOver; step++) {
    // Inside the unit circle, so the input never rescales the stick and
    // the tape holds exactly what the step read.
    input.setStickAxis(0.8, 0.55 * math.sin(step * 0.06));
    recorder.record(input);
    input.beginStep();
    run.step(1.0 / 60.0);
    trace.observe(step, run.save().toJson());
    input.endStep();
    steps.add(run.position.toVector3Relative(WorldPosition.origin));
  }
  return Demo(
    level: 'levels/strip.json',
    levelHash: level.digestHex,
    start: start,
    tape: recorder.tape,
    buildStamp: 'showcase',
    checkpoints: trace,
    simulation: SimulationVersion.engineOnly,
  );
}

Step 3: A service in memory #

RunService does no networking of its own. It is handed a function that carries one request and answers with the response. A game passes the HTTP client it already has, and a test passes the server's handler. This page passes a map. Its two routes answer in the shapes the reference server in cloud/server uses, and the POST route reads the bundle back with ShareBundle.fromJson before filing it, as the server does.

/// The `v1/shares` routes, answered from a map: a bundle filed under a code
/// made from its bytes, and opened by that code.
RunTransport _inMemory(Map<String, Map<String, Object?>> store) =>
    (RunRequest request) async {
      final List<String> path = request.uri.pathSegments;
      if (request.method == 'POST' && path.last == 'shares') {
        final json = jsonDecode(request.body!) as Map<String, Object?>;
        try {
          // The server reads the bundle the way the client wrote it, and
          // refuses one whose run is for another level just the same.
          ShareBundle.fromJson(json);
        } on ShareFormatException catch (e) {
          return RunResponse(422, jsonEncode({'message': e.message}));
        }
        final String address = contentDigestHex(json);
        final String code = address.substring(0, 6).toUpperCase();
        store[code] = json;
        return RunResponse(
          201,
          jsonEncode({
            'code': code,
            'address': address,
            'status': ShareStatus.published.name,
          }),
        );
      }
      if (request.method == 'GET' && path.length >= 2) {
        final Map<String, Object?>? bundle = store[path.last];
        return bundle == null
            ? RunResponse(
                404,
                jsonEncode({'message': 'no share "${path.last}"'}),
              )
            : RunResponse(200, jsonEncode({'bundle': bundle}));
      }
      return const RunResponse(404, '{"message":"no such route"}');
    };

Step 4: Share it, and open it by its code #

The bundle is built from the level document and the run, filed, and opened again by the code that comes back. Every call answers ServiceDone or ServiceRefused with a sentence. None of them throw, so an unreachable server is handled like any other refusal.

final service = RunService(
  base: Uri.parse('https://shares.invalid/'),
  transport: _inMemory(_store),
);
final ServiceAnswer<SharedBundle> filed = await service.share(
  ShareBundle(game: 'showcase-strip', level: _level.toJson(), run: run),
);
if (filed case ServiceDone(value: final SharedBundle shared)) {
  _code = shared.code;
}
// A friend types the code in.
final ServiceAnswer<ShareBundle> opened = await service.open(_code);
if (opened case ServiceDone(value: final ShareBundle bundle)) {
  final (:ghost, :says) = _ghostOf(
    Level.fromJson(bundle.level),
    bundle.run!,
  );
  _ghost = ghost;
  _ghostSays = says;
}

Step 5: The ghost is the run played again #

The pose track is not sent. A bundle carries a tape and a starting state, and the simulation is deterministic, so the friend's machine plays the tape into a fresh run of the level and writes down where the runner was, thirty times a second. A GhostPlayback of that track gives the ghost's place at any moment, interpolated between samples.

/// Where the runner of a shared run was: [demo]'s tape played into a fresh
/// run of [level], the position written down as it goes. Refused, with the
/// reason, when the run was recorded in another version of the level.
({GhostTape? ghost, String says}) _ghostOf(Level level, Demo demo) {
  if (demo.levelHash != level.digestHex) {
    return (
      ghost: null,
      says: 'the run was made in another version of this level',
    );
  }
  final input = InputState();
  final run = _start(level, input);
  final recorder = GhostRecorder(hz: 30.0);
  const dt = 1.0 / 60.0;
  final String? refused = demo.refusalOn(SimulationVersion.engineOnly);
  if (refused != null) return (ghost: null, says: refused);
  final playback = InputTapePlayback(
    demo,
    simulation: SimulationVersion.engineOnly,
  );
  var step = 0;
  recorder.record(
    0.0,
    position: run.position.toVector3Relative(WorldPosition.origin),
    yaw: 0.0,
  );
  while (!playback.isFinished) {
    playback.applyTo(input);
    input.beginStep();
    run.step(dt);
    input.endStep();
    step++;
    recorder.record(
      step * dt,
      position: run.position.toVector3Relative(WorldPosition.origin),
      yaw: 0.0,
    );
  }
  return (
    ghost: recorder.finish(step * dt),
    says: 'a ghost of ${(step * dt).toStringAsFixed(1)} s',
  );
}

Step 6: Another version of the level is refused #

If the run was recorded in another version of the level, the ghost would run through walls that are not there. ShareBundle refuses that run before it leaves the machine and names both hashes, because the person sharing it can record it again and the person opening it cannot. The ghost maker refuses it a second time on the other side.

// The same run with the track made longer: refused before it leaves,
// and refused again by whoever opens it in that level.
try {
  ShareBundle(game: 'showcase-strip', level: _edited.toJson(), run: run);
} on ShareFormatException catch (e) {
  _bundleRefused = e.message;
}
_editedSays = _ghostOf(_edited, run).says;

Step 7: What has to hold #

The run has to come back from its code as a ghost. The edited level has to be refused both ways. At every sample, the ghost has to be exactly where the original runner was at that moment, compared bit for bit, and its last sample has to be at the finish line.

// Filed, opened by its code, and played to a ghost.
final GhostTape? ghost = _ghost;
if (_code.length != 6 || ghost == null) {
  throw StateError('the run did not come back as a ghost: "$_ghostSays"');
}
// A run for another version of the level is refused, both ways.
if (!_bundleRefused.contains('another version of the level') ||
    !_editedSays.contains('another version')) {
  throw StateError('the edited level was not refused');
}
// The ghost is where the original runner was, to the bit, at every
// sample, and it ends where the run ended.
for (final GhostFrame pose in ghost.poses) {
  final Vector3 was = _original[(pose.timeSeconds * 60.0).round()];
  if (pose.position != was) {
    throw StateError(
      'at ${pose.timeSeconds} s the ghost is at ${pose.position}, '
      'the run was at $was',
    );
  }
}
// Thirty samples a second, so the last is within a step of the line.
if (ghost.poses.last.position.x < 15.9) {
  throw StateError('the ghost did not reach the finish');
}

Note. The real service files a bundle under the SHA-256 of its bytes and gives it a short Crockford code. The map here uses the engine's 32-bit content digest, which is enough to tell two documents apart on one machine and too short to name one among everybody's uploads. Moderation is left out: on a real server a share can wait in review before anyone can open it. Our own instance is not deployed yet, and there is no web viewer for a code. A run recorded on the other physics backend is refused as well. This toy has no physics, so the page does not show that case.