Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add a C example that animates the avatar in a terminal

shinshin8621e5e2ad94d3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0a11862..3f9a7b0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -135,3 +135,8 @@ jobs:
- name: Build and run headless C renderer example
run: make -C examples/c run-render
+
+ - name: Build and run terminal C renderer example
+ run: |
+ make -C examples/c terminal
+ COLUMNS=100 LINES=30 target/ffi-terminal-example ../samples/miko-qipao 30 > /dev/null
diff --git a/native/README.ja.md b/native/README.ja.md
index c327fc8..45d465a 100644
--- a/native/README.ja.md
+++ b/native/README.ja.md
@@ -92,6 +92,17 @@ cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --fea
make -C native/examples/c run-render
```
+[ターミナルのサンプル](examples/c/terminal.c)は毎フレーム描画し、RGBAを色付きの半角ブロック文字としてターミナルに表示します。
+ターミナルだけで動き、モーションとかなの口形を短く繰り返します。ターミナルのサイズを変えると描き直し、Ctrl+C で終了します。
+iTerm2、WezTerm、Ghosttyなど24bitカラーに対応したターミナルを使ってください。フォントを小さくするほど細かく表示されます。
+ターミナルマルチプレクサの中では、サイズの変更や色が正しく伝わらないことがあります。
+アバターのパスの後にフレーム数を指定すると、最後のフレームだけを出力して終了します。
+
+```sh
+make -C native/examples/c run-terminal
+native/target/ffi-terminal-example samples/miko-qipao 90 > native/target/frame.txt
+```
+
## デスクトップアプリ
```sh
diff --git a/native/README.md b/native/README.md
index b26f446..613e0b9 100644
--- a/native/README.md
+++ b/native/README.md
@@ -123,6 +123,19 @@ cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --fea
make -C native/examples/c run-render
```
+The [terminal example](examples/c/terminal.c) renders the avatar every frame and
+draws the RGBA buffer as colored half-block characters, so a terminal is all it
+needs. It plays a short loop of motions and kana mouth shapes, follows terminal
+resizes and exits with Ctrl+C. Use a 24-bit color terminal such as iTerm2, WezTerm
+or Ghostty; a smaller font gives a finer image. Terminal multiplexers may not pass
+resizes or colors through reliably. With a frame count after the avatar path, it
+prints only the last frame and exits:
+
+```sh
+make -C native/examples/c run-terminal
+native/target/ffi-terminal-example samples/miko-qipao 90 > native/target/frame.txt
+```
+
## Desktop app
```sh
diff --git a/native/README.zh.md b/native/README.zh.md
index 208fa72..895c187 100644
--- a/native/README.zh.md
+++ b/native/README.zh.md
@@ -87,6 +87,16 @@ cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --fea
make -C native/examples/c run-render
```
+[终端示例](examples/c/terminal.c)每帧渲染一次,并将RGBA以彩色半格方块字符显示在终端中,因此只需要一个终端即可运行。
+它会循环播放简短的动作和假名口型,跟随终端尺寸变化重新绘制,按Ctrl+C退出。
+请使用支持24位色的终端,例如iTerm2、WezTerm或Ghostty;字体越小,画面越精细。在终端复用器中,尺寸变化或颜色可能无法正确传递。
+在头像路径后指定帧数时,只输出最后一帧后退出:
+
+```sh
+make -C native/examples/c run-terminal
+native/target/ffi-terminal-example samples/miko-qipao 90 > native/target/frame.txt
+```
+
## 桌面程序
```sh
diff --git a/native/crates/mesh-avatar-ffi/src/lib.rs b/native/crates/mesh-avatar-ffi/src/lib.rs
index ddc67fc..4cf4290 100644
--- a/native/crates/mesh-avatar-ffi/src/lib.rs
+++ b/native/crates/mesh-avatar-ffi/src/lib.rs
@@ -292,7 +292,7 @@ pub unsafe extern "C" fn mesh_avatar_set_emotion(
})
})
}
-/// Play a built-in motion by its ID, e.g. nod, no, sway or greeting.
+/// Play a built-in motion by its ID, e.g. nod, no, sway or greet.
/// # Safety
/// id must be a readable UTF-8 NUL-terminated string.
#[no_mangle]
diff --git a/native/examples/c/Makefile b/native/examples/c/Makefile
index f5e65ad..fdc1e58 100644
--- a/native/examples/c/Makefile
+++ b/native/examples/c/Makefile
@@ -2,6 +2,7 @@ CC ?= cc
NATIVE := ../..
OUT := $(NATIVE)/target/ffi-example
RENDER_OUT := $(NATIVE)/target/ffi-render-example
+TERMINAL_OUT := $(NATIVE)/target/ffi-terminal-example
LIB := $(NATIVE)/target/release/libmesh_avatar_ffi.a
CFLAGS ?= -std=c11 -O2 -Wall -Wextra -Werror
UNAME_S := $(shell uname -s)
@@ -13,7 +14,7 @@ LDLIBS ?= -ldl -lpthread -lm
RENDER_LDLIBS ?= $(LDLIBS)
endif
-.PHONY: all run render run-render
+.PHONY: all run render run-render terminal run-terminal
all: $(OUT)
$(OUT): main.c $(NATIVE)/include/mesh_avatar.h $(LIB)
$(CC) $(CFLAGS) -I$(NATIVE)/include main.c $(LIB) $(LDLIBS) -o $@
@@ -24,3 +25,8 @@ $(RENDER_OUT): render.c $(NATIVE)/include/mesh_avatar.h $(NATIVE)/include/mesh_a
$(CC) $(CFLAGS) -I$(NATIVE)/include render.c $(LIB) $(RENDER_LDLIBS) -o $@
run-render: $(RENDER_OUT)
$(RENDER_OUT) $(NATIVE)/../samples/miko-qipao $(NATIVE)/target/ffi-render.ppm
+terminal: $(TERMINAL_OUT)
+$(TERMINAL_OUT): terminal.c $(NATIVE)/include/mesh_avatar.h $(NATIVE)/include/mesh_avatar_render.h $(LIB)
+ $(CC) $(CFLAGS) -I$(NATIVE)/include terminal.c $(LIB) $(RENDER_LDLIBS) -o $@
+run-terminal: $(TERMINAL_OUT)
+ $(TERMINAL_OUT) $(NATIVE)/../samples/miko-qipao
diff --git a/native/examples/c/terminal.c b/native/examples/c/terminal.c
new file mode 100644
index 0000000..9669fe6
--- /dev/null
+++ b/native/examples/c/terminal.c
@@ -0,0 +1,195 @@
+/* SIGWINCH and ioctl are BSD extensions outside strict POSIX. */
+#define _DEFAULT_SOURCE
+#define _DARWIN_C_SOURCE
+#include "mesh_avatar_render.h"
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <time.h>
+#include <unistd.h>
+
+#define CHECK(call) do { \
+ MaStatus status_ = (call); \
+ if (status_ != MA_OK) { \
+ fprintf(stderr, "%s: %d: %s\n", #call, status_, mesh_avatar_last_error()); \
+ goto cleanup; \
+ } \
+} while (0)
+
+/* Pixels with less coverage than this show the terminal background. */
+#define ALPHA_CUTOFF 96
+#define FPS 30.0
+
+static volatile sig_atomic_t quit = 0;
+static volatile sig_atomic_t resized = 0;
+static void on_quit(int signal) { (void)signal; quit = 1; }
+static void on_resize(int signal) { (void)signal; resized = 1; }
+
+typedef struct { double at; const char *motion; const char *kana; } Step;
+static const Step script[] = {
+ {0.5, "greet", "こんにちは"},
+ {4.0, "nod", NULL},
+ {6.5, NULL, "めっしゅあばたーです"},
+ {9.5, "sway", NULL},
+};
+#define SCRIPT_LENGTH 13.0
+
+/* One cell per pixel column, two pixel rows per text row; keep the last row for a caption. */
+static void terminal_pixels(uint32_t *width, uint32_t *height) {
+ struct winsize size;
+ unsigned cols = 80, rows = 24;
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0 && size.ws_col && size.ws_row) {
+ cols = size.ws_col;
+ rows = size.ws_row;
+ } else if (getenv("COLUMNS") && getenv("LINES")) {
+ cols = (unsigned)strtoul(getenv("COLUMNS"), NULL, 10);
+ rows = (unsigned)strtoul(getenv("LINES"), NULL, 10);
+ if (cols < 1 || cols > 1000) cols = 80;
+ if (rows < 3 || rows > 500) rows = 24;
+ }
+ *width = cols;
+ *height = rows > 2 ? (rows - 1) * 2 : 2;
+}
+
+typedef struct { char *data; size_t length, capacity; } Text;
+static int append(Text *text, const char *bytes, size_t length) {
+ if (text->length + length > text->capacity) {
+ size_t capacity = text->capacity ? text->capacity : 1 << 16;
+ while (capacity < text->length + length) capacity *= 2;
+ char *data = realloc(text->data, capacity);
+ if (!data) return 0;
+ text->data = data;
+ text->capacity = capacity;
+ }
+ memcpy(text->data + text->length, bytes, length);
+ text->length += length;
+ return 1;
+}
+
+/* Upper half block: foreground paints the top pixel, background the bottom one. */
+static int draw(Text *text, const uint8_t *rgba, uint32_t width, uint32_t height, const char *caption) {
+ char sgr[64];
+ text->length = 0;
+ if (!append(text, "\x1b[H", 3)) return 0;
+ for (uint32_t y = 0; y + 1 < height; y += 2) {
+ long fg = -2, bg = -2;
+ for (uint32_t x = 0; x < width; ++x) {
+ const uint8_t *top = rgba + ((size_t)y * width + x) * 4;
+ const uint8_t *bottom = top + (size_t)width * 4;
+ long t = top[3] >= ALPHA_CUTOFF ? (long)top[0] << 16 | top[1] << 8 | top[2] : -1;
+ long b = bottom[3] >= ALPHA_CUTOFF ? (long)bottom[0] << 16 | bottom[1] << 8 | bottom[2] : -1;
+ const char *glyph = "\xe2\x96\x80";
+ if (t < 0 && b < 0) glyph = " ";
+ else if (t < 0) { glyph = "\xe2\x96\x84"; t = b; b = -1; }
+ int n = 0;
+ if (t >= 0 && t != fg) {
+ n += snprintf(sgr + n, sizeof sgr - n, "\x1b[38;2;%ld;%ld;%ldm", t >> 16, t >> 8 & 255, t & 255);
+ fg = t;
+ }
+ if (b != bg) {
+ n += b < 0 ? snprintf(sgr + n, sizeof sgr - n, "\x1b[49m")
+ : snprintf(sgr + n, sizeof sgr - n, "\x1b[48;2;%ld;%ld;%ldm", b >> 16, b >> 8 & 255, b & 255);
+ bg = b;
+ }
+ if (!append(text, sgr, (size_t)n) || !append(text, glyph, strlen(glyph))) return 0;
+ }
+ if (!append(text, "\x1b[0m\r\n", 6)) return 0;
+ }
+ return append(text, "\x1b[2m", 4) && append(text, caption, strlen(caption)) &&
+ append(text, "\x1b[0m\x1b[K", 7);
+}
+
+static double now(void) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (double)t.tv_sec + (double)t.tv_nsec / 1e9;
+}
+
+int main(int argc, char **argv) {
+ const char *source = argc > 1 ? argv[1] : "../samples/miko-qipao";
+ /* Without a frame count, animate until Ctrl+C. With one, simulate that many frames at a
+ * fixed step and print only the last frame, e.g. to save a still with `> frame.txt`. */
+ long frames = argc > 2 ? strtol(argv[2], NULL, 10) : 0;
+ int interactive = frames == 0;
+ MaHandle avatar = 0;
+ MaRenderer renderer = 0;
+ MaAvatarInfo info;
+ uint8_t *rgba = NULL;
+ Text text = {0};
+ int result = EXIT_FAILURE;
+ CHECK(mesh_avatar_open_path(source, &avatar));
+ CHECK(mesh_avatar_tick(avatar, 1.0 / FPS));
+ CHECK(mesh_avatar_get_info(avatar, &info));
+ uint32_t width, height;
+ terminal_pixels(&width, &height);
+ /* A little extra headroom keeps tilted hair inside the first text row. */
+ MaRenderOptions options = {width, height, 4, MA_FIT_CONTAIN, info.pad_top + 0.06, info.pad_side};
+ MaStatus status = mesh_avatar_renderer_create(avatar, &options, &renderer);
+ if (status == MA_GPU_UNAVAILABLE) {
+ fprintf(stderr, "SKIP: %s\n", mesh_avatar_last_error());
+ result = EXIT_SUCCESS;
+ goto cleanup;
+ }
+ CHECK(status);
+ size_t length = (size_t)width * height * 4;
+ if (!(rgba = malloc(length))) { fputs("Allocation failed\n", stderr); goto cleanup; }
+
+ signal(SIGINT, on_quit);
+ signal(SIGTERM, on_quit);
+ signal(SIGWINCH, on_resize);
+ if (interactive) fputs("\x1b[?1049h\x1b[?25l\x1b[2J", stdout);
+ char caption[128];
+ double start = now(), last = start;
+ size_t next_step = 0;
+ long last_cycle = 0;
+ for (long frame = 0; !quit && (frames == 0 || frame < frames); ++frame) {
+ if (resized) {
+ resized = 0;
+ terminal_pixels(&width, &height);
+ CHECK(mesh_avatar_renderer_resize(renderer, width, height));
+ length = (size_t)width * height * 4;
+ uint8_t *grown = realloc(rgba, length);
+ if (!grown) { fputs("Allocation failed\n", stderr); goto cleanup; }
+ rgba = grown;
+ fputs("\x1b[2J", stdout);
+ }
+ double t = now(), dt = frames ? 1.0 / FPS : t - last;
+ last = t;
+ double elapsed = frames ? frame / FPS : t - start;
+ long cycle = (long)(elapsed / SCRIPT_LENGTH);
+ if (cycle != last_cycle) { last_cycle = cycle; next_step = 0; }
+ double loop_time = elapsed - SCRIPT_LENGTH * (double)cycle;
+ while (next_step < sizeof script / sizeof *script && loop_time >= script[next_step].at) {
+ const Step *step = &script[next_step++];
+ if (step->motion) CHECK(mesh_avatar_play(avatar, step->motion));
+ if (step->kana) CHECK(mesh_avatar_speak_kana(avatar, step->kana, 0, 0));
+ }
+ CHECK(mesh_avatar_tick(avatar, dt));
+ CHECK(mesh_avatar_renderer_render(renderer, rgba, length, MA_RGBA_STRAIGHT));
+ snprintf(caption, sizeof caption, " mesh-avatar %s · C ABI → RGBA → terminal · %ux%u px · Ctrl+C to quit",
+ mesh_avatar_version(), width, height);
+ if (!draw(&text, rgba, width, height, caption)) { fputs("Allocation failed\n", stderr); goto cleanup; }
+ if (interactive) {
+ fwrite(text.data, 1, text.length, stdout);
+ fflush(stdout);
+ double wait = 1.0 / FPS - (now() - t);
+ if (wait > 0) nanosleep(&(struct timespec){0, (long)(wait * 1e9)}, NULL);
+ }
+ }
+ if (!interactive) {
+ fwrite(text.data + 3, 1, text.length - 3, stdout); /* skip the cursor-home sequence */
+ fputs("\n", stdout);
+ fprintf(stderr, "Drew %ld frames at %ux%u px (%zu bytes of terminal output per frame)\n",
+ frames, width, height, text.length);
+ }
+ result = EXIT_SUCCESS;
+cleanup:
+ if (interactive) fputs("\x1b[0m\x1b[?25h\x1b[?1049l", stdout);
+ free(text.data);
+ free(rgba);
+ if (renderer) mesh_avatar_renderer_destroy(renderer);
+ if (avatar) mesh_avatar_destroy(avatar);
+ return result;
+}
diff --git a/native/include/mesh_avatar.h b/native/include/mesh_avatar.h
index 893a626..e8a4138 100644
--- a/native/include/mesh_avatar.h
+++ b/native/include/mesh_avatar.h
@@ -251,7 +251,7 @@ MaStatus mesh_avatar_set_expression(MaHandle handle, const char *name);
MaStatus mesh_avatar_set_emotion(MaHandle handle, const char *tag, uint8_t play_motion);
/**
- * Play a built-in motion by its ID, e.g. nod, no, sway or greeting.
+ * Play a built-in motion by its ID, e.g. nod, no, sway or greet.
* # Safety
* id must be a readable UTF-8 NUL-terminated string.
*/