Add modular story library and shared-progress translations

This commit is contained in:
Hadrian Burkhardt
2026-11-03 17:15:15 +01:00
parent 5b9a76fb53
commit d45cd0698a
30 changed files with 2694 additions and 495 deletions
+225 -57
View File
@@ -3,10 +3,14 @@ import 'dart:convert';
import 'package:flutter/services.dart';
import 'puzzle.dart';
import 'library.dart';
class CampaignLevel {
CampaignLevel(Map<String, dynamic> data)
: chapter = data['chapter'],
: id = data['id'] as String? ?? '',
chapterId = data['chapterId'] as String? ?? data['chapter'],
size = data['size'] as int? ?? 7,
chapter = data['chapter'],
title = data['title'],
object = data['object'],
before = data['before'],
@@ -17,21 +21,30 @@ class CampaignLevel {
picture = (data['picture'] as String).split('').map(int.parse).toList(),
clues = data['clues'],
areas = data['areas'];
final String id, chapterId;
final int size;
final String chapter, title, object, before, after, clues, areas;
final String beforeContinuation, afterContinuation;
final String? illustrationAsset;
final List<int> picture;
Puzzle puzzle() {
final p = Puzzle(7, picture);
final p = Puzzle(size, picture);
if (clues.isNotEmpty) {
for (final c in clues.split(',')) {
p.given[int.parse(c)] = true;
final index = int.parse(c);
if (index < 0 || index >= picture.length) {
throw FormatException('Invalid fixed clue: $id: $index');
}
p.given[index] = true;
}
}
if (areas.isNotEmpty) {
var i = 0;
for (final a in areas.split(';')) {
final v = a.split(',').map(int.parse).toList();
if (v.length != 4) {
throw FormatException('Invalid region: $id');
}
p.regions.add(
Region(String.fromCharCode(65 + i++), v[0], v[1], v[2], v[3]),
);
@@ -61,9 +74,10 @@ class StoryPage {
this.speaker = '',
this.illustrationAsset,
this.continuation = '',
this.caption = '',
});
final String id, title, text;
final String continuation;
final String continuation, caption;
final StoryPageType type;
final int? campaignIndex;
final String speaker;
@@ -71,68 +85,222 @@ class StoryPage {
}
class Book {
Book(this.premise, this.levels, this.pages, this.tracks);
Book(
this.premise,
this.levels,
this.pages,
this.tracks, {
this.id = 'mara-island',
this.title = 'Mara’s notebook',
this.description = '',
this.language = 'en',
this.defaultLanguage = 'en',
this.presentation = 'mara',
this.coverAsset = 'assets/artwork/home-notebook-cover-v2.png',
this.continueAt = 4,
this.initiallyAccessible = 3,
this.fontFamily = 'MaraHand',
this.copy = const {},
});
final String id, title, description, language, defaultLanguage, presentation;
final String? coverAsset, fontFamily;
final int? continueAt;
final int initiallyAccessible;
final Map<String, String> copy;
final String premise;
final List<CampaignLevel> levels;
final List<StoryPage> pages;
final Map<String, dynamic> tracks;
bool get isMara => presentation == 'mara';
List<String> get chapters => levels.map((l) => l.chapterId).toSet().toList();
List<int> chapterLevels(int chapter) => [
for (var i = 0; i < levels.length; i++)
if (levels[i].chapterId == chapters[chapter]) i,
];
int chapterFor(int level) => chapters.indexOf(levels[level].chapterId);
String puzzleKey(int index) => id == 'mara-island'
? 'story_v1_$index'
: 'story_${id}_${levels[index].id}';
int pageFor(int campaignIndex, StoryPageType type) => pages.indexWhere(
(p) => p.campaignIndex == campaignIndex && p.type == type,
);
static Future<Book> load() async {
final campaign = jsonDecode(
await rootBundle.loadString('assets/campaign.json'),
) as Map<String, dynamic>;
final scripts = jsonDecode(
await rootBundle.loadString('assets/narration/scripts.json'),
) as List;
final tracks =
jsonDecode(
await rootBundle.loadString(
'assets/audio/narration_manifest.json',
),
)['tracks']
as Map<String, dynamic>;
final levels = (campaign['levels'] as List)
.map((e) => CampaignLevel(e))
.toList();
final notebook = jsonDecode(
await rootBundle.loadString('assets/notebook.json'),
) as Map<String, dynamic>;
return Book(
campaign['premise'],
levels,
(notebook['pages'] as List).map((record) {
final index = record['campaignIndex'] as int?;
final text = switch (record['textSource']) {
'before' => levels[index!].before,
'after' => levels[index!].after,
'recording' =>
scripts
.where((s) => s['pageId'] == record['id'])
.map((s) => (s['baseText'] ?? s['text']) as String)
.firstOrNull ??
'',
_ => record['text'] as String? ?? '',
};
return StoryPage(
record['id'],
record['title'],
text,
type: StoryPageType.values.byName(record['type']),
campaignIndex: index,
speaker: record['speaker'] as String? ?? '',
illustrationAsset: record['illustrationAsset'] as String?,
continuation:
record['continuation'] as String? ??
switch (record['textSource']) {
'before' => levels[index!].beforeContinuation,
'after' => levels[index!].afterContinuation,
_ => '',
},
static Future<Book> load() async =>
(await StoryLibrary.load()).open('mara-island');
static Future<Book> loadDefinition(
StoryDefinition definition, {
String language = 'en',
AssetBundle? bundle,
}) async {
final assets = bundle ?? rootBundle;
Future<dynamic> read(String path) async =>
jsonDecode(await assets.loadString(path));
final campaign = Map<String, dynamic>.from(
await read(definition.campaignAsset),
);
final notebook = await read(definition.notebookAsset);
final scripts = definition.scriptsAsset == null
? <dynamic>[]
: await read(definition.scriptsAsset!) as List;
final actualLanguage = definition.languageFor(language);
final locale = definition.languages[actualLanguage] as Map;
final translation = locale['asset'] == null
? <String, dynamic>{}
: Map<String, dynamic>.from(await read(locale['asset']));
final translatedLevels = translation['levels'] as Map? ?? {};
final translatedPages = translation['pages'] as Map? ?? {};
// Translations may only replace presentation fields, never puzzle identity
// or rules. A missing field falls back to the original text.
const levelText = [
'chapter',
'title',
'object',
'before',
'after',
'beforeContinuation',
'afterContinuation',
'illustrationAsset',
];
const pageText = [
'title',
'text',
'speaker',
'continuation',
'caption',
'illustrationAsset',
];
Map<String, dynamic> overlay(
Map<String, dynamic> base,
Map? translated,
List<String> fields,
) => {
...base,
for (final field in fields)
if (translated?[field] is String) field: translated![field],
};
final levels = (campaign['levels'] as List).map((record) {
final base = Map<String, dynamic>.from(record);
base['chapterId'] ??= base['chapter'];
return CampaignLevel(
overlay(base, translatedLevels[base['id']], levelText),
);
}).toList();
final pages = (notebook['pages'] as List).map((record) {
final index = record['campaignIndex'] as int?;
if (index != null && (index < 0 || index >= levels.length)) {
throw FormatException('Unknown puzzle on page ${record['id']}');
}
final text = switch (record['textSource']) {
'before' => levels[index!].before,
'after' => levels[index!].after,
'recording' =>
scripts
.where((s) => s['pageId'] == record['id'])
.map((s) => (s['baseText'] ?? s['text']) as String)
.firstOrNull ??
'',
_ => record['text'] as String? ?? '',
};
final base = <String, dynamic>{
...record,
'text': text,
'continuation':
record['continuation'] ??
switch (record['textSource']) {
'before' => levels[index!].beforeContinuation,
'after' => levels[index!].afterContinuation,
_ => '',
},
};
final page = overlay(base, translatedPages[record['id']], pageText);
return StoryPage(
page['id'],
page['title'],
page['text'],
type: StoryPageType.values.byName(page['type']),
campaignIndex: index,
speaker: page['speaker'] as String? ?? '',
illustrationAsset: page['illustrationAsset'] as String?,
continuation: page['continuation'] as String? ?? '',
caption: page['caption'] as String? ?? '',
);
}).toList();
if (levels.isEmpty ||
pages.isEmpty ||
levels.any(
(l) =>
!RegExp(r'^[a-z0-9._-]+$').hasMatch(l.id) ||
l.size < 2 ||
l.size > 10 ||
l.picture.length != l.size * l.size ||
l.picture.any((v) => v != 0 && v != 1),
) ||
levels.map((l) => l.id).toSet().length != levels.length ||
pages.map((p) => p.id).toSet().length != pages.length ||
pages.any((p) => p.id.isEmpty) ||
definition.continueAt != null &&
(definition.continueAt! < 0 ||
definition.continueAt! >= levels.length) ||
pages.any(
(p) =>
[StoryPageType.puzzle, StoryPageType.memory].contains(p.type) &&
p.campaignIndex == null,
)) {
throw FormatException('Invalid story content: ${definition.id}');
}
final seenChapters = <String>{};
String? lastChapter;
for (final level in levels) {
if (level.chapterId != lastChapter &&
!seenChapters.add(level.chapterId)) {
throw FormatException(
'Chapter levels must be contiguous: ${level.chapterId}',
);
}).toList(),
}
lastChapter = level.chapterId;
final puzzle = level.puzzle();
if (puzzle.regions.any(
(r) =>
r.top < 0 ||
r.left < 0 ||
r.width <= 0 ||
r.height <= 0 ||
r.top + r.height > puzzle.size ||
r.left + r.width > puzzle.size,
)) {
throw FormatException('Invalid puzzle region: ${level.id}');
}
}
// Never play original-language narration over translated text. A locale
// supplies its own manifest, or remains readable without a recording.
final trackPath =
locale['tracksAsset'] as String? ??
(actualLanguage == definition.defaultLanguage
? definition.tracksAsset
: null);
final tracks = trackPath == null
? <String, dynamic>{}
: Map<String, dynamic>.from((await read(trackPath))['tracks']);
return Book(
translation['premise'] as String? ?? campaign['premise'],
levels,
pages,
tracks,
id: definition.id,
title: translation['title'] as String? ?? definition.title,
description:
translation['description'] as String? ?? definition.description,
language: actualLanguage,
defaultLanguage: definition.defaultLanguage,
presentation: definition.presentation,
coverAsset: translation['coverAsset'] as String? ?? definition.coverAsset,
continueAt: definition.continueAt,
initiallyAccessible: definition.initiallyAccessible.clamp(
0,
levels.length - 1,
),
fontFamily: locale['fontFamily'] as String?,
copy: Map<String, String>.from(translation['copy'] as Map? ?? {}),
);
}
}