feat: imported input-box pets, with dsh-Go's sprite packs

Nothing is built in: Settings → 宠物 shows "尚未导入宠物" until a zip is
picked. The zip holds a dsh-Go pack.json and PNG sheets; it is validated
(pack.json, every named sheet) and unpacked under the app's private files
directory, with enable, size (40/52/64) and remove kept on the device.

A pack's canvas, anchor, per-animation box and frame list drive rendering:
PetSlot reserves the area above the baseline and stands the sprite on the
composer's top edge (or on the activity cap while a turn runs). Idle,
thinking, working and error follow the chat's state, and a tap plays the
pack's react-left/react-right. Only one sheet is decoded at a time.

path_provider's JNI binding does not load on this engine, so MainActivity
exposes the files directory over a tiny method channel instead.

dist/deepy-whale-pet.zip is the Deepy whale for testing. Tests cover the
real pack manifest, frame/state mapping and zip import.

0.4.0 (400).
This commit is contained in:
blumia committed 2026-11-22 13:39:49 +08:00
1 parent ff0dbf1b37
commit d72af036a1
16 files changed
+1410 -12

No files matched your search

+2
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'appearance_prefs.dart';
import 'pets/pet_library.dart';
import 'screens/home_screen.dart';
import 'screens/servers_screen.dart';
import 'state.dart';
@@ -25,6 +26,7 @@ class _OpenChamberAppState extends State<OpenChamberApp>
WidgetsBinding.instance.addObserver(this);
app.init();
AppearancePrefs.instance.ensureLoaded();
PetLibrary.instance.ensureLoaded();
}
@override
+306
View File
@@ -0,0 +1,306 @@
// Imported pets live on the device: a zip's `pack.json` and sprite sheets are
// unpacked under the app's documents, and only this client reads them. There
// is no built-in pet; nothing shows until the person imports one.
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:archive/archive.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'pet_pack.dart';
class PetImportException implements Exception {
final String message;
const PetImportException(this.message);
@override
String toString() => message;
}
class PetLibrary extends ChangeNotifier {
PetLibrary._();
static final PetLibrary instance = PetLibrary._();
static const _activeKey = 'pet.active.v1';
static const _enabledKey = 'pet.enabled.v1';
static const _sizeKey = 'pet.size.v1';
/// The canvas width a pet is drawn at; the list offers these.
static const sizes = <double>[40, 52, 64];
PetPack? pack;
bool enabled = false;
double size = 52;
String? _packDir;
bool _loaded = false;
// One decoded sheet at a time: a full sheet can be several megabytes, and
// only the current mood is on screen.
String? _imagePath;
ui.Image? _image;
Future<ui.Image?>? _loading;
bool get hasPet => pack != null;
bool get ready => pack != null && enabled;
Future<void> ensureLoaded() async {
if (_loaded) return;
_loaded = true;
try {
final prefs = await SharedPreferences.getInstance();
enabled = prefs.getBool(_enabledKey) ?? false;
size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80);
final active = prefs.getString(_activeKey);
if (active != null && active.isNotEmpty) {
final root = await _petsRoot();
final dir = Directory('${root.path}/$active');
final manifest = File('${dir.path}/pack.json');
if (await manifest.exists()) {
final json = jsonDecode(await manifest.readAsString());
if (json is Map<String, dynamic>) {
final parsed = PetPack.fromJson(json);
if (parsed.isValid) {
pack = parsed;
_packDir = dir.path;
}
}
}
}
} catch (_) {
// A corrupt or half-written pet must not keep the app from starting.
}
notifyListeners();
}
Future<void> setEnabled(bool value) async {
enabled = value;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_enabledKey, value);
} catch (_) {}
}
Future<void> setSize(double value) async {
size = value.clamp(32, 80);
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_sizeKey, size);
} catch (_) {}
}
/// Unpacks and activates a pet package. [root] is for tests; the app uses
/// the documents directory.
Future<PetPack> importZip(List<int> bytes, {Directory? root}) async {
if (bytes.isEmpty) throw const PetImportException('文件为空');
if (bytes.length > 40 * 1024 * 1024) {
throw const PetImportException('宠物包不能超过 40MB');
}
final Archive archive;
try {
archive = ZipDecoder().decodeBytes(bytes, verify: true);
} catch (_) {
throw const PetImportException('不是有效的 zip 文件');
}
ArchiveFile? manifest;
for (final file in archive.files) {
if (!file.isFile) continue;
final name = file.name.replaceAll('\\', '/');
if (name == 'pack.json' || name.endsWith('/pack.json')) {
if (manifest == null || name.length < manifest.name.length) {
manifest = file;
}
}
}
if (manifest == null) {
throw const PetImportException('压缩包里没有 pack.json');
}
final manifestName = manifest.name.replaceAll('\\', '/');
final base = manifestName == 'pack.json'
? ''
: manifestName.substring(0, manifestName.length - '/pack.json'.length);
final PetPack parsed;
try {
final text = utf8.decode(_content(manifest));
final json = jsonDecode(text);
if (json is! Map<String, dynamic>) throw const FormatException();
parsed = PetPack.fromJson(json);
} catch (_) {
throw const PetImportException('pack.json 不是有效的宠物包');
}
if (!parsed.isValid) {
throw const PetImportException('pack.json 缺少动画或状态');
}
final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name);
final rootDir = root ?? await _petsRoot();
await rootDir.create(recursive: true);
final staging = Directory('${rootDir.path}/.$id.importing');
if (await staging.exists()) await staging.delete(recursive: true);
await staging.create(recursive: true);
try {
var extracted = 0;
for (final file in archive.files) {
if (!file.isFile) continue;
final name = file.name.replaceAll('\\', '/');
if (base.isNotEmpty && !name.startsWith('$base/')) continue;
final rel = base.isEmpty ? name : name.substring(base.length + 1);
if (rel.isEmpty || rel.startsWith('/')) continue;
final segments = rel.split('/');
if (segments.any((s) => s.isEmpty || s == '..' || s == '.')) continue;
final content = _content(file);
extracted += content.length;
if (extracted > 60 * 1024 * 1024) {
throw const PetImportException('解压后超过 60MB');
}
final target = File('${staging.path}/$rel');
await target.parent.create(recursive: true);
await target.writeAsBytes(content, flush: true);
}
for (final animation in parsed.animations.values) {
if (animation.sheet.isEmpty) {
throw PetImportException('动画 ${animation.name} 没有精灵图');
}
final sheet = File('${staging.path}/${animation.sheet}');
if (!await sheet.exists()) {
throw PetImportException('缺少精灵图 ${animation.sheet}');
}
}
final destination = Directory('${rootDir.path}/$id');
if (await destination.exists()) await destination.delete(recursive: true);
await staging.rename(destination.path);
_clearImages();
pack = parsed;
_packDir = destination.path;
enabled = true;
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_activeKey, id);
await prefs.setBool(_enabledKey, true);
} catch (_) {}
notifyListeners();
return parsed;
} catch (_) {
if (await staging.exists()) {
try {
await staging.delete(recursive: true);
} catch (_) {}
}
rethrow;
}
}
Future<void> remove() async {
final dir = _packDir;
pack = null;
_packDir = null;
enabled = false;
_clearImages();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_activeKey);
await prefs.setBool(_enabledKey, false);
} catch (_) {}
if (dir != null) {
try {
await Directory(dir).delete(recursive: true);
} catch (_) {}
}
}
/// The decoded sheet for [animation], held one at a time.
Future<ui.Image?> imageFor(PetAnimation animation) {
final dir = _packDir;
if (dir == null || animation.sheet.isEmpty) return Future.value(null);
final path = '$dir/${animation.sheet}';
if (_imagePath == path) {
if (_image != null) return Future.value(_image);
if (_loading != null) return _loading!;
}
_imagePath = path;
_image?.dispose();
_image = null;
final loading = _decode(path);
_loading = loading;
return loading;
}
Future<ui.Image?> _decode(String path) async {
try {
final bytes = await File(path).readAsBytes();
final codec = await ui.instantiateImageCodec(bytes);
final frame = await codec.getNextFrame();
final image = frame.image;
if (_imagePath != path) {
image.dispose();
return null;
}
_image = image;
return image;
} catch (_) {
return null;
} finally {
if (_imagePath == path) _loading = null;
}
}
void _clearImages() {
_image?.dispose();
_image = null;
_imagePath = null;
_loading = null;
}
static const _appDirChannel = MethodChannel('openchamber/appdir');
Future<Directory> _petsRoot() async {
String? base;
if (Platform.isAndroid) {
// A tiny channel in MainActivity: enough to find the app's files dir
// without the JNI-based path_provider, which this engine cannot load.
try {
base = await _appDirChannel.invokeMethod<String>('documents');
} catch (_) {
// Fall through to the StateError below.
}
} else {
final env = Platform.environment;
final data = env['XDG_DATA_HOME'];
base = data != null && data.isNotEmpty
? '$data/openchamber'
: '${env['HOME'] ?? '.'}/.local/share/openchamber';
}
if (base == null || base.isEmpty) {
throw StateError('no writable directory for pets');
}
final root = Directory('$base/pets');
if (!await root.exists()) await root.create(recursive: true);
return root;
}
static List<int> _content(ArchiveFile file) {
final content = file.content;
return content is List<int> ? content : List<int>.from(content as List);
}
static String _safeId(String raw) {
final id = raw
.toLowerCase()
.replaceAll(RegExp(r'[^a-z0-9._-]+'), '-')
.replaceAll(RegExp(r'^[-._]+|[-._]+$'), '');
return id.isEmpty ? 'pet' : id;
}
}
+213
View File
@@ -0,0 +1,213 @@
// A pet package, in the shape dsh-Go's packs already use: `pack.json` points
// at PNG sprite sheets, each frame cropped from a canvas of a few logical
// pixels, and names the animations for each mood.
import 'dart:ui';
/// One sheet frame in the play order, with how long it stays up.
class PetFrame {
final int index;
final int ms;
const PetFrame(this.index, this.ms);
}
class PetAnimation {
final String name;
final String sheet;
final int frameW;
final int frameH;
final int cols;
final bool loop;
/// Where this animation sits on the pack's logical canvas.
final Rect box;
final List<PetFrame> frames;
const PetAnimation({
required this.name,
required this.sheet,
required this.frameW,
required this.frameH,
required this.cols,
required this.loop,
required this.box,
required this.frames,
});
int get totalMs => frames.fold(0, (sum, f) => sum + f.ms);
factory PetAnimation.fromJson(String name, Map<String, dynamic> j) {
final box = _rect(j['box'], const Rect.fromLTWH(0, 0, 1, 1));
final cols = _int(j['cols'], 1).clamp(1, 4096);
final total = _int(j['ms'], 50 * cols);
final frames = <PetFrame>[];
final raw = j['frames'];
if (raw is List) {
for (final e in raw) {
if (e is! Map) continue;
final ms = _int(e['ms'], 50);
frames.add(PetFrame(_int(e['i'], 0), ms <= 0 ? 50 : ms));
}
}
if (frames.isEmpty) {
final each = (total / cols).round().clamp(16, 2000);
for (var i = 0; i < cols; i++) {
frames.add(PetFrame(i, each));
}
}
return PetAnimation(
name: name,
sheet: j['sheet'] as String? ?? '',
frameW: _int(j['frameW'], (box.width * 5).round()),
frameH: _int(j['frameH'], (box.height * 5).round()),
cols: cols,
loop: j['loop'] != false,
box: box,
frames: frames,
);
}
}
/// What a pack says. Only the parts this client draws are kept; reactions
/// and idle pools are read as far as they can be played.
class PetPack {
final String id;
final String name;
final String author;
final String license;
final String source;
final bool pixelArt;
/// The logical canvas the frames are placed on.
final Size canvas;
/// Where the pet's feet rest on that canvas.
final Offset anchor;
final Rect contentBox;
final Map<String, PetAnimation> animations;
final Map<String, List<String>> states;
/// tapLeft / tapRight / tickle / drag -> animation name.
final Map<String, String> reactions;
const PetPack({
required this.id,
required this.name,
required this.author,
required this.license,
required this.source,
required this.pixelArt,
required this.canvas,
required this.anchor,
required this.contentBox,
required this.animations,
required this.states,
required this.reactions,
});
bool get isValid =>
animations.isNotEmpty && states.values.any((list) => list.any(animations.containsKey));
String? get idleName {
for (final name in states['idle'] ?? const <String>[]) {
if (animations.containsKey(name)) return name;
}
return animations.keys.isEmpty ? null : animations.keys.first;
}
/// The first animation of [state] the pack actually has, then idle.
String? animationForState(String state) {
for (final name in states[state] ?? const <String>[]) {
if (animations.containsKey(name)) return name;
}
return idleName;
}
PetAnimation? animation(String? name) =>
name == null ? null : animations[name];
factory PetPack.fromJson(Map<String, dynamic> j) {
final canvasJson = j['canvas'];
final cw = _double(canvasJson is Map ? canvasJson['w'] : null, 52);
final ch = _double(canvasJson is Map ? canvasJson['h'] : null, cw);
final anchorJson = j['anchor'];
final ax = _double(anchorJson is Map ? anchorJson['x'] : null, cw / 2);
final ay = _double(anchorJson is Map ? anchorJson['baseline'] : null, ch);
final animations = <String, PetAnimation>{};
final rawAnims = j['animations'];
if (rawAnims is Map) {
for (final e in rawAnims.entries) {
final value = e.value;
if (e.key is String && value is Map) {
animations[e.key as String] =
PetAnimation.fromJson(e.key as String, Map<String, dynamic>.from(value));
}
}
}
final states = <String, List<String>>{};
final rawStates = j['states'];
if (rawStates is Map) {
for (final e in rawStates.entries) {
final list = e.value;
if (e.key is String && list is List) {
states[e.key as String] = [
for (final v in list)
if (v is String) v,
];
}
}
}
final reactions = <String, String>{};
final rawReactions = j['reactions'];
if (rawReactions is Map) {
for (final key in const ['tapLeft', 'tapRight', 'tickle', 'drag']) {
final v = rawReactions[key];
if (v is String) {
reactions[key] = v;
} else if (v is Map) {
final file = v['file'];
final files = v['files'];
if (file is String) {
reactions[key] = file;
} else if (files is List && files.isNotEmpty && files.first is String) {
reactions[key] = files.first as String;
}
}
}
}
return PetPack(
id: j['id'] as String? ?? '',
name: j['name'] as String? ?? '',
author: j['author'] as String? ?? '',
license: j['license'] as String? ?? '',
source: j['source'] as String? ?? '',
pixelArt: j['pixelArt'] != false,
canvas: Size(cw, ch),
anchor: Offset(ax, ay),
contentBox: _rect(j['contentBox'], Rect.fromLTWH(0, 0, cw, ch)),
animations: animations,
states: states,
reactions: reactions,
);
}
}
int _int(Object? v, int fallback) =>
v is num ? v.toInt() : (v is String ? int.tryParse(v) ?? fallback : fallback);
double _double(Object? v, double fallback) =>
v is num ? v.toDouble() : (v is String ? double.tryParse(v) ?? fallback : fallback);
Rect _rect(Object? v, Rect fallback) {
if (v is! Map) return fallback;
return Rect.fromLTWH(
_double(v['x'], fallback.left),
_double(v['y'], fallback.top),
_double(v['w'], fallback.width),
_double(v['h'], fallback.height),
);
}
+17
View File
@@ -12,6 +12,7 @@ import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/composer_box.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart';
import '../widgets/slash_palette.dart';
import '../widgets/usage_ring.dart';
@@ -169,6 +170,7 @@ class _ChatScreenState extends State<ChatScreen> {
Expanded(child: _messageList()),
_permissions(),
_forms(),
PetSlot(state: _petState()),
if (chat.running) _activityStrip(),
_composer(widget.keyboardInset),
],
@@ -1341,6 +1343,21 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
/// The mood the pet draws: the same activity the strip shows, then a failed
/// last turn, then idle.
String _petState() {
if (chat.running) {
return _activity().title == '思考中' ? 'thinking' : 'working';
}
for (var i = chat.msgs.length - 1; i >= 0; i--) {
final m = chat.msgs[i];
if (m.type == 'assistant' || m.type == 'idle') {
return m.error != null && !m.error!.isEmpty ? 'error' : 'idle';
}
}
return 'idle';
}
/// What the agent is doing right now, for the strip above the composer.
({String title, String detail}) _activity() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
+2
View File
@@ -9,6 +9,7 @@ import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/composer_box.dart';
import '../widgets/model_controls.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/slash_palette.dart';
import 'files_panel.dart';
@@ -259,6 +260,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
items: _attachments,
onRemove: _removeAttachment,
),
const PetSlot(state: 'idle'),
_composer(theme, widget.keyboardInset),
],
),
+133 -7
View File
@@ -1,8 +1,10 @@
// Settings. Three groups for now: appearance (device-local theme), chat (the
// server's follow-up behavior) and a pet placeholder.
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../appearance_prefs.dart';
import '../pets/pet_library.dart';
import '../state.dart';
class SettingsScreen extends StatefulWidget {
@@ -19,6 +21,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
super.initState();
// Pick up a change made on another client while this page opens.
widget.app.refreshFollowUpBehavior();
PetLibrary.instance.ensureLoaded();
}
@override
@@ -27,7 +30,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
return Scaffold(
appBar: AppBar(title: const Text('设置')),
body: ListenableBuilder(
listenable: Listenable.merge([widget.app, look]),
listenable: Listenable.merge(
[widget.app, look, PetLibrary.instance]),
builder: (context, _) {
final theme = Theme.of(context);
return ListView(
@@ -37,12 +41,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
_appearance(theme, look),
const _SectionHeader('聊天'),
_chat(theme),
const _SectionHeader('宠物'),
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('暂未提供设置',
style: TextStyle(fontSize: 13, color: theme.hintColor)),
),
const _SectionHeader('宠物',
note: '默认不提供;宠物包只存放在本机'),
_pet(theme),
],
);
},
@@ -173,6 +174,131 @@ class _SettingsScreenState extends State<SettingsScreen> {
widget.app.clearLastError();
}
}
// -------------------------------------------------------------------- pet
Widget _pet(ThemeData theme) {
final library = PetLibrary.instance;
final pack = library.pack;
if (pack == null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const ListTile(
title: Text('尚未导入宠物'),
subtitle: Text('默认不提供宠物。导入一个宠物包(.zip)后,它会站在输入框上方。'),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: FilledButton.tonalIcon(
onPressed: _importPet,
icon: const Icon(Icons.file_upload_outlined, size: 18),
label: const Text('导入宠物包'),
),
),
],
);
}
final info = [pack.author, pack.license]
.where((s) => s.trim().isNotEmpty)
.join(' · ');
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
title: Text(pack.name.isEmpty ? pack.id : pack.name),
subtitle: info.isEmpty
? null
: Text(info, maxLines: 2, overflow: TextOverflow.ellipsis),
),
SwitchListTile(
title: const Text('启用宠物'),
subtitle: const Text('站在输入框上方,默认关闭'),
value: library.enabled,
onChanged: (v) => library.setEnabled(v),
),
const _Label('大小'),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Wrap(
spacing: 8,
children: [
for (final (size, label) in const [
(40.0, '小'),
(52.0, '中'),
(64.0, '大'),
])
ChoiceChip(
label: Text(label),
selected: (library.size - size).abs() < 0.5,
onSelected: (_) => library.setSize(size),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 2, 20, 8),
child: Row(
children: [
FilledButton.tonalIcon(
onPressed: _importPet,
icon: const Icon(Icons.swap_horiz, size: 18),
label: const Text('更换宠物包'),
),
const SizedBox(width: 8),
TextButton(
onPressed: _confirmRemovePet,
child: const Text('移除'),
),
],
),
),
],
);
}
Future<void> _importPet() async {
try {
final file = await FilePicker.pickFile(
dialogTitle: '选择宠物包(.zip)',
type: FileType.custom,
allowedExtensions: const ['zip'],
);
if (file == null) return;
final bytes = await file.readAsBytes();
final pack = await PetLibrary.instance.importZip(bytes);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('已导入 ${pack.name.isEmpty ? pack.id : pack.name}')),
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('导入失败:$e')),
);
}
}
Future<void> _confirmRemovePet() async {
final ok = await showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: const Text('移除宠物?'),
content: const Text('本机保存的宠物包会被删除。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(dialog, true),
child: const Text('移除')),
],
),
);
if (ok == true) await PetLibrary.instance.remove();
}
}
class _SectionHeader extends StatelessWidget {
+267
View File
@@ -0,0 +1,267 @@
// The input-box pet. A PetSprite plays the pack's sheet frames; PetSlot is
// the strip it stands on, placed directly above the composer (or the activity
// cap when a turn runs). Nothing renders until a pack is imported and enabled.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../pets/pet_library.dart';
import '../pets/pet_pack.dart';
/// The strip a pet stands on. It reserves the space above the baseline so the
/// sprite does not cover the last message; the feet rest on its bottom edge,
/// which is the composer's (or the activity cap's) top.
class PetSlot extends StatelessWidget {
final String state;
const PetSlot({super.key, required this.state});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: PetLibrary.instance,
builder: (context, _) {
final library = PetLibrary.instance;
final pack = library.pack;
if (!library.enabled || pack == null) return const SizedBox.shrink();
final scale = library.size / pack.canvas.width;
final height = (pack.anchor.dy * scale).clamp(20.0, 80.0);
return SizedBox(
height: height,
child: Align(
alignment: Alignment.bottomCenter,
child: Transform.translate(
// Put the anchor (the feet) on the bottom edge; the rest of the
// canvas hangs above, inside the reserved strip.
offset: Offset(
(pack.canvas.width / 2 - pack.anchor.dx) * scale,
// The composer's own top padding sits between this strip and
// its visible capsule; step over it so the feet land on the
// edge, not above it.
(pack.canvas.height - pack.anchor.dy) * scale + 6,
),
child: PetSprite(
pack: pack,
state: state,
width: library.size,
),
),
),
);
},
);
}
}
class PetSprite extends StatefulWidget {
final PetPack pack;
final String state;
/// The pack canvas's on-screen width; the height follows the canvas ratio.
final double width;
const PetSprite({
super.key,
required this.pack,
required this.state,
required this.width,
});
@override
State<PetSprite> createState() => _PetSpriteState();
}
class _PetSpriteState extends State<PetSprite> {
PetAnimation? _animation;
ui.Image? _image;
String? _sheet;
int _frame = 0;
Timer? _timer;
int _loadToken = 0;
/// A reaction being played; the state resumes when it ends.
String? _oneShot;
String? _pendingState;
@override
void initState() {
super.initState();
_begin(widget.state);
}
@override
void didUpdateWidget(PetSprite oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.pack != widget.pack) {
_oneShot = null;
_pendingState = null;
_begin(widget.state);
} else if (oldWidget.state != widget.state) {
if (_oneShot != null) {
_pendingState = widget.state;
} else {
_begin(widget.state);
}
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _begin(String state) {
final animation = widget.pack.animation(
widget.pack.animationForState(state),
);
if (animation == null) {
_timer?.cancel();
_animation = null;
return;
}
_animation = animation;
_frame = 0;
_showSheet(animation);
_schedule();
}
/// Loads a new sheet; a frame from the old one must not be cropped with the
/// new animation's box, so the image clears while it loads.
void _showSheet(PetAnimation animation) {
if (animation.sheet == _sheet) return;
_sheet = animation.sheet;
_image = null;
final token = ++_loadToken;
PetLibrary.instance.imageFor(animation).then((image) {
if (!mounted || token != _loadToken) return;
setState(() => _image = image);
});
}
void _schedule() {
_timer?.cancel();
final animation = _animation;
if (animation == null || animation.frames.isEmpty) return;
final frame = animation.frames[_frame.clamp(0, animation.frames.length - 1)];
_timer = Timer(Duration(milliseconds: frame.ms), _tick);
}
void _tick() {
final animation = _animation;
if (!mounted || animation == null) return;
if (_frame + 1 < animation.frames.length) {
setState(() => _frame++);
_schedule();
return;
}
final oneShot = _oneShot;
if (oneShot != null) {
_oneShot = null;
final next = _pendingState ?? widget.state;
_pendingState = null;
_begin(next);
setState(() {});
return;
}
if (animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
_begin(widget.state);
setState(() {});
}
void _react(TapDownDetails details) {
final left = details.localPosition.dx < widget.width / 2;
final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight'];
final animation = widget.pack.animation(name);
if (animation == null) return;
_oneShot = name;
_pendingState = widget.state;
_animation = animation;
_frame = 0;
_showSheet(animation);
_schedule();
setState(() {});
}
@override
Widget build(BuildContext context) {
final width = widget.width;
final height = width * widget.pack.canvas.height / widget.pack.canvas.width;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: _react,
child: CustomPaint(
size: Size(width, height),
painter: _PetPainter(
pack: widget.pack,
animation: _animation,
image: _image,
frame: _frame,
),
),
);
}
}
class _PetPainter extends CustomPainter {
final PetPack pack;
final PetAnimation? animation;
final ui.Image? image;
final int frame;
const _PetPainter({
required this.pack,
required this.animation,
required this.image,
required this.frame,
});
@override
void paint(Canvas canvas, Size size) {
final animation = this.animation;
final image = this.image;
if (image == null || animation == null || animation.frames.isEmpty) return;
final cols = animation.cols;
final maxCols = image.width ~/ animation.frameW;
final maxRows = image.height ~/ animation.frameH;
if (maxCols <= 0 || maxRows <= 0) return;
final entry =
animation.frames[frame.clamp(0, animation.frames.length - 1)];
final col = (entry.index % cols).clamp(0, maxCols - 1);
final row = (entry.index ~/ cols).clamp(0, maxRows - 1);
final src = Rect.fromLTWH(
col * animation.frameW.toDouble(),
row * animation.frameH.toDouble(),
animation.frameW.toDouble(),
animation.frameH.toDouble(),
);
final scale = size.width / pack.canvas.width;
final dst = Rect.fromLTWH(
animation.box.left * scale,
animation.box.top * scale,
animation.box.width * scale,
animation.box.height * scale,
);
canvas.drawImageRect(
image,
src,
dst,
Paint()
..filterQuality =
pack.pixelArt ? FilterQuality.none : FilterQuality.medium,
);
}
@override
bool shouldRepaint(_PetPainter oldDelegate) =>
oldDelegate.image != image ||
oldDelegate.animation != animation ||
oldDelegate.frame != frame ||
oldDelegate.pack != pack;
}