fix: 修复迁移后的基础UI显示问题

This commit is contained in:
cancerai committed 2026-10-25 16:03:05 +08:00
1 parent 18017f819a
commit a93e06f60c
68 files changed
+2293 -8404

No files matched your search

File diff suppressed because it is too large. Load diff
+52 -33
View File
@@ -1,25 +1,45 @@
// 游戏画布:把 World 在 800×608 虚拟分辨率下的渲染做信箱(letterbox)缩放。
// 游戏画布:把 World 的虚拟视口渲染铺满整个屏幕(全屏、无信箱黑边)。
// 虚拟视口保证 800×608 始终完整可见(不裁游戏内容),另一维随屏幕比例
// 自动加宽:例如 2340×1080 的横屏手机 → 视口约 1318×608(横向看得更多),
// 与 PC 游戏支持任意宽高比的做法一致。
import 'dart:ui' show Canvas, Rect, Paint, Color;
import 'dart:math' show min;
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:iwbtc/src/core/app_error.dart' show AppError;
import 'package:iwbtc/src/game/world.dart' show World, W, H;
/// 计算 800×608 虚拟画面在给定屏幕尺寸下的信箱矩形(居中、等比缩放)。
///
/// 画布和虚拟手柄都用它:横屏手机宽高比远大于画面比例,两侧会出现黑边,
/// 手柄按钮必须锚定在**画面区域**内,否则会漂到黑边上(手指按到的位置和
/// 屏幕上看到的游戏内容对不上)。尺寸非法(尚未布局完成)时返回 Rect.zero。
Rect letterboxRect(Size size) {
if (!size.width.isFinite || !size.height.isFinite) return Rect.zero;
if (size.width <= 0 || size.height <= 0) return Rect.zero;
final s = min(size.width / W, size.height / H);
if (!s.isFinite || s <= 0) return Rect.zero;
final double w = W * s;
final double h = H * s;
return Rect.fromLTWH(
(size.width - w) / 2, (size.height - h) / 2, w, h);
/// 屏幕对应的虚拟视口:缩放系数 + 视口尺寸(虚拟像素)。
class StageMetrics {
final double scale;
final double vw;
final double vh;
const StageMetrics(this.scale, this.vw, this.vh);
bool get isValid =>
scale > 0 &&
scale.isFinite &&
vw.isFinite &&
vh.isFinite &&
vw >= W - 0.5 &&
vh >= H - 0.5;
}
/// 计算铺满全屏的虚拟视口(无黑边),且保证 800×608 完整可见:
/// - 屏幕比游戏「更宽」(横屏手机几乎总是如此)→ 高度定标 608,
/// 视口横向加宽到 vw = 屏宽 / scale,游戏内容横向看得更多;
/// - 屏幕比游戏「更窄」→ 宽度定标 800,视口纵向加高到 vh = 屏高 / scale。
/// 摄像机随后按视口尺寸取景(Camera 自带对关卡边界的钳制)。
StageMetrics stageMetrics(Size size) {
if (!size.width.isFinite || !size.height.isFinite) {
return const StageMetrics(0, 0, 0);
}
if (size.width <= 0 || size.height <= 0) return const StageMetrics(0, 0, 0);
if (size.width / size.height >= W / H) {
final s = size.height / H;
return StageMetrics(s, size.width / s, H);
}
final s = size.width / W;
return StageMetrics(s, W, size.height / s);
}
class GameCanvas extends StatelessWidget {
@@ -32,9 +52,7 @@ class GameCanvas extends StatelessWidget {
// 用 SizedBox.expand 明确占满父级,避免 CustomPaint 使用 Size.infinite
// 时在部分平台上拿到零尺寸/无穷尺寸,算出 scale = 0 而整屏消失(表现为黑屏)。
return SizedBox.expand(
child: CustomPaint(
painter: _GamePainter(world, repaint),
),
child: CustomPaint(painter: _GamePainter(world, repaint)),
);
}
}
@@ -48,21 +66,21 @@ class _GamePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// 信箱外框(黑色)
canvas.drawRect(
Rect.fromLTWH(0, 0, size.width, size.height),
Paint()..color = const Color(0xff000000));
// 首帧可能尚未完成布局,尺寸为 0 时不要绘制内容(stageMetrics 无效)。
final m = stageMetrics(size);
if (!m.isValid) return;
// 首帧可能尚未完成布局,尺寸为 0 时不要绘制内容(letterboxRect 返回 zero)。
final rect = letterboxRect(size);
if (rect.isEmpty) return;
// 同步虚拟视口(只改纯数值字段,不触发任何通知 —— paint 阶段禁止 notifier)。
world.setViewport(m.vw, m.vh);
canvas.save();
canvas.translate(rect.left, rect.top);
canvas.scale(rect.width / W, rect.width / W);
canvas.clipRect(Rect.fromLTWH(0, 0, W, H));
canvas.scale(m.scale);
canvas.clipRect(Rect.fromLTWH(0, 0, m.vw, m.vh));
// 兜底底色:即使 world.render 抛异常也不会露出透明/白屏。
canvas.drawRect(
Rect.fromLTWH(0, 0, W, H), Paint()..color = const Color(0xff0a0a14));
Rect.fromLTWH(0, 0, m.vw, m.vh),
Paint()..color = const Color(0xff0a0a14),
);
// 渲染异常原本会被静默吞掉,画面变成纯黑。
// 偶发的一帧异常不该让整局报废 —— 只记录日志;但若连续多帧都失败
// (比如某张地图/某种渲染路径真有问题),才升级成占屏错误以便真机诊断。
@@ -84,9 +102,10 @@ class _GamePainter extends CustomPainter {
if (!_loggedFirstPaint) {
_loggedFirstPaint = true;
debugPrint(
'[boot] canvas rendered: screen=${size.width}x${size.height} '
'stage=${rect.width}x${rect.height} at (${rect.left},${rect.top}) '
'state=${world.state}');
'[boot] canvas rendered: screen=${size.width}x${size.height} '
'viewport=${m.vw.toStringAsFixed(0)}x${m.vh.toStringAsFixed(0)} '
'state=${world.state}',
);
}
}
File diff suppressed because it is too large. Load diff
+54 -40
View File
@@ -2,20 +2,19 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:iwbtc/src/core/input.dart' show Input;
import 'package:iwbtc/src/ui/touch_layout.dart'
show BUTTONS, metaSettings;
import 'package:iwbtc/src/ui/touch_layout.dart' show BUTTONS, metaSettings;
import 'package:iwbtc/src/game/world.dart' show World, W;
import 'package:iwbtc/src/ui/game_canvas.dart' show letterboxRect;
class TouchControls extends StatelessWidget {
final World world;
final ValueNotifier<bool> visible;
final ValueNotifier<bool> hasGun;
const TouchControls(
{super.key,
required this.world,
required this.visible,
required this.hasGun});
const TouchControls({
super.key,
required this.world,
required this.visible,
required this.hasGun,
});
@override
Widget build(BuildContext context) {
@@ -24,11 +23,10 @@ class TouchControls extends StatelessWidget {
valueListenable: visible,
builder: (_, bool v, __) {
if (!v) return const SizedBox();
// 按钮锚定在「信箱缩放后的画面矩形」内,而不是整块屏幕:
// 横屏时两侧是黑边,若按全屏百分比定位,左/右/跳跃键会飘到黑边上。
// 画面已铺满全屏(无信箱黑边),按钮直接按整屏百分比定位。
return LayoutBuilder(
builder: (_, BoxConstraints cons) {
final area = letterboxRect(Size(cons.maxWidth, cons.maxHeight));
final area = Rect.fromLTWH(0, 0, cons.maxWidth, cons.maxHeight);
return Stack(
children: <Widget>[
for (final b in BUTTONS)
@@ -68,17 +66,18 @@ class _TouchButton extends StatefulWidget {
/// 空 Rect 表示尚未完成布局,此时不渲染。
final Rect area;
const _TouchButton(
{required this.world,
required this.keyName,
required this.label,
this.label2,
required this.shape,
required this.cx,
required this.cy,
required this.size,
required this.hasGun,
required this.area});
const _TouchButton({
required this.world,
required this.keyName,
required this.label,
this.label2,
required this.shape,
required this.cx,
required this.cy,
required this.size,
required this.hasGun,
required this.area,
});
@override
State<_TouchButton> createState() => _TouchButtonState();
@@ -114,8 +113,14 @@ class _TouchButtonState extends State<_TouchButton> {
}
void _release() {
if (!_pressed) return;
_pressed = false;
// 注意:即便 _pressed 因事件丢失而处于异常状态,也要强制复位虚拟键,
// 否则 touch['jump'] 会卡在 true(漏接松手事件时极易发生),
// 之后每次按下都因 setTouch 的「值未变则直接 return」短路而触发不了
// 新的边沿 —— 表现就是「跳跃键经常失灵、时好时坏」。
if (_pressed) {
_pressed = false;
setState(() {});
}
_shootTimer?.cancel();
_shootTimer = null;
final a = widget.keyName;
@@ -124,7 +129,6 @@ class _TouchButtonState extends State<_TouchButton> {
} else {
Input.setTouch(a, false);
}
setState(() {});
}
@override
@@ -143,10 +147,15 @@ class _TouchButtonState extends State<_TouchButton> {
top: top,
width: sz,
height: sz,
child: Listener(
onPointerDown: (_) => _press(),
onPointerUp: (_) => _release(),
onPointerCancel: (_) => _release(),
// 用 GestureDetector(Pan 识别器会「认领」指针)替代 Listener:
// Listener 不捕获指针,手指在按钮上滑动后于按钮外松手时,松手事件
// 落到别的控件上 → 本按钮的虚拟键永久卡在按下态。Pan 会持续把
// 抬起/取消事件回传给本按钮,松手必定复位。
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) => _press(),
onPanEnd: (_) => _release(),
onPanCancel: () => _release(),
child: ValueListenableBuilder<bool>(
valueListenable: widget.hasGun,
builder: (_, __, ___) {
@@ -160,23 +169,28 @@ class _TouchButtonState extends State<_TouchButton> {
: const Color(0x444a5a7a),
shape: isJump ? BoxShape.circle : BoxShape.rectangle,
borderRadius: isJump ? null : BorderRadius.circular(sz * 0.3),
border: Border.all(
color: const Color(0xff7ae0ff), width: 2),
border: Border.all(color: const Color(0xff7ae0ff), width: 2),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(widget.label,
style: TextStyle(
color: const Color(0xffffffff),
fontSize: sz * 0.32,
fontWeight: FontWeight.bold)),
Text(
widget.label,
style: TextStyle(
color: const Color(0xffffffff),
fontSize: sz * 0.32,
fontWeight: FontWeight.bold,
),
),
if (widget.label2 != null)
Text(widget.label2!,
style: TextStyle(
color: const Color(0xffcfe8ff),
fontSize: sz * 0.16)),
Text(
widget.label2!,
style: TextStyle(
color: const Color(0xffcfe8ff),
fontSize: sz * 0.16,
),
),
],
),
),
+299
View File
@@ -0,0 +1,299 @@
// 触屏手柄布局编辑器:独立全屏页,从「设置 → 自定义按键」进入。
// 背景保持透明,透出下面的实时游戏画布(标题星空 + 刺地带动画),
// 编辑体验与正常玩游戏时完全一致(同样的全屏沉浸、同样的按钮渲染)。
//
// 布局即改即存(每次拖动/缩放都写回存档),返回时无需再点「确定」。
// 位置/大小与真实手柄同一套换算(cx/cy 百分比 + size×k),所见即所得。
import 'package:flutter/material.dart';
import 'package:iwbtc/src/core/save.dart' show Save;
import 'package:iwbtc/src/game/world.dart' show W;
import 'package:iwbtc/src/ui/touch_layout.dart'
show BUTTONS, TouchBtn, metaSettings;
/// 读取某按键当前布局(cx/cy/size)。
Map<String, double> touchLayoutOf(String key) {
final t = metaSettings()['touch'] as Map;
final m = (t[key] as Map?) ?? const <String, dynamic>{};
return <String, double>{
'cx': double.tryParse(m['cx'].toString()) ?? 50,
'cy': double.tryParse(m['cy'].toString()) ?? 50,
'size': double.tryParse(m['size'].toString()) ?? 60,
};
}
void writeTouchLayout(String key, Map<String, double> p) {
(metaSettings()['touch'] as Map)[key] = <String, dynamic>{
'cx': p['cx'],
'cy': p['cy'],
'size': p['size'],
};
// 即改即存:布局写回存档,返回/切后台都不会丢。
Save.flush();
}
class TouchLayoutEditor extends StatefulWidget {
final VoidCallback onDone; // 仅负责返回设置页(布局已即改即存)
const TouchLayoutEditor({super.key, required this.onDone});
@override
State<TouchLayoutEditor> createState() => _TouchLayoutEditorState();
}
class _TouchLayoutEditorState extends State<TouchLayoutEditor> {
@override
Widget build(BuildContext context) {
// 背景保持透明:透出下面的实时游戏画布(标题星空+刺地),
// 编辑体验与正常游戏完全一致(全屏沉浸)。
return Stack(
children: <Widget>[
// 按钮编辑层(铺满全屏,与真实手柄同一坐标系)
Positioned.fill(
child: LayoutBuilder(
builder: (BuildContext _, BoxConstraints cons) {
final double w = cons.maxWidth;
final double h = cons.maxHeight;
// 与 _TouchButton 完全一致的缩放系数,保证编辑所见 = 游戏所得
final double k = (w / W).clamp(0.6, 2.6);
return Stack(
children: <Widget>[
for (final b in BUTTONS) ...<Widget>[
_EditBtn(
b: b,
k: k,
screenW: w,
screenH: h,
onChanged: () => setState(() {}),
),
_ResizeHandle(
b: b,
k: k,
screenW: w,
screenH: h,
onChanged: () => setState(() {}),
),
],
],
);
},
),
),
// 顶部操作行:恢复默认 / 返回
Positioned(
top: 10,
right: 12,
child: Row(
children: <Widget>[
ElevatedButton(
onPressed: () {
final t = metaSettings()['touch'] as Map;
t.clear();
for (final b in BUTTONS) {
t[b.key] = <String, dynamic>{
'cx': b.cx,
'cy': b.cy,
'size': b.size,
};
}
Save.flush();
setState(() {});
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0x991a1a26),
foregroundColor: const Color(0xffffffff),
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
child: const Text('恢复默认', style: TextStyle(fontSize: 13)),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: widget.onDone,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0x995a3a7a),
foregroundColor: const Color(0xffffffff),
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 6,
),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
child: const Text('返回', style: TextStyle(fontSize: 13)),
),
],
),
),
// 底部提示
const Positioned(
left: 0,
right: 0,
bottom: 8,
child: Center(
child: Text(
'点选按钮后可拖动位置 · 拖右下角黄点调整大小(改动即时保存)',
style: TextStyle(color: Color(0x88ffffff), fontSize: 12),
),
),
),
],
);
}
}
class _EditBtn extends StatefulWidget {
final TouchBtn b;
final double k; // 真实手柄同款缩放系数
final double screenW;
final double screenH;
final VoidCallback onChanged;
const _EditBtn({
required this.b,
required this.k,
required this.screenW,
required this.screenH,
required this.onChanged,
});
@override
State<_EditBtn> createState() => _EditBtnState();
}
class _EditBtnState extends State<_EditBtn> {
bool _selected = false;
@override
Widget build(BuildContext context) {
final p = touchLayoutOf(widget.b.key);
final double sz = p['size']! * widget.k;
final double left = p['cx']! / 100 * widget.screenW - sz / 2;
final double top = p['cy']! / 100 * widget.screenH - sz / 2;
final isJump = widget.b.shape == 'jump';
return Positioned(
left: left,
top: top,
width: sz,
height: sz,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(() => _selected = !_selected),
onPanStart: (_) => setState(() => _selected = true),
onPanUpdate: (d) {
final np = touchLayoutOf(widget.b.key);
np['cx'] = (np['cx']! + d.delta.dx / widget.screenW * 100).clamp(
3.0,
97.0,
);
np['cy'] = (np['cy']! + d.delta.dy / widget.screenH * 100).clamp(
4.0,
96.0,
);
writeTouchLayout(widget.b.key, np);
widget.onChanged();
},
child: Container(
decoration: BoxDecoration(
color: _selected
? const Color(0x88ffffff)
: const Color(0x444a5a7a),
shape: isJump ? BoxShape.circle : BoxShape.rectangle,
borderRadius: isJump ? null : BorderRadius.circular(sz * 0.3),
border: Border.all(
color: _selected
? const Color(0xffffd23a)
: const Color(0xff7ae0ff),
width: 2,
),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
widget.b.label,
style: TextStyle(
color: const Color(0xffffffff),
fontSize: sz * 0.3,
fontWeight: FontWeight.bold,
),
),
if (widget.b.label2 != null)
Text(
widget.b.label2!,
style: TextStyle(
color: const Color(0xffcfe8ff),
fontSize: sz * 0.15,
),
),
],
),
),
),
),
);
}
}
/// 缩放手柄:选中按钮后显示在其右下角的小黄点,拖动改变按钮大小。
/// 单独一层 Positioned(在按钮之后 = 绘制在上层),不吃按钮本体的手势。
class _ResizeHandle extends StatefulWidget {
final TouchBtn b;
final double k;
final double screenW;
final double screenH;
final VoidCallback onChanged;
const _ResizeHandle({
required this.b,
required this.k,
required this.screenW,
required this.screenH,
required this.onChanged,
});
@override
State<_ResizeHandle> createState() => _ResizeHandleState();
}
class _ResizeHandleState extends State<_ResizeHandle> {
bool _active = false;
@override
Widget build(BuildContext context) {
final p = touchLayoutOf(widget.b.key);
final double sz = p['size']! * widget.k;
final double left = p['cx']! / 100 * widget.screenW + sz / 2 - 14;
final double top = p['cy']! / 100 * widget.screenH + sz / 2 - 14;
return Positioned(
left: left,
top: top,
width: 26,
height: 26,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanStart: (_) => setState(() => _active = true),
onPanEnd: (_) => setState(() => _active = false),
onPanCancel: () => setState(() => _active = false),
onPanUpdate: (d) {
final np = touchLayoutOf(widget.b.key);
// 向右/向下拖 = 变大,换算回虚拟 size 单位
final double dSize = (d.delta.dx + d.delta.dy) / widget.k;
np['size'] = (np['size']! + dSize).clamp(30.0, 180.0);
writeTouchLayout(widget.b.key, np);
widget.onChanged();
},
child: Container(
decoration: BoxDecoration(
color: _active ? const Color(0xffffd23a) : const Color(0xccffd23a),
shape: BoxShape.circle,
border: Border.all(color: const Color(0xff2a2a3a), width: 1.5),
),
child: const Center(
child: Icon(Icons.open_in_full, size: 14, color: Colors.black87),
),
),
),
);
}
}
+35 -28
View File
@@ -10,18 +10,29 @@ class TouchBtn {
final double cx;
final double cy;
final double size;
const TouchBtn(this.key, this.label, this.shape, this.cx, this.cy, this.size,
[this.label2]);
const TouchBtn(
this.key,
this.label,
this.shape,
this.cx,
this.cy,
this.size, [
this.label2,
]);
}
// 默认布局仿照主流 IWBT 手游截图:左下 ◀▶ 并排、右侧大「跳」、
// 左下角🔫射击 / 右下角▼下蹲、右中上 ↺ 自杀、右上角 ❚❚ 暂停。
const List<TouchBtn> BUTTONS = <TouchBtn>[
TouchBtn('left', '◀', 'round', 12, 80, 62),
TouchBtn('right', '▶', 'round', 24, 80, 62),
TouchBtn('jump', '跳', 'jump', 88, 84, 94),
TouchBtn('shoot', '🔫', 'item', 79, 72, 54, '射击'),
TouchBtn('down', '▼', 'item', 90, 72, 54, '下蹲'),
TouchBtn('pause', '❚❚', 'sm', 81, 58, 42),
TouchBtn('suicide', '↺', 'sm', 90, 58, 42),
TouchBtn('left', '◀', 'round', 12.5, 81, 62),
TouchBtn('right', '▶', 'round', 22, 81, 62),
TouchBtn('shoot', '🔫', 'item', 78.5, 90, 56, '射击'),
TouchBtn('down', '▼', 'item', 94.5, 89, 56, '下蹲'),
TouchBtn('pause', '❚❚', 'sm', 96.5, 8, 40),
TouchBtn('suicide', '↺', 'sm', 91, 56, 52),
// 跳跃键放最后(绘制在最上层):即便与其它键像素重叠,重叠区也优先归跳跃键,
// 避免按下跳跃时落到射击/下蹲键上导致「跳跃键失灵」。
TouchBtn('jump', '跳', 'jump', 85, 73, 78),
];
const List<List<String>> KEY_ACTIONS = <List<String>>[
@@ -38,32 +49,28 @@ const List<List<String>> KEY_ACTIONS = <List<String>>[
Map<String, dynamic> defaultTouch() {
final m = <String, dynamic>{};
for (final b in BUTTONS) {
m[b.key] = <String, dynamic>{
'cx': b.cx,
'cy': b.cy,
'size': b.size,
};
m[b.key] = <String, dynamic>{'cx': b.cx, 'cy': b.cy, 'size': b.size};
}
return m;
}
Map<String, dynamic> defaultSettings() => <String, dynamic>{
'username': '',
'touch': defaultTouch(),
'keys': defaultBindings(),
};
'username': '',
'touch': defaultTouch(),
'keys': defaultBindings(),
};
Map<String, List<String>> defaultBindings() => <String, List<String>>{
'left': <String>['ArrowLeft', 'KeyA'],
'right': <String>['ArrowRight', 'KeyD'],
'up': <String>['ArrowUp', 'KeyW'],
'down': <String>['ArrowDown', 'KeyS'],
'jump': <String>['ShiftLeft', 'ShiftRight', 'Space', 'KeyZ', 'KeyN'],
'shoot': <String>['KeyX', 'KeyJ', 'KeyC', 'KeyM'],
'suicide': <String>['KeyR'],
'restart': <String>['Backspace'],
'pause': <String>['Escape', 'KeyP'],
};
'left': <String>['ArrowLeft', 'KeyA'],
'right': <String>['ArrowRight', 'KeyD'],
'up': <String>['ArrowUp', 'KeyW'],
'down': <String>['ArrowDown', 'KeyS'],
'jump': <String>['ShiftLeft', 'ShiftRight', 'Space', 'KeyZ', 'KeyN'],
'shoot': <String>['KeyX', 'KeyJ', 'KeyC', 'KeyM'],
'suicide': <String>['KeyR'],
'restart': <String>['Backspace'],
'pause': <String>['Escape', 'KeyP'],
};
/// 读取/补全存档里的设置对象(保证 touch / keys 字段齐全)。
Map<String, dynamic> metaSettings() {