Android: move the shell to dm/android and the Vulkan backend to dm/gfx/vulkan

Mirror the iOS layout instead of nesting Android inside dm/host:
- dm/android/app       GameActivity app (manifest, java, res, build_apk.sh)
- dm/android/Sources   front_app.c, touch_app.c, front_headless.c
- dm/android/Makefile  entry point (apk / lib / install / headless / tests);
                       rules in build.mk (was dm/host/Makefile.android),
                       run with dm/host as cwd; outputs in dm/android/build/
- dm/android/tests     t_vk_perf
- dm/gfx/vulkan        nvn_vk.c and friends, next to the Metal backend

Only include paths, build paths and docs change; no code changes.
The Mac / iOS source lists do not pick up gfx/vulkan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-14 16:59:36 +09:00
co-authored by Claude Opus 5.5
parent 3429c6c0a4
commit 3c25cd89fc
26 changed files with 135 additions and 72 deletions
@@ -0,0 +1,287 @@
// 全屏横屏 Activity:SurfaceView 交给 Vulkan 后端出图,上面盖一层触屏 HUD(TouchOverlay);触点 / 手柄 / 软键盘转给 libd2r.so(front_app.c、touch_app.c)。
// Fullscreen landscape Activity: the SurfaceView goes to the Vulkan backend for presenting, with the touch HUD (TouchOverlay) on top; touches / controller / software keyboard go to libd2r.so (front_app.c, touch_app.c).
package org.d2rmobile.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.Choreographer;
import android.view.DisplayCutout;
import android.view.WindowInsets;
import android.widget.FrameLayout;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
public final class GameActivity extends Activity implements SurfaceHolder.Callback {
private static native int nativeStart(String root, int screenW, int screenH);
private static native void nativeSurface(Object surface, float hz);
// 触屏 HUD(touch_app.c),坐标单位 dp | touch HUD (touch_app.c), coordinates in dp
private static native void nativeLayout(float w, float h, float safeL, float safeR);
private static native void nativeTouchEvent(int action, int pid, int[] pids, float[] xs, float[] ys, int n);
private static native int nativeTick();
static native Object[] nativeDraw(int part);
private static native void nativePad(int face, int other, boolean nintendo, float lx, float ly, float rx, float ry);
private static native long nativeFrames();
private static native String[] nativeTextRequest();
private static native void nativeTextResult(boolean ok, String text);
// 前后台:0 onPause、1 onStop(局内等存盘,最多 2.5 s)、2 onStart、3 onResume(front_app.c)| foreground / background: 0 onPause, 1 onStop (waits for the save in a run, at most 2.5 s), 2 onStart, 3 onResume (front_app.c)
private static native void nativeLifecycle(int ev);
// nn::hid 按钮位(dm_input.h)| nn::hid button bits (dm_input.h)
private static final int LS = 1 << 4, RS = 1 << 5, L = 1 << 6, R = 1 << 7, ZL = 1 << 8, ZR = 1 << 9,
PLUS = 1 << 10, MINUS = 1 << 11, LEFT = 1 << 12, UP = 1 << 13, RIGHT = 1 << 14, DOWN = 1 << 15;
private final Handler ui = new Handler(Looper.getMainLooper());
private SurfaceView view;
private boolean started;
private TouchOverlay overlay, joy, goals;
private float safeL, safeR;
private Vibrator vibrator;
private final int[] tPids = new int[32]; private final float[] tXs = new float[32], tYs = new float[32];
private int padFace, padKeys, padHat;
private float lx, ly, rx, ry, lt, rt;
private boolean nintendo;
private AlertDialog textDialog;
// 左上角 FPS 标签:每 1 s 按游戏出帧数更新 | top-left FPS label: refreshed every 1 s from the game's presented frame count
private TextView fps;
private long fpsFrames, fpsTime;
/* 游戏自己按 60 Hz(省电 30 Hz)出帧;120 Hz 面板上软件时钟和垂直同步拍频,帧落在 1/2/3 个 vsync 上抖动,所以把屏幕钉在同分辨率的 60 Hz 模式
* The game paces itself at 60 Hz (30 Hz in eco); on a 120 Hz panel the software clock beats against vsync and frames land on 1/2/3 vsyncs, so pin the panel to the same-resolution 60 Hz mode */
private void pin60Hz() {
if (android.os.Build.VERSION.SDK_INT < 23) return;
android.view.Display d = getWindowManager().getDefaultDisplay();
android.view.Display.Mode cur = d.getMode(), best = null;
for (android.view.Display.Mode m : d.getSupportedModes()) {
if (m.getPhysicalWidth() != cur.getPhysicalWidth() || m.getPhysicalHeight() != cur.getPhysicalHeight()) continue;
if (Math.abs(m.getRefreshRate() - 60f) < 1f) { best = m; break; }
}
if (best == null) return;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.preferredDisplayModeId = best.getModeId();
getWindow().setAttributes(lp);
}
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
// 库的构造函数要按 DM_ROOT 找 dm/derived.tsv(经验表等),所以先设环境变量再加载 | the library's constructors locate dm/derived.tsv (EXP table etc.) via DM_ROOT, so set it before loading
try { android.system.Os.setenv("DM_ROOT", new File(getFilesDir(), "d2r").getAbsolutePath(), true); } catch (Exception e) {}
System.loadLibrary("d2r");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (android.os.Build.VERSION.SDK_INT >= 28)
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
pin60Hz();
view = new SurfaceView(this);
view.getHolder().addCallback(this);
view.setFocusable(true); view.setFocusableInTouchMode(true);
// 主体层与摇杆层分开:手指在摇杆上动时只重画摇杆层(见 touch_app.c op_list)。主体层不设 LAYER_TYPE_HARDWARE:在 Adreno 上那块离屏层刚进游戏的十几秒里会把屏幕顶部合成成台阶状黑块
// the body and joystick layers are separate: while a finger moves on the stick only the joystick layer is redrawn (see touch_app.c op_list). No LAYER_TYPE_HARDWARE on the body layer: on Adreno that offscreen layer composited stepped black blocks at the top of the screen for the first dozen seconds in game
overlay = new TouchOverlay(this, 0);
joy = new TouchOverlay(this, 1);
goals = new TouchOverlay(this, 2); // 小地图任务终点:跟着玩家走每帧变,单独一层不牵动主体层 | minimap quest goals: change every frame as the player walks, own layer so the body layer is untouched
FrameLayout root = new FrameLayout(this);
root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(goals, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(overlay, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(joy, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
fps = new TextView(this);
fps.setTextSize(12); fps.setTextColor(0xffe9d9ba); fps.setBackgroundColor(0x80000000);
fps.setTypeface(android.graphics.Typeface.MONOSPACE); fps.setPadding(12, 4, 12, 4);
root.addView(fps, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
setContentView(root);
// 刘海 / 挖孔:横屏左右的安全边距交给布局(同 iOS safeAreaInsets)| cutout / punch hole: the landscape left / right safe insets go to the layout (like iOS safeAreaInsets)
root.setOnApplyWindowInsetsListener((v, in) -> {
DisplayCutout cut = in.getDisplayCutout();
safeL = cut != null ? cut.getSafeInsetLeft() : 0; safeR = cut != null ? cut.getSafeInsetRight() : 0;
fps.setTranslationX(safeL);
layoutHud(); return in;
});
overlay.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> layoutHud());
vibrator = getSystemService(Vibrator.class);
immersive();
ui.post(textPoll);
}
private void immersive() {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
@Override public void onWindowFocusChanged(boolean focus) { super.onWindowFocusChanged(focus); if (focus) immersive(); }
private void fail(String text) {
TextView t = new TextView(this); t.setText(text); t.setTextSize(18); t.setPadding(48, 48, 48, 48);
t.setTextColor(0xffe9d9ba); t.setBackgroundColor(0xff0d0d0f); setContentView(t);
}
// ---- Surface ----
@Override public void surfaceCreated(SurfaceHolder h) {}
@Override public void surfaceChanged(SurfaceHolder h, int format, int w, int hh) {
if (!started) {
DisplayMetrics m = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(m);
File root = new File(getFilesDir(), "d2r");
int rc = nativeStart(root.getAbsolutePath(), m.widthPixels, m.heightPixels);
if (rc != 0) { fail("游戏文件不全(错误 " + rc + ")\n请把 dm/、romfs/、rt64/ 放到\n" + root.getAbsolutePath()); return; }
started = true;
layoutHud();
Choreographer.getInstance().postFrameCallback(frame);
}
// 同步交出窗口:surfaceDestroyed 返回前后端必须已放手,这里对称处理 | Hand the window over synchronously: the backend must let go before surfaceDestroyed returns, handled symmetrically here
nativeSurface(h.getSurface(), getWindowManager().getDefaultDisplay().getRefreshRate());
}
@Override public void surfaceDestroyed(SurfaceHolder h) {
if (started) nativeSurface(null, 0);
cancelTouches();
}
// ---- 触屏 HUD | touch HUD ----
private void layoutHud() {
if (!started || overlay.getWidth() <= 0) return;
float d = getResources().getDisplayMetrics().density;
nativeLayout(overlay.getWidth() / d, overlay.getHeight() / d, safeL / d, safeR / d);
overlay.invalidate(); joy.invalidate(); goals.invalidate();
}
// 每帧:推进 HUD 状态机(长按、松手脉冲、腰带 …),要重画才 invalidate;掉落震动按档位 | per frame: advance the HUD state machine (long press, release pulse, belt …), invalidate only when a redraw is needed; drop haptics by level
private final Choreographer.FrameCallback frame = new Choreographer.FrameCallback() { public void doFrame(long t) {
if (!started) return;
int r = nativeTick();
if ((r & 1) != 0) overlay.invalidate();
if ((r & 2) != 0) joy.invalidate();
if ((r & 4) != 0) goals.invalidate();
if (t - fpsTime >= 1_000_000_000L) {
long n = nativeFrames();
if (fpsTime != 0) fps.setText(String.format(java.util.Locale.ROOT, "%.1f FPS", (n - fpsFrames) * 1e9 / (t - fpsTime)));
fpsFrames = n; fpsTime = t;
}
int hap = r >> 4 & 3;
if (hap != 0 && vibrator != null && vibrator.hasVibrator())
vibrator.vibrate(VibrationEffect.createPredefined(hap == 1 ? VibrationEffect.EFFECT_HEAVY_CLICK : hap == 2 ? VibrationEffect.EFFECT_CLICK : VibrationEffect.EFFECT_TICK));
Choreographer.getInstance().postFrameCallback(this);
}};
private void cancelTouches() { if (started) nativeTouchEvent(3, -1, null, null, null, 0); }
@Override public boolean onTouchEvent(MotionEvent e) {
if (!started) return true;
int act = e.getActionMasked(), action;
switch (act) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: action = 0; break;
case MotionEvent.ACTION_MOVE: action = 1; break;
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: action = 2; break;
case MotionEvent.ACTION_CANCEL: action = 3; break;
default: return true;
}
float d = getResources().getDisplayMetrics().density;
int n = Math.min(e.getPointerCount(), tPids.length);
for (int i = 0; i < n; i++) { tPids[i] = e.getPointerId(i); tXs[i] = e.getX(i) / d; tYs[i] = e.getY(i) / d; }
int pid = action == 0 || action == 2 ? e.getPointerId(e.getActionIndex()) : -1;
nativeTouchEvent(action, pid, tPids, tXs, tYs, n); // 重画交给同一帧随后的 doFrame(nativeTick 比对指令表) | the redraw is left to the doFrame later in the same frame (nativeTick compares the draw lists)
return true;
}
// ---- 实体手柄 | physical controller ----
private static boolean isPad(int source) {
return (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD || (source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
}
private void padPublish() {
int other = padKeys | padHat | (lt > 0.5f ? ZL : 0) | (rt > 0.5f ? ZR : 0);
nativePad(padFace, other, nintendo, lx, ly, rx, ry);
}
private static float dead(float v) { return Math.abs(v) < 0.12f ? 0 : v; }
@Override public boolean dispatchKeyEvent(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.KEYCODE_BACK && !isPad(e.getSource())) return true; // 系统返回键不退出游戏 | the system back key does not quit the game
if (!started || !isPad(e.getSource())) return super.dispatchKeyEvent(e);
int face = 0, key = 0;
switch (code) {
case KeyEvent.KEYCODE_BUTTON_A: face = 1; break; // 下 | bottom
case KeyEvent.KEYCODE_BUTTON_B: face = 2; break; // 右 | right
case KeyEvent.KEYCODE_BUTTON_X: face = 4; break; // 左 | left
case KeyEvent.KEYCODE_BUTTON_Y: face = 8; break; // 上 | top
case KeyEvent.KEYCODE_BUTTON_L1: key = L; break;
case KeyEvent.KEYCODE_BUTTON_R1: key = R; break;
case KeyEvent.KEYCODE_BUTTON_L2: key = ZL; break;
case KeyEvent.KEYCODE_BUTTON_R2: key = ZR; break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: key = LS; break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: key = RS; break;
case KeyEvent.KEYCODE_BUTTON_START: key = PLUS; break;
case KeyEvent.KEYCODE_BUTTON_SELECT: case KeyEvent.KEYCODE_BACK: key = MINUS; break;
case KeyEvent.KEYCODE_DPAD_UP: key = UP; break;
case KeyEvent.KEYCODE_DPAD_DOWN: key = DOWN; break;
case KeyEvent.KEYCODE_DPAD_LEFT: key = LEFT; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: key = RIGHT; break;
default: return super.dispatchKeyEvent(e);
}
InputDevice d = e.getDevice(); nintendo = d != null && d.getName() != null && d.getName().toLowerCase().matches(".*(nintendo|switch|joy-con).*");
boolean down = e.getAction() == KeyEvent.ACTION_DOWN;
if (face != 0) padFace = down ? padFace | face : padFace & ~face;
else padKeys = down ? padKeys | key : padKeys & ~key;
padPublish();
return true;
}
@Override public boolean dispatchGenericMotionEvent(MotionEvent e) {
if (!started || !isPad(e.getSource()) || e.getAction() != MotionEvent.ACTION_MOVE) return super.dispatchGenericMotionEvent(e);
lx = dead(e.getAxisValue(MotionEvent.AXIS_X)); ly = dead(e.getAxisValue(MotionEvent.AXIS_Y));
rx = dead(e.getAxisValue(MotionEvent.AXIS_Z)); ry = dead(e.getAxisValue(MotionEvent.AXIS_RZ));
lt = Math.max(e.getAxisValue(MotionEvent.AXIS_LTRIGGER), e.getAxisValue(MotionEvent.AXIS_BRAKE));
rt = Math.max(e.getAxisValue(MotionEvent.AXIS_RTRIGGER), e.getAxisValue(MotionEvent.AXIS_GAS));
float hx = e.getAxisValue(MotionEvent.AXIS_HAT_X), hy = e.getAxisValue(MotionEvent.AXIS_HAT_Y);
padHat = (hx < -0.5f ? LEFT : 0) | (hx > 0.5f ? RIGHT : 0) | (hy < -0.5f ? UP : 0) | (hy > 0.5f ? DOWN : 0);
padPublish();
return true;
}
// ---- 软键盘 | software keyboard ----
private final Runnable textPoll = new Runnable() { public void run() {
if (started && textDialog == null) {
String[] r = nativeTextRequest();
if (r != null) showText(r);
}
ui.postDelayed(this, 250);
}};
private void showText(String[] r) {
final EditText edit = new EditText(this);
edit.setSingleLine(true); edit.setText(r[3]); edit.setSelection(edit.getText().length());
if (!r[2].isEmpty()) edit.setHint(r[2]);
int max = Integer.parseInt(r[4]); if (max > 0) edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
String msg = r[1] + (!r[1].isEmpty() && !r[2].isEmpty() ? "\n" : "") + r[2];
textDialog = new AlertDialog.Builder(this).setTitle(r[0].isEmpty() ? "输入" : r[0]).setMessage(msg.isEmpty() ? null : msg).setView(edit)
.setPositiveButton(android.R.string.ok, (d, w) -> { nativeTextResult(true, edit.getText().toString()); textDialog = null; })
.setNegativeButton(android.R.string.cancel, (d, w) -> { nativeTextResult(false, null); textDialog = null; })
.setOnCancelListener(d -> { nativeTextResult(false, null); textDialog = null; })
.create();
textDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
textDialog.show();
}
// ---- 前后台 | foreground / background ----
// 切走时按着的触点和手柄键一并清零:在后台松开收不到「松开」| touches and controller keys held while switching away are cleared: a release in the background never arrives
@Override protected void onPause() {
super.onPause();
if (!started) return;
cancelTouches();
padFace = padKeys = padHat = 0; lx = ly = rx = ry = lt = rt = 0; padPublish();
nativeLifecycle(0);
}
@Override protected void onStop() { super.onStop(); if (started) nativeLifecycle(1); }
@Override protected void onStart() { super.onStart(); if (started) nativeLifecycle(2); }
@Override protected void onResume() { super.onResume(); if (started) nativeLifecycle(3); }
@Override protected void onDestroy() {
ui.removeCallbacks(textPoll);
super.onDestroy();
// 宿主不支持在同一进程里重新起跑:Activity 销毁就结束进程 | The host cannot restart in the same process: end the process when the Activity is destroyed
if (isFinishing()) android.os.Process.killProcess(android.os.Process.myPid());
}
}
@@ -0,0 +1,179 @@
// 局内触屏 HUD 叠加层:照 touch_app.c 每帧给的绘制指令表画(与 iOS DmTouchOverlay.m drawRect 一一对应);坐标单位 dp。
// 素材取自 APK assets:TouchArt/(原版技能图集等)与 hud_v4_ui/(底部 UI v4,gen_hud_v4.py 生成)。本视图不接触摸,触摸由 Activity 交给 nativeTouchEvent。
// In-run touch HUD overlay: draws from the per-frame draw list given by touch_app.c (one-to-one with iOS DmTouchOverlay.m drawRect); units are dp.
// Assets come from the APK assets: TouchArt/ (original game skill atlases etc.) and hud_v4_ui/ (bottom UI v4, generated by gen_hud_v4.py). This view takes no touches; the Activity hands them to nativeTouchEvent.
package org.d2rmobile.app;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import java.io.InputStream;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
final class TouchOverlay extends View {
// 指令码:与 touch_app.c 的 OP_* 一致 | op codes: same as OP_* in touch_app.c
private static final int FILL_ELLIPSE = 1, STROKE_ELLIPSE = 2, LINE = 3, ARC = 4, IMAGE = 5, TEXT = 6, FILL_RECT = 7, V4 = 8, V4TEXT = 9, LABEL = 10, COVER = 11;
private final float density;
private final int part; // 0 = HUD 主体,1 = 摇杆,2 = 小地图任务终点(touch_app.c draw_overlay) | 0 = HUD body, 1 = joystick, 2 = minimap quest goals (touch_app.c draw_overlay)
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG), stroke = new Paint(Paint.ANTI_ALIAS_FLAG),
img = new Paint(Paint.FILTER_BITMAP_FLAG), text = new Paint(Paint.ANTI_ALIAS_FLAG);
private final HashMap<String, Bitmap> bitmaps = new HashMap<>();
private final RectF rf = new RectF(); private final Rect src = new Rect();
private JSONObject ui; private boolean uiLoaded;
TouchOverlay(Context c, int part) {
super(c);
this.part = part;
density = getResources().getDisplayMetrics().density;
fill.setStyle(Paint.Style.FILL); stroke.setStyle(Paint.Style.STROKE);
text.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL)); text.setTextAlign(Paint.Align.CENTER);
setWillNotDraw(false); setClickable(false); setFocusable(false);
}
private Bitmap bitmap(String path) {
if (bitmaps.containsKey(path)) return bitmaps.get(path);
Bitmap b = null;
try (InputStream in = getContext().getAssets().open(path)) {
BitmapFactory.Options o = new BitmapFactory.Options(); o.inScaled = false; o.inPremultiplied = true;
b = BitmapFactory.decodeStream(in, null, o);
} catch (Exception e) { Log.w("d2r", "触屏 HUD:缺素材 " + path); }
bitmaps.put(path, b); return b; // 缺的也记下,不每帧重试 | misses are remembered too, no per-frame retry
}
private JSONObject ui() {
if (!uiLoaded) { uiLoaded = true;
try (InputStream in = getContext().getAssets().open("hud_v4_ui/ui.json")) {
ui = new JSONObject(new String(in.readAllBytes(), "UTF-8"));
} catch (Exception e) { Log.e("d2r", "【红】底部 UI v4:APK 内缺 hud_v4_ui/ui.json"); } }
return ui;
}
private static int rgba(float r, float g, float b, float a) {
return Color.argb(Math.round(Math.max(0, Math.min(1, a)) * 255), Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
}
@Override protected void onDraw(Canvas c) {
Object[] d = GameActivity.nativeDraw(part); if (d == null) return;
float[] o = (float[]) d[0]; String[] s = (String[]) d[1];
c.save(); c.scale(density, density);
for (int p = 0; p + 2 <= o.length; ) {
int code = (int) o[p], n = (int) o[p + 1], a = p + 2; p = a + n;
switch (code) {
case FILL_ELLIPSE: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, fill); break;
case STROKE_ELLIPSE: stroke.setStrokeWidth(o[a + 4]); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, stroke); break;
case LINE: stroke.setStrokeWidth(o[a + 4]); stroke.setStrokeCap(Paint.Cap.BUTT); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); c.drawLine(o[a], o[a + 1], o[a + 2], o[a + 3], stroke); break;
case ARC: { float r = o[a + 2]; stroke.setStrokeWidth(o[a + 5]); stroke.setColor(rgba(o[a + 6], o[a + 7], o[a + 8], o[a + 9]));
rf.set(o[a] - r, o[a + 1] - r, o[a] + r, o[a + 1] + r);
c.drawArc(rf, (float) Math.toDegrees(o[a + 3]), (float) Math.toDegrees(o[a + 4] - o[a + 3]), false, stroke); break; }
case FILL_RECT: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); c.drawRect(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3], fill); break;
case IMAGE: {
Bitmap b = o[a] >= 0 ? bitmap(s[(int) o[a]]) : null;
if (b == null && o[a + 1] >= 0) b = bitmap(s[(int) o[a + 1]]);
if (b == null) break;
if (o[a + 4] > 0) src.set((int) o[a + 2], (int) o[a + 3], (int) (o[a + 2] + o[a + 4]), (int) (o[a + 3] + o[a + 5]));
else src.set(0, 0, b.getWidth(), b.getHeight());
rf.set(o[a + 6], o[a + 7], o[a + 6] + o[a + 8], o[a + 7] + o[a + 9]);
img.setAlpha(Math.round(Math.max(0, Math.min(1, o[a + 10])) * 255));
img.setBlendMode(o[a + 11] == 1 ? BlendMode.LUMINOSITY : null);
c.drawBitmap(b, src, rf, img); img.setBlendMode(null); break; }
case TEXT: { // 矩形内水平居中、顶对齐(同 NSString drawInRect)| centered horizontally, top-aligned in the rect (like NSString drawInRect)
text.setTextSize(o[a + 5]); text.setColor(rgba(.85f, .79f, .65f, o[a + 6]));
c.drawText(s[(int) o[a]], o[a + 1] + o[a + 3] / 2, o[a + 2] - text.getFontMetrics().ascent, text); break; }
case LABEL: {
Bitmap b = bitmap(s[(int) o[a]]);
if (b == null && n > 4 && o[a + 4] >= 0) b = bitmap(s[(int) o[a + 4]]); // 可选第 5 项 = 备用图 | optional 5th value = fallback image
if (b == null) break;
float h = o[a + 3], w = b.getWidth() * h / b.getHeight();
rf.set(o[a + 1] - w / 2, o[a + 2] - h / 2, o[a + 1] + w / 2, o[a + 2] + h / 2); img.setAlpha(255); c.drawBitmap(b, null, rf, img); break; }
case V4TEXT: { JSONObject u = ui(); if (u == null) break;
float hh = getHeight() / density, ww = getWidth() / density;
v4text(c, s[(int) o[a]], u.optJSONObject("badge").optJSONObject("glyphs"), o[a + 1], o[a + 2], (int) o[a + 3], ww, hh / 1320f); break; }
case V4: drawV4(c, o, a, s); break;
case COVER: fill.setColor(Color.BLACK); c.drawRect(0, 0, o[a], o[a + 1], fill); break;
}
}
c.restore();
}
// ---- 底部 UI v4(同 DmTouchOverlay.m drawV4):几何单位 = 2868×1320 效果图像素,x = (像素 − 1434) × u + 宽/2,y = 像素 × u,u = 高/1320 ----
// ---- Bottom UI v4 (same as DmTouchOverlay.m drawV4): geometry unit = pixels of the 2868×1320 mockup, x = (px − 1434) × u + width/2, y = px × u, u = height/1320 ----
private void v4text(Canvas c, String str, JSONObject glyphs, float x, float baseline, int align, float W, float u) {
if (glyphs == null) return;
float adv = 0; for (int i = 0; i < str.length(); i++) { JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g != null) adv += (float) g.optDouble("adv"); }
float pen = align == 1 ? x - adv : x - adv / 2;
img.setAlpha(255);
for (int i = 0; i < str.length(); i++) {
JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g == null) continue;
String f = g.optString("file", null); Bitmap b = f != null && !g.isNull("file") ? bitmap("hud_v4_ui/" + f) : null;
if (b != null) { float l = (pen + (float) g.optDouble("dx") - 1434) * u + W / 2, t = (baseline + (float) g.optDouble("dy")) * u;
rf.set(l, t, l + b.getWidth() * u, t + b.getHeight() * u); c.drawBitmap(b, null, rf, img); }
pen += (float) g.optDouble("adv");
}
}
private float X(float px, float u, float W) { return (px - 1434) * u + W / 2; }
private void blit(Canvas c, Bitmap b, float l, float t, float w, float h, float alpha) {
if (b == null) return; rf.set(l, t, l + w, t + h); img.setAlpha(Math.round(alpha * 255)); c.drawBitmap(b, null, rf, img); img.setAlpha(255);
}
private void digit(Canvas c, int n, float cx, float cy, float alpha, float u, float W) {
Bitmap d = bitmap("hud_v4_ui/diff_" + n + ".png"); if (d == null) return;
blit(c, d, X(cx, u, W) - d.getWidth() * u / 2, cy * u - d.getHeight() * u / 2, d.getWidth() * u, d.getHeight() * u, alpha);
}
private static int rgb(JSONArray a) { return Color.rgb(a.optInt(0), a.optInt(1), a.optInt(2)); }
// v:life, mana, lv(字符串表下标), 十字按住, 有点数, 任务未读, 经验‰, 腰带 ×4, 难度档, 选择条展开
// v: life, mana, lv (string table indices), cross held, has points, quest unread, exp ‰, belt ×4, difficulty level, selector expanded
private void drawV4(Canvas c, float[] o, int a, String[] s) {
JSONObject ui = ui(); if (ui == null) return;
try {
float W = getWidth() / density, u = getHeight() / density / 1320f;
boolean held = o[a + 3] != 0, points = o[a + 4] != 0, alert = points || o[a + 5] != 0;
float exp = o[a + 6]; int players = (int) o[a + 11]; boolean diffOpen = o[a + 12] != 0;
Bitmap full = bitmap("hud_v4_ui/base_full.png"); JSONObject bo = ui.getJSONObject("base");
if (full != null) blit(c, full, X((float) bo.getDouble("x"), u, W), (float) bo.getDouble("y") * u, full.getWidth() * u, full.getHeight() * u, 1);
JSONArray slots = ui.getJSONArray("slots"), s6 = slots.getJSONArray(5);
Bitmap btn = bitmap(alert ? (held ? "hud_v4_ui/lvl_1.png" : "hud_v4_ui/lvl_0.png") : (held ? "hud_v4_ui/lvl_d1.png" : "hud_v4_ui/lvl_d0.png"));
float bl = X((float) s6.getDouble(0), u, W), bt = (float) s6.getDouble(1) * u, bw = (float) (s6.getDouble(2) - s6.getDouble(0)) * u, bh = (float) (s6.getDouble(3) - s6.getDouble(1)) * u;
if (btn != null) {
if (points) { img.setShadowLayer(10 * u, 0, 0, Color.argb(242, 255, 209, 89)); blit(c, btn, bl, bt, bw, bh, 1); img.clearShadowLayer(); }
blit(c, btn, bl, bt, bw, bh, 1);
}
JSONObject e = ui.getJSONObject("exp");
float x0 = (float) e.getDouble("x0"), x1 = (float) e.getDouble("x1"), y = (float) e.getDouble("y"), eh = (float) e.getDouble("h");
fill.setColor(rgb(e.getJSONArray("track"))); c.drawRect(X(x0, u, W), y * u, X(x0, u, W) + (x1 - x0) * u, (y + eh) * u, fill);
stroke.setColor(rgb(e.getJSONArray("edge"))); stroke.setStrokeWidth(u);
c.drawRect(X(x0, u, W) + u / 2, y * u + u / 2, X(x0, u, W) + u / 2 + (x1 - x0 - 1) * u, y * u + u / 2 + (eh - 1) * u, stroke);
fill.setColor(rgb(e.getJSONArray("fill"))); c.drawRect(X(x0 + 1, u, W), (y + 1) * u, X(x0 + 1, u, W) + (x1 - x0 - 2) * u * exp / 1000f, (y + eh - 1) * u, fill);
int ticks = e.getInt("ticks"); fill.setColor(rgb(e.getJSONArray("track")));
for (int t = 1; t < ticks; t++) { float tx = X(x0 + Math.round((x1 - x0) * t / (double) ticks), u, W); c.drawRect(tx, (y + 1) * u, tx + u, (y + eh - 1) * u, fill); }
JSONObject vt = ui.getJSONObject("vital");
v4text(c, s[(int) o[a]], vt.getJSONObject("glyphs"), (float) vt.getDouble("left_x"), (float) vt.getDouble("baseline"), 0, W, u);
v4text(c, s[(int) o[a + 1]], vt.getJSONObject("glyphs"), (float) vt.getDouble("right_x"), (float) vt.getDouble("baseline"), 0, W, u);
JSONObject lv = ui.getJSONObject("lv");
v4text(c, s[(int) o[a + 2]], lv.getJSONObject("glyphs"), (float) lv.getDouble("x"), (float) lv.getDouble("baseline"), 0, W, u);
JSONArray in = ui.getJSONArray("inner"); JSONObject bd = ui.getJSONObject("badge");
for (int i = 1; i <= 4; i++) { int cnt = (int) o[a + 6 + i]; if (cnt == 0) continue;
JSONArray si = slots.getJSONArray(i);
v4text(c, Integer.toString(cnt), bd.getJSONObject("glyphs"), (float) (si.getDouble(0) + in.getDouble(2) + bd.getDouble("dx")), (float) (si.getDouble(1) + in.getDouble(3) + bd.getDouble("dy")), 1, W, u); }
float icx = (float) (in.getDouble(0) + in.getDouble(2) + 1) / 2, icy = (float) (in.getDouble(1) + in.getDouble(3) + 1) / 2;
JSONArray s0 = slots.getJSONArray(0);
if (players >= 1 && players <= 8) digit(c, players, (float) s0.getDouble(0) + icx, (float) s0.getDouble(1) + icy, 1, u, W);
if (diffOpen) {
JSONObject pk = ui.getJSONObject("pick"); Bitmap tile = bitmap("hud_v4_ui/slot.png");
for (int i = 0; i < 8; i++) {
float cx = (float) (pk.getDouble("center_x") + (i - 3.5) * pk.getDouble("pitch")), cy = (float) pk.getDouble("y"), al = i + 1 == players ? 1 : .82f;
if (tile != null) blit(c, tile, X(cx - tile.getWidth() / 2f, u, W), (cy - tile.getHeight() / 2f) * u, tile.getWidth() * u, tile.getHeight() * u, al);
digit(c, i + 1, cx, cy, al, u, W);
}
}
} catch (Exception ex) { Log.e("d2r", "底部 UI v4 绘制失败:" + ex); }
}
}