Files
openchamber-android-native/lib/widgets/pet_sprite.dart
T
blumia d25167de58 fix: float the pet over the messages and let it be dragged
The pet used to sit in the column above the composer, reserving a strip of
its own: the message list ended there, which read as an opaque band cutting
off the last row. It is now a layer over the message area, so the list keeps
its full height and shows through around the sprite. Only the body of the
sheet takes touches (contentBox, 4dp out); taps and drags on the transparent
canvas still reach the messages underneath.

Dragging the body moves the pet along the composer's top edge (or the
activity cap's) with a small lift while held and the pack's drag reaction.
The spot is stored as a fraction of the width in pet.x.v1, so a restart or a
change in width puts it back in the same place. Taps now react on tap-up so a
drag does not fire a left/right reaction.

0.4.1 (401).
2026-11-22 14:30:30 +08:00

392 lines
12 KiB
Dart

// The input-box pet. A PetSprite plays the pack's sheet frames; PetLayer is
// the floating layer it lives in, placed over the chat's message area so the
// messages keep their full height and show through around the pet. 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 pet over the chat. It reserves no layout space: the message list runs
/// underneath, and only the sprite's body takes touches. The feet rest on the
/// bottom edge of the layer, which is the composer's top (or the activity
/// cap's while a turn runs). Dragging it sideways moves it along that edge.
class PetLayer extends StatefulWidget {
final String state;
const PetLayer({super.key, required this.state});
@override
State<PetLayer> createState() => _PetLayerState();
}
class _PetLayerState extends State<PetLayer> {
/// Where the feet are, as a fraction of the layer's width. Null: use the
/// saved spot.
double? _fraction;
bool _dragging = false;
double _lift = 0;
/// How far from either end the body keeps, logical px.
static const _edge = 8.0;
@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();
return LayoutBuilder(builder: (context, constraints) {
final width = constraints.maxWidth;
final size = library.size;
final scale = size / pack.canvas.width;
final height = size * pack.canvas.height / pack.canvas.width;
// Body extents left and right of the feet, so dragging keeps the
// whole pet on screen.
final leftExtent = (pack.anchor.dx - pack.contentBox.left) * scale;
final rightExtent = (pack.contentBox.right - pack.anchor.dx) * scale;
final lo = leftExtent + _edge;
final hi = width - rightExtent - _edge;
final minFoot = hi <= lo ? width / 2 : lo;
final maxFoot = hi <= lo ? width / 2 : hi;
final fraction = (_fraction ?? library.position).clamp(0.0, 1.0);
final foot = (fraction * width).clamp(minFoot, maxFoot);
// Stand on the composer's top edge. The sprite's own canvas goes a
// little below the anchor, and the composer keeps a few px of top
// padding above its capsule, so step past both; that overflow is
// fine, the layer does not clip.
final bottom =
-((pack.canvas.height - pack.anchor.dy) * scale + 6) + _lift;
return Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: foot - pack.anchor.dx * scale,
bottom: bottom,
width: size,
height: height,
child: PetSprite(
pack: pack,
state: widget.state,
width: size,
dragging: _dragging,
onDragStart: () => setState(() {
_dragging = true;
_lift = -6;
}),
onDragUpdate: (dx) {
final next = ((_fraction ?? library.position) * width + dx)
.clamp(minFoot, maxFoot);
setState(() => _fraction = next / width);
},
onDragEnd: () {
final spot = _fraction;
setState(() {
_dragging = false;
_lift = 0;
});
if (spot != null) library.setPosition(spot);
},
),
),
],
);
});
},
);
}
}
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;
/// A drag is in progress: play the pack's drag reaction while held.
final bool dragging;
/// Called when the body is dragged; the layer moves the pet.
final VoidCallback? onDragStart;
final ValueChanged<double>? onDragUpdate;
final VoidCallback? onDragEnd;
const PetSprite({
super.key,
required this.pack,
required this.state,
required this.width,
this.dragging = false,
this.onDragStart,
this.onDragUpdate,
this.onDragEnd,
});
@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;
/// The drag reaction's name while a drag holds it.
String? _dragAnimation;
@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;
_dragAnimation = null;
_begin(widget.state);
return;
}
if (oldWidget.dragging != widget.dragging) {
_oneShot = null;
if (widget.dragging) {
final drag = widget.pack.reactions['drag'];
_dragAnimation =
drag != null && widget.pack.animations.containsKey(drag) ? drag : null;
final name = _dragAnimation ?? widget.pack.animationForState(widget.state);
if (name != null) _beginNamed(name);
} else {
final next = _pendingState ?? widget.state;
_pendingState = null;
_dragAnimation = null;
_begin(next);
}
return;
}
if (oldWidget.state != widget.state) {
if (_oneShot != null || widget.dragging) {
_pendingState = widget.state;
} else {
_begin(widget.state);
}
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _begin(String state) => _beginNamed(widget.pack.animationForState(state));
void _beginNamed(String? name) {
final animation = widget.pack.animation(name);
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;
}
// Held by a drag: keep the pose until it is let go, even when the pack's
// drag sheet plays once.
if (widget.dragging &&
_dragAnimation != null &&
animation.name == _dragAnimation &&
!animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
if (animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
_begin(widget.state);
setState(() {});
}
void _react(TapUpDetails 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(
// Only the body takes touches; the rest of the layer lets the message
// list scroll.
behavior: HitTestBehavior.deferToChild,
onTapUp: _react,
onHorizontalDragStart: (_) => widget.onDragStart?.call(),
onHorizontalDragUpdate: (details) =>
widget.onDragUpdate?.call(details.delta.dx),
onHorizontalDragEnd: (_) => widget.onDragEnd?.call(),
onHorizontalDragCancel: () => widget.onDragEnd?.call(),
child: CustomPaint(
size: Size(width, height),
painter: _PetPainter(
pack: widget.pack,
animation: _animation,
image: _image,
frame: _frame,
spriteSize: Size(width, height),
),
),
);
}
}
class _PetPainter extends CustomPainter {
final PetPack pack;
final PetAnimation? animation;
final ui.Image? image;
final int frame;
/// The on-screen size, for hit testing.
final Size spriteSize;
const _PetPainter({
required this.pack,
required this.animation,
required this.image,
required this.frame,
required this.spriteSize,
});
/// The body only: taps and drags on the transparent canvas around it go to
/// whatever is underneath.
@override
bool? hitTest(Offset position) {
if (spriteSize.width <= 0) return false;
final scale = spriteSize.width / pack.canvas.width;
final body = Rect.fromLTRB(
pack.contentBox.left * scale,
pack.contentBox.top * scale,
pack.contentBox.right * scale,
pack.contentBox.bottom * scale,
).inflate(4);
return body.contains(position);
}
@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 ||
oldDelegate.spriteSize != spriteSize;
}