蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Shader TileMode、Linear/Radial/SweepGradient 插值与 ComposeShader DARKEN 核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-shader.py
explore-tutorial-shader.py172 行
"""Offline Android graphics verifier for Ch 122: Paint Shader."""
import json
import math

VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"


def tile_coord(coord: float, size: float, mode: str) -> float:
    if mode == "CLAMP":
        return max(0.0, min(size - 1.0, coord))
    if mode == "REPEAT":
        return coord % size
    if mode == "MIRROR":
        period = 2.0 * size
        m = coord % period
        return m if m < size else (period - 1.0 - m)
    raise ValueError(mode)


def tile_t(t: float, mode: str) -> float:
    if mode == "CLAMP":
        return max(0.0, min(1.0, t))
    if mode == "REPEAT":
        return t % 1.0
    if mode == "MIRROR":
        m = t % 2.0
        return m if m <= 1.0 else 2.0 - m
    raise ValueError(mode)


def eval_gradient(t: float, colors: list[tuple[int, int, int]], positions: list[float] | None, mode: str) -> list[int]:
    if positions is None:
        n = len(colors)
        positions = [i / (n - 1) for i in range(n)]
    u = tile_t(t, mode)
    if u <= positions[0]:
        return list(colors[0])
    if u >= positions[-1]:
        return list(colors[-1])
    for i in range(len(positions) - 1):
        p0, p1 = positions[i], positions[i + 1]
        if p0 <= u <= p1:
            local = 0.0 if p1 == p0 else round((u - p0) / (p1 - p0), 12)
            c0, c1 = colors[i], colors[i + 1]
            return [int(round(c0[k] + local * (c1[k] - c0[k]))) for k in range(3)]
    return list(colors[-1])


def linear_t(x: float, y: float, x0: float, y0: float, x1: float, y1: float) -> float:
    dx, dy = x1 - x0, y1 - y0
    denom = dx * dx + dy * dy
    return ((x - x0) * dx + (y - y0) * dy) / denom


def radial_t(x: float, y: float, cx: float, cy: float, radius: float) -> float:
    return math.hypot(x - cx, y - cy) / radius


def sweep_t(x: float, y: float, cx: float, cy: float) -> float:
    ang = math.atan2(y - cy, x - cx)
    if ang < 0:
        ang += 2.0 * math.pi
    return ang / (2.0 * math.pi)


def porter_duff_darken_rgb(dst: tuple[int, int, int], src: tuple[int, int, int]) -> list[int]:
    # For opaque colors (alpha=1), PorterDuff.Mode.DARKEN computes min(dst, src) per channel
    return [min(dst[i], src[i]) for i in range(3)]


def main() -> None:
    # Case 1: BitmapShader TileMode CLAMP / REPEAT / MIRROR coordinate mapping on width=100
    probes = [-10, 0, 50, 100, 130, 210]
    c1_actual = {
        mode: [int(tile_coord(p, 100.0, mode)) for p in probes]
        for mode in ("CLAMP", "REPEAT", "MIRROR")
    }
    c1_expected = {
        "CLAMP": [0, 0, 50, 99, 99, 99],
        "REPEAT": [90, 0, 50, 0, 30, 10],
        "MIRROR": [9, 0, 50, 99, 69, 10],
    }

    # Case 2: LinearGradient(0,0,100,100, [RED, GREEN, BLUE, WHITE], null, REPEAT)
    colors_lin = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]
    lin_pts = [(0, 0), (50, 50), (100, 100), (150, 150)]
    c2_actual = {
        f"({x},{y})": eval_gradient(linear_t(x, y, 0, 0, 100, 100), colors_lin, None, "REPEAT")
        for x, y in lin_pts
    }
    # At (0,0): t=0 -> RED; at (50,50): t=0.5 (mid between GREEN@1/3 and BLUE@2/3) -> (0,128,128)
    # At (100,100): t=1.0 -> REPEAT 1.0%1.0 = 0.0 -> RED; at (150,150): t=1.5 -> 0.5 -> (0,128,128)
    c2_expected = {
        "(0,0)": [255, 0, 0],
        "(50,50)": [0, 128, 128],
        "(100,100)": [255, 0, 0],
        "(150,150)": [0, 128, 128],
    }

    # Case 3: RadialGradient(50,200,50) & SweepGradient(30,30) stop sampling
    colors_rg = [(0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 255, 255)]
    c3_actual = {
        "radial_center": eval_gradient(radial_t(50, 200, 50, 200, 50), colors_rg, None, "REPEAT"),
        "radial_half_r": eval_gradient(radial_t(75, 200, 50, 200, 50), colors_rg, None, "REPEAT"),
        "sweep_0deg": eval_gradient(sweep_t(60, 30, 30, 30), colors_rg, None, "CLAMP"),
        "sweep_90deg": eval_gradient(sweep_t(30, 60, 30, 30), colors_rg, None, "CLAMP"),
        "sweep_180deg": eval_gradient(sweep_t(0, 30, 30, 30), colors_rg, None, "CLAMP"),
    }
    c3_expected = {
        "radial_center": [0, 255, 0],
        "radial_half_r": [128, 0, 128],
        "sweep_0deg": [0, 255, 0],
        "sweep_90deg": [191, 64, 0],
        "sweep_180deg": [128, 0, 128],
    }

    # Case 4: ComposeShader(BitmapShader, LinearGradient, PorterDuff.Mode.DARKEN) + BitmapShaderView layout
    bit_w, bit_h = 200, 200
    darkened = porter_duff_darken_rgb((200, 180, 90), (120, 240, 150))
    c4_actual = {
        "compose_darken_rgb": darkened,
        "oval_bounds": [0, 0, bit_w, bit_h],
        "linear_rect": [bit_w, 0, bit_w * 2, bit_h],
        "compose_rect": [0, bit_h, bit_w, bit_h * 2],
        "radial_circle_center_r": [round(bit_w * 2.8, 1), bit_h / 2, bit_h / 2],
        "sweep_rect": [bit_w, bit_h, bit_w * 2, bit_h * 2],
    }
    c4_expected = {
        "compose_darken_rgb": [120, 180, 90],
        "oval_bounds": [0, 0, 200, 200],
        "linear_rect": [200, 0, 400, 200],
        "compose_rect": [0, 200, 200, 400],
        "radial_circle_center_r": [560.0, 100.0, 100.0],
        "sweep_rect": [200, 200, 400, 400],
    }

    cases = [
        {
            "name": "bitmap_shader_tilemode_mapping",
            "summary": "核验 BitmapShader 三种 TileMode(CLAMP/REPEAT/MIRROR)在越界坐标下的纹理采样映射",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "linear_gradient_stops_and_repeat",
            "summary": "核验 LinearGradient 四色均分(positions=null)与 REPEAT 平铺在斜向渐变上的 RGB 插值",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "radial_and_sweep_gradient_sampling",
            "summary": "核验 RadialGradient 径向归一化距离与 SweepGradient 360° 扫描角度的色标插值",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "compose_shader_darken_and_view_bounds",
            "summary": "核验 ComposeShader(PorterDuff.Mode.DARKEN) 通道叠加及 BitmapShaderView 五块区域绘制边界",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-shader-lab/explore-tutorial-shader.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-shader.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1943.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习