Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。
feat(brand): make the blue horned Andee the default look, icon and cover
booboosuie4c0e07ed8df
diff --git a/app/src/main/java/net/kuafuai/andee/ui/ball/BallLook.kt b/app/src/main/java/net/kuafuai/andee/ui/ball/BallLook.ktindex ef2aa31..48c27f8 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ball/BallLook.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ball/BallLook.kt@@ -349,6 +349,34 @@ class BallLook(val hornBend: Float = 0f,val hornColor: FloatArray = EMPTY,+ /**+ * Profile exponent handed to `Horn.build`. 1 = the straight thorn every look+ * had before this field; above 1 the horn holds its width and rounds off, a+ * blunt chunky horn instead of a spike.+ */+ val hornTaper: Float = 1f,++ /**+ * Colour the horn as this multiple of the *live* body colour, like [earShade],+ * instead of the fixed [hornColor]. 0 = use [hornColor].+ *+ * Exists for a horn that is part of the animal rather than bone: a fixed colour+ * is right for the imp's, whose horns do not follow the mood, and wrong for a+ * horn the same blue as the head, where it would drift out of match every time+ * the mood tint moved the body.+ */+ val hornShade: Float = 0f,++ // ---- Second catchlight ----+ /**+ * A second, smaller highlight low and to the right of the eye — the one that+ * makes a dark eye look like glass rather than paint. 0 = none, which is every+ * look but one. Only drawn on a look with no pupil: with a pupil the glint is+ * anchored to it and a second one has nowhere obvious to sit.+ */+ val glint2R: Float = 0f,+ val glint2Color: FloatArray = EMPTY,+// ---- Tail ----/** World length of the tail chain. 0 = no tail. */val tailLen: Float = 0f,@@ -883,6 +911,131 @@ val BAJIE = BallLook(persona = BAJIE_PERSONA,)+/**+ * The house character: a cobalt-blue ball with a pair of short, fat, curled horns+ * and big glassy navy eyes — the head in `images/brand/andee-head.png`, which is+ * also what the launcher icon, the README cover and the org avatar are made from.+ * A swipe away from it are the costumes ([CREAM], [BAJIE], [RABBIT], [BEAR],+ * [IMP]); this is who is wearing them, so it is first in [BallLooks.ALL] and is+ * what a device with no saved pick and a factory reset both land on.+ *+ * **Every number below was measured off that picture, not picked.** The first+ * pass was eyeballed and read as a different, less cute animal: eyes too close+ * together and too high, and — the part the user named — *ears* where the picture+ * has *horns*. The second pass inverse-projects the picture through the same+ * camera the renderer uses (`CAM_Z` 4.9, 42° fov), so a pixel in the reference+ * becomes a world unit on the face plane (0.00210 per px) or on the horn plane+ * (0.00232 per px).+ *+ * * **Eyes** are 173 px across on a 693 px head: [eyeRadius] 0.175, centres+ * ±161 px from the middle, so [eyeX] 0.338 (the first pass had 0.262 — close-set+ * eyes are a different face). They sit a hair *below* the middle of the head,+ * [eyeY] −0.03, which is the baby proportion the picture is made of: a big+ * forehead and the whole face in the lower half. The eye is round, so+ * [eyeCyl] is almost nothing.+ * * **Two catchlights.** A big one up and left ([glintR] 0.038, at the offset+ * [drawEyeContents] already uses for every look) and a small light-blue one low+ * and right ([glint2R] 0.023). The second is what makes it glass instead of+ * paint, and it is the one thing in the picture the first pass left out.+ * * **The mouth** is 133 px wide, 36 px deep and 7 px thick: [mouthR] 0.136,+ * [mouthY] −0.305 (the resting `smile` lifts it 0.0156, which puts the line's+ * ends at −0.29), and [mouthThick] chosen so the resting arch is ~0.45 of its+ * radius deep. The line is thin at the bottom and fatter at the ends by construction+ * (the torus is squashed vertically), which is why [mouthTube] is 0.016.+ * * **The horns are horns.** Round in section, thick at the root and tapering,+ * leaning out and then curling back in at the tip — [hornTilt] 50° and+ * [hornBend] −80° is a path that stays within 0.01 world units of the+ * picture's horn centreline (fitted, not drawn), then moved up by 0.07 on+ * request so the horns stand clear of the head. The mesh needed a rounded+ * profile for it: `Horn.build`'s straight cone is a thorn, and the picture's+ * are blunt. [hornTaper] 0.9 with [hornR] 0.255 reproduces the measured widths+ * (0.174 / 0.125 / 0.068 half-width at 53 / 73 / 89% of the length) to 0.018.+ * Most of that radius is buried in the head by design: the base is at+ * (0.413, 0.477), well inside the sphere, so there is no seam where it+ * emerges. [hornShade] 1.0 makes them the head's own blue at every mood.+ * (The first pass used the *ear* mesh, a flat rounded flap, and it read as a+ * cat. Don't go back: a flap has no thickness to catch light.)+ *+ * **Blue is a body colour here, and the mood still has to reach it.** The shell+ * shader is a multiply, `uColor × grad × (uAmb + uDiff · diff)`, and the target is+ * the picture's (≈ 27–50, 114–125, 240) at the face plane — and then *lighter*:+ * the first match (36, 112, 235) read as too deep on the tablet, so [bodyBase]+ * (0.200, 0.560, 1.000) lands at (59, 141, 245) after [bodyTint] 0.10 of the+ * mood, with [bodyGrad] eased to 0.26 so the underside (54, 128, 222) does not+ * sink. Back-solved against the lit factor, 0.956 at the face plane. Blue is one channel+ * at its ceiling, which is why [bodyAmb] is as high as it is — at the 0.78 the+ * other dark bodies use it tops out at 207 and reads navy, not cobalt.+ *+ * One thing that is *not* matched: the picture's head is oblate (693 wide, ~620+ * tall) and the ball is a sphere. The renderer scales the body uniformly and the+ * rim sphere is tied to it, so a squash is not a number here. The face is placed+ * to keep the picture's proportions on the *ellipse*, not the circle — eyes at+ * the middle, mouth 45% of the way down — rather than the pixel offsets from a+ * circle's centre, which would have put the face too high.+ */+val ANDEE = BallLook(+ name = "andee",+ bodyBase = floatArrayOf(0.200f, 0.560f, 1.000f),+ bodyTint = 0.10f,+ bodyAlbedo = 1.00f,+ bodyGrad = 0.26f,+ bodyAmb = 0.94f,+ bodyDiff = 0.20f,+ // Soft, like the picture — a velvety plush, not lacquer. Low enough that+ // the crown does not grow a white blob that would fight the catchlights.+ bodyGloss = 0.22f,+ bodyScale = 0.870f,+ faceZ = 0.876f,+ eyeX = 0.338f,+ eyeY = -0.030f,+ eyeRadius = 0.175f,+ eyeCyl = 0.012f,+ mouthR = 0.136f,+ mouthTube = 0.016f,+ mouthY = -0.305f,+ mouthThick = 0.140f,+ eyeColor = floatArrayOf(0.030f, 0.065f, 0.230f),+ pupilR = 0f,+ glintR = 0.038f,+ glint2R = 0.023f,+ glint2Color = floatArrayOf(0.45f, 0.70f, 1.00f),+ // Light droplet on a mid-dark body, the same side of the split as [BEAR].+ bubbleX = 0.085f,+ bubbleY = -0.030f,+ bubbleR = 0.085f,+ bubbleColor = floatArrayOf(0.88f, 0.93f, 1.00f),+ bubblePow = 3.0f,+ bubbleShine = 26f,+ bubbleInner = 0.10f,+ mouthDeep = true,+ // The picture has no cheeks. Kept faintly so the happy moods still flush.+ blushColor = floatArrayOf(1f, 0.55f, 0.75f),+ blushAlpha = 0.10f,+ blushBlendNormal = true,+ blushSize = 0.40f,+ blushX = 0.440f,+ blushY = -0.110f,+ // A light rim, like the imp's and bear's: a dark outline on a mid-dark body+ // is a smudge.+ rimDark = false,+ rimGain = 0.80f,+ rimPow = 4.4f,+ labelRes = R.string.ball_look_andee,++ // See the class note: fitted to the picture's horn (base at 0.407), then lifted+ // 0.07 on request so the horns stand clear of the head.+ // Base buried at (0.413, 0.477) so only the curl shows.+ hornH = 0.452f,+ hornR = 0.255f,+ hornX = 0.413f,+ hornY = 0.477f,+ hornZ = 0.450f,+ hornTilt = 50f,+ hornBend = -80f,+ hornTaper = 0.9f,+ hornShade = 1.00f,+)+/*** Pale mascot ball, dark bead eyes, hard outline.*@@ -1071,9 +1224,9 @@ private val IMP_PERSONA = """* [voice] and [persona] are both set here, so swiping to the imp changes what* the device sounds like and how it talks, not only what it looks like. That is* no longer the distinction it was — [BAJIE] and [RABBIT] both do it now, and- * [CREAM] is the only look left wearing the house voice and the plain prompt,- * which is the right place for it to be: it is the one that shipped first and- * the one a factory reset lands on. Read the caveats on those two fields — in+ * [ANDEE] and [CREAM] are the looks left wearing the house voice and the plain+ * prompt, which is the right place for them to be: [ANDEE] is the one a factory+ * reset lands on. Read the caveats on those two fields — in* particular, the persona reaches the local brain only.** **It is black, and the black is the design.** The first build made it a@@ -1926,11 +2079,13 @@ val BEAR = BallLook(object BallLooks {/*** Swipe order, and the first entry is what a device with no saved pick- * gets. [CREAM] stays first because it is what the window was designed- * around; [IMP] is last because it is the one a user should arrive at on- * purpose.+ * gets. [ANDEE] is first because it is the house character — the one in the+ * launcher icon and the README — and a user who has never swiped should see+ * the thing the app is called; [CREAM] is what the window was originally+ * designed around; [IMP] is last because it is the one a user should arrive+ * at on purpose.*/- val ALL = listOf(CREAM, BAJIE, RABBIT, BEAR, IMP)+ val ALL = listOf(ANDEE, CREAM, BAJIE, RABBIT, BEAR, IMP)@Volatileprivate var requested = 0diff --git a/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt b/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallRenderer.ktindex 01caad0..cacefbd 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt@@ -244,7 +244,15 @@ class EmotionBallRenderer : GLSurfaceView.Renderer {else Capsule.build(look.eyeRadius, look.eyeCyl, 4, 12)val mouth: Mesh = Torus.build(look.mouthR, look.mouthTube, 8, 24, PI.toFloat())val horn: Mesh? =- if (look.hornH > 0f) Horn.build(look.hornR, look.hornH, look.hornBend / DEG, 7, 12)+ if (look.hornH > 0f)+ Horn.build(+ look.hornR, look.hornH, look.hornBend / DEG,+ // A rounded profile packs its curvature into the last rings,+ // so it needs more of them than the straight thorn does.+ segs = if (look.hornTaper != 1f) 12 else 7,+ radialSegs = 12,+ taper = look.hornTaper,+ )else nullval barb: Mesh? =if (look.barbH > 0f) Horn.build(look.barbR, look.barbH, 0f, 4, 10) else null@@ -342,6 +350,7 @@ class EmotionBallRenderer : GLSurfaceView.Renderer {/** Filled per frame from [bodyColor] — see [BallLook.earShade]. */private val earColor = FloatArray(3)+ private val hornColor = FloatArray(3)/** Scratch for the nostril dots — a dark relative of [bodyColor]. */private val nostrilColor = FloatArray(3)@@ -736,7 +745,12 @@ class EmotionBallRenderer : GLSurfaceView.Renderer {*/private fun drawHorns() {val horn = meshes.horn ?: return- useShellWith(LOOK.hornColor)+ if (LOOK.hornShade > 0f) {+ for (i in 0..2) hornColor[i] = bodyColor[i] * LOOK.hornShade+ useShellWith(hornColor)+ } else {+ useShellWith(LOOK.hornColor)+ }for (side in -1..1 step 2) {composeModelFromRoot {if (side < 0) Matrix.scaleM(local, 0, -1f, 1f, 1f)@@ -1518,6 +1532,14 @@ class EmotionBallRenderer : GLSurfaceView.Renderer {rotZ, lidScale,gr, eyeFrontZ + GLINT_Z_STEP, WHITE,)+ val g2 = LOOK.glint2R+ if (g2 > 0f) {+ drawDot(+ cx + LOOK.eyeRadius * 0.54f, cy + sink - LOOK.eyeRadius * 0.26f * follow,+ rotZ, lidScale,+ g2, eyeFrontZ + GLINT_Z_STEP, LOOK.glint2Color,+ )+ }}}diff --git a/app/src/main/java/net/kuafuai/andee/ui/ball/gl/Horn.kt b/app/src/main/java/net/kuafuai/andee/ui/ball/gl/Horn.ktindex 2f734f7..f8b2056 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ball/gl/Horn.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ball/gl/Horn.kt@@ -33,8 +33,19 @@ object Horn {* @param radius base radius; the tip is a point.* @param height length along the (curved) axis.* @param bend total rotation of the axis from base to tip, radians, toward +X.+ * Negative curls the tip back toward the head, which is a calf's horn+ * rather than a devil's.* @param segs rings along the length. 6 is plenty at the size this is drawn.* @param radialSegs vertices around each ring.+ * @param taper the profile exponent. **1 is the straight cone** every caller+ * got before this parameter existed and is the default, so the imp's horns+ * and the tail's barb are untouched. The radius is+ * `√(1 − t^taper)` instead, whatever the value: it ends in a dome with a+ * vertical tangent, the way [Ear] does, which is the difference between a+ * thorn and a blunt, chunky horn. Above 1 it holds its width for most of+ * the length first; below 1 (0.9 is a near-linear cone) it narrows from the+ * start and only the last stretch is round. A cone this fat reads as a+ * party hat; this one reads as something you could pat.*/fun build(radius: Float,@@ -42,6 +53,7 @@ object Horn {bend: Float = 0f,segs: Int = 6,radialSegs: Int = 10,+ taper: Float = 1f,): Mesh {val rings = segs + 1val vertCount = rings * (radialSegs + 1)@@ -55,6 +67,14 @@ object Horn {val nAxis = radius / sqrt(height * height + radius * radius)val nRad = height / sqrt(height * height + radius * radius)+ // The rounded profile has no constant slope, so its normals come from the+ // neighbouring rings instead. Only filled when [taper] asks for it.+ val profile = FloatArray(rings) { i ->+ val t = i.toFloat() / segs+ if (taper == 1f) radius * (1f - t)+ else radius * sqrt((1f - Math.pow(t.toDouble(), taper.toDouble()).toFloat()).coerceAtLeast(0f))+ }+var cx = 0fvar cy = 0fvar pi = 0@@ -62,7 +82,25 @@ object Horn {var ui = 0for (i in 0 until rings) {val t = i.toFloat() / segs- val r = radius * (1f - t)+ val r = profile[i]+ // Per-ring normal tilt. For the straight cone these are the constants+ // above; for a rounded profile the slope is read off the rings either+ // side (one-sided at the ends), and at the tip it steepens until the+ // normal points straight along the axis — which is what makes the+ // end read as a dome instead of a flat cut.+ val nR: Float+ val nA: Float+ if (taper == 1f) {+ nR = nRad+ nA = nAxis+ } else {+ val lo = (i - 1).coerceAtLeast(0)+ val hi = (i + 1).coerceAtMost(rings - 1)+ val slope = (profile[hi] - profile[lo]) / ((hi - lo) * step)+ val inv = 1f / sqrt(1f + slope * slope)+ nR = inv+ nA = -slope * inv+ }// The axis at this ring, and the two directions spanning the ring// plane: u in the bend plane, v out of it.val ang = bend * t@@ -82,9 +120,9 @@ object Horn {positions[pi++] = cx + r * rxpositions[pi++] = cy + r * rypositions[pi++] = r * rz- normals[ni++] = nRad * rx + nAxis * ax- normals[ni++] = nRad * ry + nAxis * ay- normals[ni++] = nRad * rz+ normals[ni++] = nR * rx + nA * ax+ normals[ni++] = nR * ry + nA * ay+ normals[ni++] = nR * rzuvs[ui++] = j.toFloat() / radialSegsuvs[ui++] = t}diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webpindex 05fb8db..e7eea44 100644Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differdiff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_background.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_background.webpindex 43e2f77..18b8fe1 100644Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_background.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_background.webp differdiff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webpindex 4771590..b60a88b 100644Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differdiff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webpindex 7bd363b..d1d9a14 100644Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp differdiff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webpindex 7a4efcf..a8654ad 100644Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differdiff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webpindex 48327b0..da3c375 100644Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differdiff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_background.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_background.webpindex 982b7d8..9d13a0f 100644Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_background.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_background.webp differdiff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webpindex c60e393..f8a6f7f 100644Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differdiff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webpindex 15cffe4..6a68ff1 100644Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp differdiff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webpindex a0099dd..bacd77e 100644Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differdiff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webpindex 2e8b67f..b3471d4 100644Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differdiff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.webpindex 40c806d..b85e95b 100644Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.webp differdiff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webpindex 9b11a12..e6eae51 100644Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differdiff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webpindex 0f28a1f..b11dc60 100644Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp differdiff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webpindex 230cd17..4b23943 100644Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differdiff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webpindex ca1febb..44ae744 100644Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differdiff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.webpindex c498c95..197615e 100644Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.webp differdiff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webpindex 98ad80a..5607558 100644Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differdiff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webpindex b241d2e..5c3509c 100644Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp differdiff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webpindex 347c124..f8f5874 100644Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differdiff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webpindex 090d91e..5f576a4 100644Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differdiff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.webpindex a4ff64a..baa9bb5 100644Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.webp differdiff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webpindex 5b1bc7c..fa1ad4e 100644Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differdiff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webpindex 58b36f2..24d8f39 100644Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp differdiff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webpindex 159524b..f6de87d 100644Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differdiff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xmlindex 4f7fc90..3a5624a 100644--- a/app/src/main/res/values-en/strings.xml+++ b/app/src/main/res/values-en/strings.xml@@ -515,6 +515,7 @@change them, and the new one announces itself in the subtitle band —that name is read by a person, hence a resource rather thanBallLook.name, which is for logs and diffs. -->+ <string name="ball_look_andee">Andee</string><string name="ball_look_cream">Cream</string><string name="ball_look_bajie">Pigsy</string><string name="ball_look_rabbit">Rascal</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex e5c3933..4061d51 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -595,6 +595,7 @@<!-- 球球的几种样子。用户在全屏卡片上左右滑动球球来换,换到哪个就用字幕报一下名字 —— 这个名字是给人看的,所以是资源,而不是 BallLook.name(那个是给日志和 diff 看的)。 -->+ <string name="ball_look_andee">Andee</string><string name="ball_look_cream">奶油</string><string name="ball_look_bajie">八戒</string><string name="ball_look_rabbit">贱贱兔</string>diff --git a/images/avatar-org.png b/images/avatar-org.pngindex e776014..e64a5e1 100644Binary files a/images/avatar-org.png and b/images/avatar-org.png differdiff --git a/images/brand/andee-head.png b/images/brand/andee-head.pngnew file mode 100644index 0000000..b16ca0aBinary files /dev/null and b/images/brand/andee-head.png differdiff --git a/images/cover.png b/images/cover.pngindex 28412c5..7ef7423 100644Binary files a/images/cover.png and b/images/cover.png differdiff --git a/images/cover.zh-CN.png b/images/cover.zh-CN.pngindex 356e1d5..e2a8a92 100644Binary files a/images/cover.zh-CN.png and b/images/cover.zh-CN.png differdiff --git a/images/social-preview.png b/images/social-preview.pngindex 9dbc0ce..a12a5ed 100644Binary files a/images/social-preview.png and b/images/social-preview.png differdiff --git a/images/social-preview.zh-CN.png b/images/social-preview.zh-CN.pngindex 958703b..9e8d998 100644Binary files a/images/social-preview.zh-CN.png and b/images/social-preview.zh-CN.png differdiff --git a/tools/andee_head.py b/tools/andee_head.pynew file mode 100644index 0000000..4529a87--- /dev/null+++ b/tools/andee_head.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+"""从 images/brand/andee-head.png 取出角色:头部抠图、五官遮罩、光晕底片。++源图是一张**不透明**的方图:白底,头部外面一圈橙→粉的光晕,头部本身是蓝色。+没有 alpha,所以这里要自己抠 —— 抠法是量出来的,不是调出来的:++ * 光晕和头部在**色相**上是分开的:光晕的 R 通道约 253,头部的 R 在 27–110。+ 光晕环 = `R-G > 14 且 R-B > -5`,它把头部整圈包住,所以"光晕环内侧、与头部+ 中心连通的那一块"就是头部。这比任何亮度阈值都稳 —— 头部边缘有一圈偏白的+ 亮边(rim light),亮度阈值会把它当背景吃掉。+ * 边缘 alpha 用到光晕环的距离做软过渡,宽 2px,再对**颜色**做去色边:+ 边缘像素混了光晕的橙,直接缩小会在头部外沿留一圈橙边(48px 图标上就是脏边)。++这个模块只负责"素材",不写任何文件;`make_launcher_icon.py` 和+`make_social_preview.py` 各自 import 它。+"""+from pathlib import Path++import numpy as np+from PIL import Image, ImageFilter++REPO = Path(__file__).resolve().parent.parent+SRC = REPO / "images" / "brand" / "andee-head.png"++# 光晕环的判据。数是从源图上量的:头部蓝 (27,114,240)、橙晕 (253,195,180)、+# 粉晕 (253,172,217),边缘亮边 (254,254,253)。亮边的 R-G 只有 ~1,不会被当成环。+RING_RG = 14+RING_RB = -5++# 五官亮度阈值(Rec.709 亮度,头部内)。瞳孔 0–33,嘴 0–33,头部蓝身 70–140,+# 高光点 > 200。落在 33 和 70 之间的空隙里取 50。+DARK_LUM = 50.0+++def load_src() -> np.ndarray:+ return np.asarray(Image.open(SRC).convert("RGB")).astype(np.float64)+++def _flood(free: np.ndarray, seed):+ """4 邻域泛洪。不引 scipy —— 这个仓库的图片工具链只依赖 numpy + PIL。"""+ H, W = free.shape+ seen = np.zeros((H, W), bool)+ stack = [seed]+ seen[seed] = True+ while stack:+ y, x = stack.pop()+ for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):+ if 0 <= ny < H and 0 <= nx < W and free[ny, nx] and not seen[ny, nx]:+ seen[ny, nx] = True+ stack.append((ny, nx))+ return seen+++def head_matte(a: np.ndarray):+ """返回 (alpha[0..1], 头部硬遮罩)。"""+ R, G, B = a[..., 0], a[..., 1], a[..., 2]+ ring = ((R - G) > RING_RG) & ((R - B) > RING_RB)+ H, W = R.shape+ hard = _flood(~ring, (H // 2 + 20, W // 2))+ # 软边:硬遮罩模糊后取 [0.25,0.75] 重映射,得到约 2px 的过渡。+ soft = Image.fromarray((hard * 255).astype(np.uint8), "L").filter(+ ImageFilter.GaussianBlur(1.1))+ s = np.asarray(soft).astype(np.float64) / 255.0+ alpha = np.clip((s - 0.25) / 0.5, 0.0, 1.0)+ return alpha, hard+++def decontaminate(a: np.ndarray, hard: np.ndarray) -> np.ndarray:+ """边缘像素的颜色换成"往头部里面 3px"的颜色,去掉光晕渗进来的橙边。"""+ m = hard.copy()+ for _ in range(3):+ m = m & np.roll(m, 1, 0) & np.roll(m, -1, 0) & np.roll(m, 1, 1) & np.roll(m, -1, 1)+ inner = a.copy()+ inner[~m] = np.nan+ # 向外最多 4 轮,每轮用 4 邻域里已知像素的均值填边缘外一圈。+ known = m.copy()+ out = a.copy()+ filled = np.where(m[..., None], a, 0.0)+ for _ in range(5):+ acc = np.zeros_like(a)+ cnt = np.zeros(a.shape[:2])+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ k = np.roll(known, (dy, dx), (0, 1))+ acc += np.where(k[..., None], np.roll(filled, (dy, dx), (0, 1)), 0.0)+ cnt += k+ new = (~known) & (cnt > 0)+ filled[new] = acc[new] / cnt[new][:, None]+ known = known | new+ edge = known & ~m+ out[edge] = filled[edge]+ return out+++def character_rgba():+ """透明底的角色 RGBA(uint8),和它的 alpha / 硬遮罩 / 原图。"""+ a = load_src()+ alpha, hard = head_matte(a)+ rgb = decontaminate(a, hard)+ rgba = np.dstack([np.clip(rgb, 0, 255), alpha * 255.0]).astype(np.uint8)+ return rgba, alpha, hard, a+++def luminance(a: np.ndarray) -> np.ndarray:+ return 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]+++def face_holes(a: np.ndarray, hard: np.ndarray):+ """眼睛(两颗)与嘴的镂空遮罩,给单色(主题)图标用。++ 眼睛里有一颗高光点(亮度 254),阈值 mask 会在洞里留一个疙瘩,所以眼睛用+ "暗像素的 bbox 拟合椭圆",嘴用阈值 mask 做闭运算 —— 嘴是弧,细,椭圆会把+ 背景一起拖进来。耳朵(头顶的角)不会命中:亮度 > 100。+ """+ lum = luminance(a)+ H, W = lum.shape+ yy, xx = np.mgrid[0:H, 0:W]+ dark = hard & (lum < DARK_LUM)+ cx = W / 2.0+ holes = np.zeros((H, W), bool)++ def ellipse(box, grow):+ x0, y0, x1, y1 = box+ ex, ey = (x0 + x1) / 2.0, (y0 + y1) / 2.0+ ax, ay = (x1 - x0 + 1) / 2.0 * grow, (y1 - y0 + 1) / 2.0 * grow+ return ((xx - ex) / ax) ** 2 + ((yy - ey) / ay) ** 2 <= 1.0++ boxes = []+ # 眼睛在 y<760,嘴在 y>760;按 x 分左右。+ for lo, hi in ((0, cx), (cx, W)):+ sel = dark & (yy < 760) & (xx >= lo) & (xx < hi)+ if sel.sum() < 2000:+ raise SystemExit("找不到眼睛:阈值或源图变了,先看 head_matte 的结果。")+ ys, xs = np.where(sel)+ # 眼窝外的细暗线(头部亮边的内沿)会把 bbox 撑大 —— 取 1%–99% 分位。+ x0, x1 = np.percentile(xs, [0.5, 99.5])+ y0, y1 = np.percentile(ys, [0.5, 99.5])+ boxes.append((x0, y0, x1, y1))+ holes |= ellipse((x0, y0, x1, y1), 1.04)++ mouth = dark & (yy >= 760) & (yy < 840)+ for _ in range(2):+ mouth = mouth | np.roll(mouth, 1, 0) | np.roll(mouth, -1, 0) | np.roll(mouth, 1, 1) | np.roll(mouth, -1, 1)+ for _ in range(2):+ mouth = mouth & np.roll(mouth, 1, 0) & np.roll(mouth, -1, 0) & np.roll(mouth, 1, 1) & np.roll(mouth, -1, 1)+ holes |= mouth+ return holes, boxes, mouth+++def circumcircle(alpha: np.ndarray, thr: float = 0.03):+ """让"到画布中心最大距离"最小的下移量 —— 同 make_launcher_icon 的 best_shift。++ 返回 (半径, 需要下移 dy)。角在头顶两侧,外接圆比头本身大,下移后更贴。+ """+ ys, xs = np.where(alpha > thr)+ H, W = alpha.shape+ ccx, ccy = (W - 1) / 2.0, (H - 1) / 2.0+ best = (float(np.hypot(xs - ccx, ys - ccy).max()), 0)+ for dy in range(-160, 161):+ d = float(np.hypot(xs - ccx, (ys + dy) - ccy).max())+ if d < best[0]:+ best = (d, dy)+ return best+++if __name__ == "__main__":+ rgba, alpha, hard, a = character_rgba()+ ys, xs = np.where(alpha > 0.03)+ print(f"头部 bbox x[{xs.min()},{xs.max()}] y[{ys.min()},{ys.max()}] "+ f"{xs.max() - xs.min() + 1}×{ys.max() - ys.min() + 1}")+ holes, boxes, mouth = face_holes(a, hard)+ for i, b in enumerate(boxes):+ print(f"眼{i + 1} bbox x[{b[0]:.0f},{b[2]:.0f}] y[{b[1]:.0f},{b[3]:.0f}]")+ print(f"嘴 {int(mouth.sum())}px")+ r, dy = circumcircle(alpha)+ print(f"外接圆半径 {r:.1f},最优下移 {dy}px")+ out = Path("/tmp/andee-brand")+ out.mkdir(exist_ok=True)+ Image.fromarray(rgba, "RGBA").save(out / "character.png")+ chk = Image.new("RGBA", rgba.shape[1::-1], (40, 40, 48, 255))+ chk.alpha_composite(Image.fromarray(rgba, "RGBA"))+ chk.convert("RGB").resize((627, 627), Image.LANCZOS).save(out / "character_on_dark.png")+ ov = a.copy()+ ov[holes] = (255, 0, 80)+ Image.fromarray(ov.astype(np.uint8)).crop((380, 570, 900, 830)).save(out / "holes.png")diff --git a/tools/check_launcher_icon.py b/tools/check_launcher_icon.pydeleted file mode 100644index 4ca99cc..0000000--- a/tools/check_launcher_icon.py+++ /dev/null@@ -1,421 +0,0 @@-#!/usr/bin/env python3-"""校验生成好的一整套 Android 启动图标。--这些判据是**踩过之后才定下来的**,每一条都对应一个曾经出过错的地方。-关键的一条是"剪影一致":第一版用 IoU 直接比前景层和单色层的剪影,得到-0.8611 —— 看起来像几何错了,其实是**挖空造成的**(前景不透明而单色为 0 的-像素正好等于眼睛+嘴的面积 5565px)。判据不修正的话,一个正确的结果会被-报成错误,而错误的判据比没有判据更危险:它教人忽略警告。--所以这里比的是"把挖空补回来之后的剪影"。--用法:check_launcher_icon.py --res app/src/main/res [--src 源图.alpha.png]-"""-import argparse-import sys-from pathlib import Path--import numpy as np-from PIL import Image--sys.path.insert(0, str(Path(__file__).resolve().parent))-import cosmic_backdrop--DENSITIES = [("mdpi", 1.0), ("hdpi", 1.5), ("xhdpi", 2.0), ("xxhdpi", 3.0), ("xxxhdpi", 4.0)]-ADAPTIVE_CANVAS = 108.0-LEGACY_CANVAS = 48.0-VISIBLE_FRACTION = 72.0 / 108.0-LEGACY_EXPECT = 0.88--BG = (14, 23, 43)-LUM_EYE = 60.0 # 前景层里眼睛的亮度上限(实测眼睛 ≈34,球体 ≈131)-LUM_MOUTH = 100.0 # ⚠️ 别写 120 —— 球体自身暗部底就是 120.6,会吞进来当嘴(见 check 6)-BALL_INNER = 0.90--# 底片装饰的判据(只在 --backdrop 给了以后生效)-GLOW_CEIL = 118.0 # 底片 P99 亮度上限。球体主体实测 ≈131,留 ~13 的余量-STAR_MIN_DELTA = 26.0 # 比底片中位数亮这么多,才算"一颗星"--failures: list[str] = []-notes: list[str] = []---def fail(msg):- failures.append(msg)- print(f" ✗ {msg}")---def ok(msg):- print(f" ✓ {msg}")---def load_rgba(p):- return np.asarray(Image.open(p).convert("RGBA")).astype(np.float64)---def check_alpha_semantics(res: Path):- print("\n── 1. 文件完整性 / alpha 语义 ──")- need_opaque = ("ic_launcher_background", "ic_launcher")- need_alpha = ("ic_launcher_foreground", "ic_launcher_monochrome", "ic_launcher_round")- n = 0- for name, dpi in DENSITIES:- for base in need_opaque + need_alpha:- p = res / f"mipmap-{name}/{base}.webp"- if not p.exists():- fail(f"缺文件 {p}")- continue- n += 1- a = load_rgba(p)- al = a[:, :, 3]- if base in need_opaque:- if al.min() < 255:- fail(f"{p.name} ({name}) 应当全不透明,实测 alpha 最小 {al.min():.0f}")- else:- if al.max() == 0:- fail(f"{p.name} ({name}) 全透明,没有内容")- elif al.min() == al.max():- fail(f"{p.name} ({name}) alpha 没有变化,不像是带剪影的层")- if n == 25:- ok(f"25 个文件齐全,background/ic_launcher 全不透明,其余带 alpha")---def check_canvas_sizes(res: Path):- print("\n── 2. 画布尺寸 ──")- bad = 0- for name, dpi in DENSITIES:- want_a = int(round(ADAPTIVE_CANVAS * dpi))- want_l = int(round(LEGACY_CANVAS * dpi))- for base, want in (("ic_launcher_background", want_a), ("ic_launcher_foreground", want_a),- ("ic_launcher_monochrome", want_a),- ("ic_launcher", want_l), ("ic_launcher_round", want_l)):- w, h = Image.open(res / f"mipmap-{name}/{base}.webp").size- if (w, h) != (want, want):- fail(f"{name}/{base} 尺寸 {w}×{h},应为 {want}×{want}")- bad += 1- if not bad:- ok("自适应层 108dp、传统层 48dp,五个密度都对")---def check_visible_circle(res: Path):- print("\n── 3. 自适应层:角色是否落在保证可见的圆里 ──")- rows = []- bad = 0- for name, dpi in DENSITIES:- cvs = int(round(ADAPTIVE_CANVAS * dpi))- a = load_rgba(res / f"mipmap-{name}/ic_launcher_foreground.webp")- al = a[:, :, 3]- ys, xs = np.where(al > 8)- cc = (cvs - 1) / 2.0- r = float(np.hypot(xs - cc, ys - cc).max())- vis = cvs * VISIBLE_FRACTION / 2.0- rows.append((name, cvs, r, vis))- if r >= vis:- fail(f"{name}: 角色最大半径 {r:.2f} ≥ 可见圆 {vis:.1f},会被遮罩切到")- bad += 1- if not bad:- slack = min(v - r for _, _, r, v in rows)- ok(f"五个密度都放得下,最紧的一档余量 {slack:.2f}px(@其自身画布)")- for name, cvs, r, vis in rows:- print(f" {name:8s} 画布{cvs:4d} 角色 {r:6.2f} / 可见 {vis:5.1f} 余量 {vis-r:5.2f}")---def check_silhouette_match(res: Path):- """核心一项:单色层的剪影要和美术层一致 —— **把挖空补回来再比**。-- 判据**不是**"固定 IoU 阈值"。第一版写了 0.98,结果 mdpi 0.9663 / hdpi- 0.9757 被判失败 —— 但量下来的事实是:五种密度的**最佳整数位移都是 (0,0)**- (±1 扫一圈 IoU 一点都不提升),非挖空区 alpha 平均只差 0.53/255,而- "对称差 ÷ 半个边界带"恒等于 **0.48px**(五档依次 0.48/0.49/0.48/0.48/0.48)。-- 恒定的 0.48px 就是纯亚像素效应的签名:差异面积 ∝ 周长 × 常数,而 IoU 是- 面积比 ⇒ 小画布上必然更差。固定阈值等于**在惩罚分辨率,不在检查几何**。- 真正的几何错位会给出约 2.0px(差 1px 的轮廓)。-- 所以判据两条:- ① 位移扫描无收益 —— 两层注册正确;- ② 对称差 ÷ 半个边界带 ≤ 1.0px —— 差异是亚像素级的。- IoU 照打,但只作参考,不设阈值。- """- print("\n── 4. 单色层剪影 vs 美术层剪影(挖空已补回) ──")- bad = 0- for name, _ in DENSITIES:- fg = load_rgba(res / f"mipmap-{name}/ic_launcher_foreground.webp")- mo = load_rgba(res / f"mipmap-{name}/ic_launcher_monochrome.webp")- fa, ma = fg[:, :, 3], mo[:, :, 3]- # 挖空 = 实体上被单色层挖掉的洞(光看 ma==0 会把背景也算进去)- holes = (ma == 0) & (fa > 200)- sil_fg = fa > 128- sil_mono = (ma > 128) | holes- iou = (sil_fg & sil_mono).sum() / max(1, (sil_fg | sil_mono).sum())-- # ① 位移扫描:任何一个 ±1 整数位移能让 IoU 变好,就是真的错位了- gain = 0.0- for sy in (-1, 0, 1):- for sx in (-1, 0, 1):- s2 = np.roll(np.roll(sil_mono, sy, 0), sx, 1)- gain = max(gain, (sil_fg & s2).sum() / max(1, (sil_fg | s2).sum()) - iou)-- # ② 边界带:1px 膨胀 ∩ 1px 腐蚀的环,面积 ≈ 周长 × 2- d1 = np.roll(sil_fg, 1, 0) | np.roll(sil_fg, -1, 0) | np.roll(sil_fg, 1, 1) | np.roll(sil_fg, -1, 1)- e1 = np.roll(sil_fg, 1, 0) & np.roll(sil_fg, -1, 0) & np.roll(sil_fg, 1, 1) & np.roll(sil_fg, -1, 1)- perim = (d1 & ~e1).sum() / 2.0- sym = int((sil_fg ^ sil_mono).sum())- edge_px = sym / max(1.0, perim)-- mark = "✓" if (edge_px <= 1.0 and gain <= 1e-9) else "✗"- print(f" {name:8s} IoU {iou:.4f} (仅供参考) 对称差 {sym:4d}px /"- f" 周长 {perim:6.1f} = {edge_px:.2f}px {mark}"- f" 位移收益 {gain:+.4f} 挖空 {int(holes.sum())}px")- if edge_px > 1.0:- fail(f"{name}: 剪影差异达 {edge_px:.2f}px(周长归一),超出亚像素级")- bad += 1- if gain > 1e-9:- fail(f"{name}: 单色层与美术层有整体错位(某个 ±1 位移能把 IoU 变好 {gain:+.4f})")- bad += 1- if not bad:- ok("五档剪影差异均为亚像素级(周长归一 ≤1.0px),且无整体错位")---def check_holes(res: Path):- """挖空必须是"被实体包住的洞",不能碰到剪影外沿。"""- print("\n── 5. 挖空是内洞,不是缺口 ──")- bad = 0- for name in ("xxxhdpi",):- cvs = int(round(ADAPTIVE_CANVAS * {"xxxhdpi": 4.0}[name]))- fg = load_rgba(res / f"mipmap-{name}/ic_launcher_foreground.webp")- mo = load_rgba(res / f"mipmap-{name}/ic_launcher_monochrome.webp")- fa, ma = fg[:, :, 3], mo[:, :, 3]- holes = (ma == 0) & (fa > 200)- sil = fa > 128- ys, xs = np.where(sil)- hy, hx = np.where(holes)- for lbl, arr, lo, hi in (("x", hx, xs.min(), xs.max()), ("y", hy, ys.min(), ys.max())):- if arr.min() <= lo or arr.max() >= hi:- fail(f"挖空在 {lbl} 方向碰到剪影边界(洞 {arr.min()}..{arr.max()},"- f"剪影 {lo}..{hi}) —— 洞漏到外面了")- bad += 1- # 洞应当在球体内部:到球心的距离 < 剪影的包络- cc = (cvs - 1) / 2.0- rmax = float(np.hypot(xs - cc, ys - cc).max())- rh = float(np.hypot(hx - cc, hy - cc).max())- print(f" 挖空 {len(hx)} px,最远点到中心 {rh:.1f} / 剪影包络 {rmax:.1f}")- if rh >= rmax * 0.98:- fail(f"挖空的最远点已经贴到剪影边缘({rh:.1f} vs {rmax:.1f})")- bad += 1- if not bad:- ok("挖空完全在剪影内部,没有漏到边界")---def check_holes_align_with_face(res: Path):- """洞要盖在真的五官上 —— 用美术层自己的暗像素当对照。-- 两个坑:-- ① **阈值必须落在实测的谷底里,不能"看着像"。** 原来嘴用 LUM_MOUTH=120,- 而球体自身的暗部底就是 120.6(下半部亮度分位 5%=78.9、10%=120.6、- 50%=124.1)。阈值贴上去的结果是把球体暗部一起吞进来当嘴:115→120 时- "嘴"从 589px 涨到 725px、覆盖从 89.3% 掉到 72.6%;120→125 更是暴涨到- 6131px。改成 100(谷底正中)后是 551px / 95.3%。-- ② **洞的边缘是抗锯齿的,`ma == 0` 取不到那一圈。** 单色层的 alpha 在洞的- 边界上是一条从 0 斜坡到 255 的过渡,所以"严格相等 0"会漏掉最外一圈。- 实测:嘴覆盖不到的那 26px **100% 都落在洞的 1px 边缘带上**。- 所以判据给 1px 容差 —— 但**同时**还要严判,否则洞整体偏出去也能靠边缘- 带凑过去。两条都要过。- """- print("\n── 6. 挖空位置与美术层的五官对齐 ──")- tol_edges = 0.98 # 洞 ∪ 洞外 1px,应当几乎全覆盖- min_strict = 0.70 # 只用洞本身,不许偏太远- bad = 0- name, dpi = "xxxhdpi", 4.0- cvs = int(round(ADAPTIVE_CANVAS * dpi))- fg = load_rgba(res / f"mipmap-{name}/ic_launcher_foreground.webp")- mo = load_rgba(res / f"mipmap-{name}/ic_launcher_monochrome.webp")- fa, ma = fg[:, :, 3], mo[:, :, 3]- lum = 0.2126 * fg[:, :, 0] + 0.7152 * fg[:, :, 1] + 0.0722 * fg[:, :, 2]-- ys, xs = np.where(fa > 128)- # 球心 = 剪影里最宽那一行的中心;球半径 = 最宽行的半宽- best = (0, 0)- for y in range(ys.min(), ys.max() + 1):- xr = np.where(fa[y] > 128)[0]- if len(xr) and xr.max() - xr.min() + 1 > best[0]:- best = (xr.max() - xr.min() + 1, (xr.min() + xr.max()) / 2.0)- ball_cx = best[1]- ball_cy = float(ys.max()) - best[0] / 2.0- ball_r = best[0] / 2.0-- yy, xx = np.mgrid[0:cvs, 0:cvs]- inside = np.hypot(xx - ball_cx, yy - ball_cy) < ball_r * BALL_INNER- holes = (ma == 0) & (fa > 200)- hd = (holes | np.roll(holes, 1, 0) | np.roll(holes, -1, 0)- | np.roll(holes, 1, 1) | np.roll(holes, -1, 1))- fringe = hd & ~holes-- for lbl, mask in (("眼睛", inside & (yy < ball_cy) & (lum < LUM_EYE)),- ("嘴", inside & (yy > ball_cy) & (lum < LUM_MOUTH))):- if mask.sum() == 0:- notes.append(f"{lbl}: 在美术层里没找到暗像素,跳过")- print(f" {lbl}: 没找到对照像素,跳过")- continue- n = mask.sum()- s = (mask & holes).sum() / n- t = (mask & hd).sum() / n- inedge = (mask & fringe).sum()- print(f" {lbl}: 暗像素 {int(n):5d}px 严格覆盖 {s*100:5.1f}%"- f" (含洞外 1px 边缘带) {t*100:5.1f}% 边缘带 {int(inedge)}px")- if t < tol_edges:- fail(f"{lbl} 含边缘带也只有 {t*100:.1f}% 落在洞上 —— 洞和五官没对上")- bad += 1- elif s < min_strict:- fail(f"{lbl} 严格覆盖只有 {s*100:.1f}%(<{min_strict*100:.0f}%) ——"- f"靠边缘带凑数,洞偏了")- bad += 1- if not bad:- ok(f"眼睛和嘴都落在洞上(含洞外 1px 边缘带 ≥{tol_edges*100:.0f}%),"- f"且严格覆盖 ≥{min_strict*100:.0f}%")---def check_legacy(res: Path, bdir: Path | None, expect: float):- """传统光栅图占比。-- ⚠️ **底片从纯色换成渐变之后,"拿角点当背景色"这招就废了。** 原来靠- `a[1,1]` 取一个纯色再找和它不同的像素;换成星尘底片以后整个背景都和角点- 不同,于是角色 bbox 涨到整张图、占比量出 100.0%。这不是产物的问题,是判据- 的前提没了 —— 所以改成**和纯底片相减**:底片由 `cosmic_backdrop.render`- 出,生成器和校验器调的是同一份实现,不是各写一遍。-- ⚠️ `expect` 不能写死 0.88 —— 那 88% 是**量旧图量出来的**,不是一条独立于- 角色的约定。一旦下调用 `--content` 把角色缩小(为了给配景留空间),预期的- 占比必然跟着降,写死就会把正确的结果报成失败。这是这条判据**第二次**因为- 前提变化而失效。- """- print("\n── 7. 传统光栅图占比 / 圆形版 ──")- bad = 0- for name, dpi in DENSITIES:- lgs = int(round(LEGACY_CANVAS * dpi))- a = load_rgba(res / f"mipmap-{name}/ic_launcher.webp")- if bdir is not None:- bd = load_rgba(bdir / f"legacy-{name}.png")[:, :, :3]- d = np.abs(a[:, :, :3] - bd).sum(axis=2)- else:- bg = a[1, 1, :3]- d = np.abs(a[:, :, :3] - bg).sum(axis=2)- ys, xs = np.where(d > 12)- frac = max(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1) / lgs- mark = "✓" if abs(frac - expect) < 0.03 else "✗"- print(f" {name:8s} 传统图 {lgs:3d}px 角色占 {frac*100:5.1f}%"- f" (目标 {expect*100:.1f}%) {mark}")- if abs(frac - expect) >= 0.03:- fail(f"{name}: 传统图角色占 {frac*100:.1f}%,偏离目标 {expect*100:.1f}%")- bad += 1-- r = load_rgba(res / f"mipmap-{name}/ic_launcher_round.webp")- ral = r[:, :, 3]- rys, rxs = np.where(ral > 128)- # 满幅圆:最宽行应当等于边长(±2),且四角透明- widths = {}- for y in range(rys.min(), rys.max() + 1, max(1, lgs // 24)):- xr = np.where(ral[y] > 128)[0]- if len(xr):- widths[y] = xr.max() - xr.min() + 1- wmax = max(widths.values()) if widths else 0- corners = ral[0, 0] + ral[0, -1] + ral[-1, 0] + ral[-1, -1]- if wmax < lgs - 2:- fail(f"{name}: 圆形版最宽行 {wmax},应接近边长 {lgs}")- bad += 1- if corners > 8:- fail(f"{name}: 圆形版四角不透明(合计 {corners}),不是圆")- bad += 1- if not bad:- ok(f"传统图占 {expect*100:.1f}% 满幅(与生成时 --content 一致),"- f"圆形版是满幅圆(四角透明)")---def check_decor(bdir: Path | None):- """底片装饰本身的三条:确定性、亮度上限、星点存在。-- 这三条都是"看着挺好、下一版就悄悄坏掉"的类型,所以写成判据:-- * **确定性** —— 图标是提交进仓库的产物。同一 (size, seed) 只要有一点随机漂移,- 每次重跑都在 diff 里炸出一堆无意义的字节变更,真改动会被淹掉。- 所以这里**跨进程**比:同一个尺寸渲两遍必须逐像素相同。- * **亮度上限** —— 球体主体亮度实测 ≈130,底片再好看也不能跟球抢。把小尺寸下- "球还认不认得出"这件事变成一条可量的线。- * **星点存在** —— 装饰最容易出的事是"改了参数之后星点全被暗角/渐变吃掉",- 而肉眼在预览图那样的大图上根本发现不了。- """- print("\n── 8. 底片装饰(确定性 / 亮度上限 / 星点) ──")- if bdir is None:- print(" 没给 --backdrop,跳过(底片是纯色时这三条不适用)")- return- bad = 0-- # ① 确定性:同一个尺寸渲两遍- a1 = np.asarray(cosmic_backdrop.render(432))- a2 = np.asarray(cosmic_backdrop.render(432))- if not np.array_equal(a1, a2):- fail("同一尺寸渲两遍不一致 —— 底片不是确定性的(图标会每次重建都变)")- bad += 1- else:- print(" 确定性:同尺寸两遍逐像素相同 ✓")-- # ② 亮度上限- bg = load_rgba(bdir / "adaptive-xxxhdpi.png")[:, :, :3]- lum = 0.2126 * bg[:, :, 0] + 0.7152 * bg[:, :, 1] + 0.0722 * bg[:, :, 2]- print(f" 底片亮度 均值 {lum.mean():.1f} 中位 {np.median(lum):.1f}"- f" P99 {np.percentile(lum, 99):.1f} 最大 {lum.max():.1f}")- if np.percentile(lum, 99) > GLOW_CEIL:- fail(f"底片 P99 亮度 {np.percentile(lum, 99):.1f} 超过上限 {GLOW_CEIL}"- f" —— 会和球体(≈131)抢对比度")- bad += 1-- # ③ 星点:局部亮于周边 N 的孤立小亮点- med = np.median(lum)- lit = lum > med + STAR_MIN_DELTA- print(f" 星点数(亮于底片中位数 +{STAR_MIN_DELTA}) {int(lit.sum())} px")- if lit.sum() < 200:- fail(f"亮星只有 {int(lit.sum())} px —— 星点被渐变或暗角吃掉了")- bad += 1- if not bad:- ok("底片确定性、辉光不压过球、星点确实存在")---def main():- ap = argparse.ArgumentParser()- ap.add_argument("--res", default="app/src/main/res")- ap.add_argument("--src", default=None, help="源图,给了就顺便核对几何比例")- ap.add_argument("--backdrop", default=None,- help="纯底片目录(生成器 --dump-backdrop 的产物)。底片是渐变时"- "必给,否则第 7 项量不准")- ap.add_argument("--content", type=float, default=1.0,- help="角色大小因子,必须和生成时用的相同 —— 第 7 项的目标占比"- "要跟着它走(88% 是量旧图来的,不是独立约定)")- args = ap.parse_args()- res = Path(args.res)- bdir = Path(args.backdrop) if args.backdrop else None- expect_legacy = LEGACY_EXPECT * args.content-- print(f"校验 {res}")- check_alpha_semantics(res)- check_canvas_sizes(res)- check_visible_circle(res)- check_silhouette_match(res)- check_holes(res)- check_holes_align_with_face(res)- check_legacy(res, bdir, expect_legacy)- check_decor(bdir)-- total = sum(p.stat().st_size for p in res.glob("mipmap-*/*.webp"))- print(f"\n总体积 {total/1024:.1f} KiB")- for n in notes:- print(f" 注: {n}")- if failures:- print(f"\n✗ {len(failures)} 项没过")- return 1- print("\n✓ 全部通过")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/tools/cosmic_backdrop.py b/tools/cosmic_backdrop.pydeleted file mode 100644index 73e6185..0000000--- a/tools/cosmic_backdrop.py+++ /dev/null@@ -1,124 +0,0 @@-#!/usr/bin/env python3-"""星尘宇宙底片 —— 启动图标的自适应背景层。--## 为什么单独一个模块--底片不只生成器要用,**校验器也要用**:校验"角色在传统光栅图里占 88%"时,-原来靠 `a[1,1]` 取一个背景纯色再找和它不同的像素 —— 那招在渐变底上直接失效-(整个背景都和角点不一样,角色 bbox 会涨到整张图)。所以校验器改成"和纯底片-相减",于是底片必须是两边都能调到的同一份实现。--## 两条硬约束--1. **确定性。** 同一 (size, seed) 必须逐像素一样。图标是提交进仓库的产物,- 每次重跑都在 diff 里炸出一堆无意义的字节变更,是很实在的噪音。-2. **亮度压在球体之下。** 球体主体亮度实测 ≈130。底片再好看也不能跟球抢 ——- 目标是把辉光峰值压在 100 以下,给球留出对比度。这不是审美,是"小尺寸下- 球还认不认得出"的问题,所以校验器里有一条专门量它(见 check 8)。-"""-import numpy as np-from PIL import Image--SEED = 20260930--# 深空紫:中心偏紫,边缘近黑-CORE = (46, 26, 92)-EDGE = (9, 6, 19)-# 品红辉光,垫在球后面 —— 球挡住中心,露出来的正好是一圈光晕-GLOW = (214, 74, 172)-GLOW_STRENGTH = 0.42-# 低频紫云,给渐变加一点层次,免得看上去像"圆的线性渐变"-#-# ⚠️ 第一版是 n=24 / 强度 0.16,结果**看出「拼布」**了:每 18px 一个格子、格边可见,-# 中间再被品红辉光一放大,读起来像图片压缩块,不像星云。教训是这类"随机场放大"-# 的**格子尺寸**才是观感的主导 —— 幅度只有 ±10 几个色阶,眼睛照样抓得住连贯结构。-# 所以 n 从 24 降到 7(格子 ~62px,比球还大),强度同步减半:要的是**光的不均匀**,-# 不是**纹理**。-NEBULA = (120, 70, 200)-NEBULA_STRENGTH = 0.085-VIGNETTE = 0.30-STAR_N = 110---def _stars(size: int, seed: int) -> np.ndarray:- """星点。核心 + 一圈淡光晕,大小/亮度/色偏都用同一个 rng 定,所以可重现。"""- rng = np.random.default_rng(seed + 1)- acc = np.zeros((size, size, 3), np.float64)- scale = size / 432.0- for _ in range(STAR_N):- x = float(rng.random()) * size- y = float(rng.random()) * size- # **2.2 让大部分星很小、少数明显偏大 —— 均匀分布会得到"一片均匀的麻点"- rr = (0.45 + float(rng.random()) ** 2.2 * 2.1) * scale- b = 0.22 + 0.78 * float(rng.random()) ** 2.5- t = float(rng.random())- if t < 0.62:- col = np.array([1.00, 1.00, 1.00])- elif t < 0.84:- col = np.array([0.78, 0.72, 1.00]) # 淡紫- else:- col = np.array([1.00, 0.74, 0.93]) # 淡粉- col = col * b * 255.0- for rad, k in ((rr, 1.0), (rr * 2.7, 0.20)):- x0, x1 = max(0, int(x - rad - 1)), min(size, int(x + rad + 2))- y0, y1 = max(0, int(y - rad - 1)), min(size, int(y + rad + 2))- if x1 <= x0 or y1 <= y0:- continue- yy, xx = np.mgrid[y0:y1, x0:x1]- d = np.hypot(xx + 0.5 - x, yy + 0.5 - y)- w = np.clip(1.0 - d / max(rad, 1e-6), 0.0, 1.0)- acc[y0:y1, x0:x1] += w[:, :, None] * col[None, None, :] * k- return acc---def render(size: int, ball_cx: float = None, ball_cy: float = None,- ball_r: float = None, seed: int = SEED) -> Image.Image:- """渲一张 size×size 的星尘底片。-- bit 中心 / 半径用来把辉光垫在球的正后方 —— 传 None 就退回画布中心。- 传进来而不是"默认居中"是有理由的:自适应层里球被下移过 dy,辉光跟着- 画布中心走就会和球错开,看上去像贴歪了的反光。- """- yy, xx = np.mgrid[0:size, 0:size]- cx = float(ball_cx) if ball_cx is not None else (size - 1) / 2.0- cy = float(ball_cy) if ball_cy is not None else (size - 1) / 2.0- R = float(ball_r) if ball_r else size * 0.30-- # 1) 径向渐变- d = np.hypot(xx - cx, yy - cy)- t = np.clip(d / (R * 2.6), 0.0, 1.0) ** 0.85- img = np.zeros((size, size, 3), np.float64)- for i in range(3):- img[:, :, i] = CORE[i] * (1.0 - t) + EDGE[i] * t-- # 2) 品红辉光- g = np.exp(-0.5 * (d / max(R * 0.92, 1e-6)) ** 2) * GLOW_STRENGTH- img += g[:, :, None] * np.array(GLOW, np.float64)-- # 3) 低频紫云:小尺寸随机场放大 —— 用 BICUBIC 插值,确定性- rng = np.random.default_rng(seed)- n = 7- low = rng.random((n, n))- cloud = np.asarray(- Image.fromarray((low * 255).astype(np.uint8)).resize((size, size), Image.BICUBIC)- ).astype(np.float64) / 255.0- cloud = cloud - cloud.mean()- img += cloud[:, :, None] * NEBULA_STRENGTH * np.array(NEBULA, np.float64)-- # 4) 星点- img += _stars(size, seed)-- # 5) 暗角(放在星点之后,角落的星也跟着压暗,像真的景深)- v = np.clip(d / (size * 0.72), 0.0, 1.0) ** 2 * VIGNETTE- img *= (1.0 - v)[:, :, None]-- return Image.fromarray(np.clip(img, 0, 255).astype(np.uint8), "RGB")---if __name__ == "__main__":- import sys- from pathlib import Path- out = Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/shot/cosmic.png")- out.parent.mkdir(parents=True, exist_ok=True)- render(432).save(out)- print(f"底片 -> {out}")diff --git a/tools/make_launcher_icon.py b/tools/make_launcher_icon.pyindex b89cf37..bcbfe66 100644--- a/tools/make_launcher_icon.py+++ b/tools/make_launcher_icon.py@@ -1,172 +1,135 @@#!/usr/bin/env python3-"""从一张**透明底的角色渲染图**生成整套 Android 启动图标。+"""从 images/brand/andee-head.png 生成整套 Android 启动图标。-## 和「从美术稿做图标」那套流程的区别+源图是不透明的(白底 + 橙粉光晕 + 蓝色头部),抠图与五官遮罩在+`andee_head.py`;这里只管"怎么摆到各个图层里"。-那套流程的对象是别人画好的一张**不透明**方图,难点全在"把主体从背景里抠-出来":背景色是猜的、几何圆遮罩会糊边、五官要找亮度阈值。这一版不一样 ——-源图由 `tools/ball_shot.mjs` 从实验室那一页渲出来,**自带一路 alpha**:+## 四种图- * **不用抠图**。alpha 就是剪影,边界就是美术自己的边界,没有"几何圆 vs- 按背景抠"这个取舍,也不会有 1px 的羽化假边。- * **不用猜背景色**。背景层是单独填的纯色,源图里根本没有背景。- * **五官的阈值有干净的峰**。实测球内亮度直方图是三个分离的峰:眼睛 33±2- (21070px)、嘴 78±2(2905px)、主体 120–215,峰与峰之间是空的。阈值落在- 空隙里是量出来的,不是试出来的。+ * `ic_launcher_foreground` 自适应前景:抠出的角色,透明底+ * `ic_launcher_background` 自适应背景:**源图自己的光晕**,头部那块用周围的+ 光晕补平(push-pull 式的归一化卷积)。不是另画一张渐变 —— 图标和封面要+ 看起来是同一张画,所以用同一份光晕+ * `ic_launcher_monochrome` 主题图标:黑 = 实体,透明 = 镂空,眼睛和嘴是洞+ * `ic_launcher` / `_round` 传统光栅图(API < 26 与部分启动器):背景 + 角色+ 合成,圆形版加圆遮罩-## 几何怎么定(没有一个是拍的)+## 几何-**构图下移。** 角色的外接圆是歪的:耳朵在斜上方把它撑开,而**可见圆是以画布-中心为圆心的**。把角色整体下移,让"到画布中心的最大距离"最小 —— 实测最优-下移 43px,最大半径 357.9 → 323.6,**白赚 10.6%**。不做这一步,球还要再小-10%。+**一次变换,不是每层各缩一次。** 所有层从同一张源图、同一个 scale、同一组整数+offset 变换过去 —— 每层各缩一次会让单色层的眼睛洞和前景的眼睛差 1px,432px+上看不出,108px 上一眼就歪。-**球体尺寸不是自由变量。** 外接圆半径 / 球半径 = 1.154,因为耳朵伸在球外。-要让**整个角色**落进保证可见的 72dp 圆里,球就只能是角色高度的一个固定比例。-这是几何结论,不是缩水的选择 —— 肉眼看到的是"整个角色",而角色占可见圆的-比例几乎没变(95.8% → 96.5%)。+**外接圆决定大小。** 系统把画布中央 72/108 当保证可见的圆。角伸在头外,外接圆+比头大;把角色整体下移到"到画布中心的最大距离"最小,再把这个距离缩到可见圆半径+的 `CONTENT` 倍。角永远不会被圆形遮罩切到。-**两层用两套占比,不能互相缩。** 自适应层沿用被替换那套的 CONTENT=276/432-(先量旧图再沿用,换图才不会改变桌面上的视觉大小);传统光栅图**单独构建**-—— 从自适应画布缩下来会把"为遮罩预留的死环"一起烘进去,48px 下就是贴纸。-传统图按满幅惯例,角色占 88%(实测旧图 169/192 = 88.0%)。--## 单色层的语义--**黑 = 实体,透明 = 镂空**,不是"画一个白色剪影"。眼睛和嘴是 alpha=0 的洞。--### 剪影绝不二值化(这条踩过,而且错得不明显)--第一版写的是 `sil = alpha > 128`,结果单色层的剪影和美术层的 IoU 只有-**0.8611**,单色层还比美术层宽 16px(@432)。原因是把剪影当成了"一个实心形状",-而它其实不是 —— 球最外那一圈描边(`rimDark`)的 alpha 是一条**斜坡**:-- 球心行剖面,从最外沿往内:- 202 168 109 86 65 53 44 37 30 24 20 16 14 11 9 8 7 | 118 231 233 ...--最外沿 202,向内一路衰减到 **7**,然后球体本体的 231 才开始。也就是说描边那一圈-(18px @1152)的 alpha 从 79% 掉到 3% —— 描边是靠最外那 1~2px 撑着的。--任何阈值都会把这条斜坡切成两段:阈值以上留一个细环、阈值以下丢掉整条斜坡,-中间断开。所以**单色层的 alpha 直接沿用源图的 alpha**,不二值化 ——-alpha 本来就是这个像素"被角色覆盖了多少",那正是 mask 要的语义。--眼睛和嘴**必须用 bbox 拟合椭圆 / 真实形状,不能用阈值 mask**:-- * 眼球里有一个亮度 252–255 的高光白点,阈值 mask 会在洞里留一个疙瘩。- * 嘴是两端收细的弧,矩形框要么切掉嘴角,要么把背景一起拖走。- * **耳朵会把嘴的阈值一起命中的坑**:耳朵亮度中位数 90,和嘴的 78 只差 12,- 光靠亮度分不开。分开它们靠**位置** —— 耳朵整片都在球心上方。所以判据是- `y > 球心` 而不是调阈值。--## 一次变换,不是每层各缩一次--所有层都从**同一张源图**、用**同一个 scale 和同一个整数 offset** 变换过去。-每层各缩一次(尤其遮罩单独缩)会让单色层挖掉的眼睛和美术层的眼睛差 1px ——-432px 上看不出来,108px 上一眼就歪。所以这里先在源图分辨率上把要合成的东西-合成完,再整张变换一次。+传统图单独构建(同样按外接圆,占圆形的 `LEGACY_CONTENT`),不从自适应画布缩下+来 —— 那样会把为遮罩预留的那圈死边一起缩进去,48px 上就是一张贴纸。用法:- python tools/make_launcher_icon.py --src a.alpha.png --check-only- python tools/make_launcher_icon.py --src a.alpha.png --res app/src/main/res \\- --dump-masks /tmp/masks.png+ python3 tools/make_launcher_icon.py # 写 app/src/main/res/mipmap-*+ python3 tools/make_launcher_icon.py --dump /tmp/x # 另存背景 / 前景大图核对"""import argparseimport sysfrom pathlib import Pathimport numpy as np-from PIL import Image, ImageDraw, ImageFilter+from PIL import Image, ImageFilter-import cosmic_backdrop+sys.path.insert(0, str(Path(__file__).resolve().parent))+import andee_head as head # noqa: E402-# ---------------------------------------------------------------- 常量DENSITIES = [("mdpi", 1.0), ("hdpi", 1.5), ("xhdpi", 2.0), ("xxhdpi", 3.0), ("xxxhdpi", 4.0)]ADAPTIVE_DP = 108.0LEGACY_DP = 48.0--# 保证可见圆:系统把画布中央 72/108 铺满图标位,外面那圈是给遮罩预留的。VISIBLE_FRACTION = 72.0 / 108.0-# 角色到画布中心的最大半径,占可见圆半径的比例。**基准** 139/144 = 96.5%-# (沿用被替换那套的视觉大小,留的余量是给锐化的 —— 锐化会让主体略微外扩)。-#-# ⚠️ 这个 96.5% 有一个副作用,加了装饰之后才暴露出来:**装饰是加在球周围的**,-# 球占满可见圆的时候,底片只剩一圈细边,等于白加。所以 `--content` 是一个乘在-# 这个基准上的因子,用来给配景让出可见空间。缩小时**必须连传统光栅图一起缩**-# (见下),否则同一个设备上桌面图标和圆形图标会显示成两种大小。-CONTENT_OF_VISIBLE = 139.0 / 144.0--# 传统光栅图上"角色"占方形的比例。实测旧图 169/192 = 88.0%。-# 同样乘 `--content` —— 这两条路的角色大小在视觉上必须一致(见上)。-LEGACY_CONTENT = 0.88--BG = (14, 23, 43) # 实测旧图标 background 的纯色 #0E172B--# 源图上的阈值,落在实测的峰之间的空隙里。**空隙在哪要量,不能看着像就定。**-EYE_LUM = 60.0 # 眼睛 33±2,下一个峰在 76 → 60 落在空隙里-# ⚠️ 嘴这里踩过一次:原来写 120,而**球体自身的暗部底就是 120.6**(下半部亮度-# 分位 5%=78.9、10%=120.6、50%=124.1)。阈值贴着球体暗部底的结果是把它一起吞-# 进来当嘴:阈值 115→120 时"嘴"的像素从 589 涨到 725、被挖空覆盖从 89.3% 掉到-# 72.6%;120→125 更是从 725 暴涨到 6131。真正的谷底在 79 和 120 之间,取 100。-MOUTH_LUM = 100.0 # 嘴 78±2,球体暗部底 120.6 → 100 落在谷底正中-BALL_INNER = 0.90 # 只在球体半径的这个比例内找五官,把耳根挡在外面--SHARPEN_RADIUS = 1.0-SHARPEN_PERCENT = 60--# ---- 装饰:星尘宇宙 -----# 球缘那圈紫粉边缘光,让它"接住"背景的辉光。宽度按球半径取比例(不是固定像素),-# 否则 432 画布上调好的宽度到 108 画布上就成了一整块糊。-RIM_COLOR = (188, 96, 226)-RIM_OF_R = 0.030-RIM_STRENGTH = 0.50---def rim_tint(im: Image.Image, color, ball_r: float, of_r: float) -> Image.Image:- """把剪影最外那薄薄一圈染向 color —— 模拟环境光打在边缘。-- **只改 RGB,不动 alpha。** 这既是"剪影绝不能碰"的老规矩,也是这次能加装饰- 的前提:边缘光在剪影内部,所以可见圆的预算一点没动(前景层的最大半径不变)。-- 做法:`alpha>200` 腐蚀掉 of_r*ball_r 得到内芯,`实心 & ~内芯` 就是贴着边界的- 那圈;再高斯模糊出柔和过渡。模糊会让它溢到剪影外,但那里 alpha=0,看不见。+# 角色外接圆半径 / 可见圆半径。小于 1 是给光晕留出看得见的一圈 —— 角色占满可见圆+# 的话,背景只剩一道细边,等于白做。+CONTENT = 0.86+# 传统图:外接圆半径 / (方图边长的一半)。圆形版的圆就是这一半,所以 < 1 才保证+# 角不被切。+LEGACY_CONTENT = 0.90++SHARPEN_PERCENT = 40+++# ---------------------------------------------------------------- 背景+def gauss_fft(field: np.ndarray, sigma: float) -> np.ndarray:+ """频域高斯模糊。PIL 的 GaussianBlur 不支持浮点图,scipy 这里没有。"""+ H, W = field.shape+ fy = np.fft.fftfreq(H)[:, None]+ fx = np.fft.fftfreq(W)[None, :]+ k = np.exp(-2.0 * (np.pi ** 2) * (sigma ** 2) * (fx ** 2 + fy ** 2))+ return np.real(np.fft.ifft2(np.fft.fft2(field) * k))+++def glow_background(a: np.ndarray, hard: np.ndarray) -> np.ndarray:+ """把源图里头部那块补成周围光晕的延伸,得到一张只有光晕的底片。++ 光晕是以头部为中心向外的径向渐变,所以补法是**按距离取环**:对头部之外的+ 每个半径,取该半径上光晕像素的平均色,再让头部之内的像素按到头部中心的+ 距离去查这张"半径→颜色"表。内部的半径超出已知范围时,沿用最内一环的颜色。+ 再整体做一次大半径模糊压掉环状噪声 —— 头部被角色盖住,补出来的内容只在+ 系统给图层做视差位移时才会露一点边,要的是平滑,不是细节。++ 第一版用的是"归一化卷积"(已知像素带权重向未知区域扩散):头部这么大一块+ 洞,它在洞中央只剩一个很小的权重,补出来是一个白斑加一道头部轮廓的影子。"""- a = np.asarray(im).astype(np.float64)- # ⚠️ 必须转成 Python float —— ball_r 一路从 numpy 运算下来是 np.float64,- # 而 PIL 的 GaussianBlur 里要 `if xy == (0, 0)`,np.float64 和元组比较会返回- # 一个数组,于是抛 "truth value of an array is ambiguous"。报错点还落在 PIL 里,- # 看着像是 PIL 的毛病。- ball_r = float(ball_r)- solid = a[:, :, 3] > 200- core = solid.copy()- for _ in range(max(1, int(round(ball_r * of_r)))):- core = (core & np.roll(core, 1, 0) & np.roll(core, -1, 0)- & np.roll(core, 1, 1) & np.roll(core, -1, 1))- ring = solid & ~core- w = Image.fromarray((ring * 255).astype(np.uint8), "L").filter(- ImageFilter.GaussianBlur(max(0.6, ball_r * of_r * 0.55)))- ww = np.asarray(w).astype(np.float64) / 255.0 * RIM_STRENGTH- out = a.copy()- for i in range(3):- out[:, :, i] = a[:, :, i] * (1.0 - ww) + color[i] * ww- return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8), "RGBA")+ H, W = hard.shape+ ys, xs = np.where(hard)+ cy, cx = ys.mean(), xs.mean()+ yy, xx = np.mgrid[0:H, 0:W]+ dist = np.hypot(xx - cx, yy - cy)++ near = hard.copy()+ for _ in range(8):+ near = near | np.roll(near, 1, 0) | np.roll(near, -1, 0) | np.roll(near, 1, 1) | np.roll(near, -1, 1)+ known = ~near++ # 头部外沿最远的半径之外才是"光晕环"可用的范围;只取到画布内接圆,避开+ # 四个角上的纯白。+ rmax = min(H, W) / 2.0+ edges = np.arange(0.0, rmax + 1.0, 2.0)+ idx = np.digitize(dist, edges) - 1+ nb = len(edges) - 1+ table = np.zeros((nb, 3))+ have = np.zeros(nb, bool)+ for c in range(3):+ s = np.bincount(idx[known & (idx < nb)], weights=a[..., c][known & (idx < nb)], minlength=nb)[:nb]+ n = np.bincount(idx[known & (idx < nb)], minlength=nb)[:nb]+ ok = n > 40+ table[ok, c] = s[ok] / n[ok]+ have |= ok+ first = int(np.argmax(have))+ for i in range(first):+ table[i] = table[first]+ for i in range(first, nb):+ if not have[i]:+ table[i] = table[i - 1]+ out = a.copy()+ inner = near & (idx >= 0) & (idx < nb)+ out[inner] = table[idx[inner]]+ # 径向表在方位上是平均的,会丢掉"左橙右粉"的方位差;再混回一点原有光晕的+ # 方位信息:用已知像素相对表值的残差做一个很大的模糊后加回去。+ res = np.where(known[..., None], a - table[np.clip(idx, 0, nb - 1)], 0.0)+ w = gauss_fft(known.astype(np.float64), 120.0)+ for c in range(3):+ r = gauss_fft(res[..., c], 120.0)+ out[..., c][near] += (r / np.maximum(w, 0.03))[near]+ for c in range(3):+ sm = gauss_fft(out[..., c], 18.0)+ out[..., c][near] = sm[near]+ return np.clip(out, 0, 255)-def backdrop(size: int, ball_cx: float, ball_cy: float, ball_r: float, decor: str):- """底片。`none` 就是原来的纯色 —— 老样式要能原样复现,不能只有新样式。"""- if decor == "cosmic":- return cosmic_backdrop.render(size, ball_cx, ball_cy, ball_r)- return Image.new("RGB", (size, size), BG)# ---------------------------------------------------------------- 工具def resize_rgba(im: Image.Image, size: int) -> Image.Image:- """缩放 RGBA。**必须走预乘**,否则透明像素的黑会渗进半透明边缘变成暗边。-- 这不是保险起见:源图是"深色描边 + 抗锯齿过渡",直通缩放时插值会把透明的- 黑混进边缘像素,48px 上就是一圈脏边。- """+ """缩放 RGBA,走预乘 —— 否则透明像素的黑会渗进半透明边缘变成暗边。"""a = np.asarray(im).astype(np.float64)al = a[:, :, 3:4] / 255.0pm = Image.fromarray(np.dstack([a[:, :, :3] * al, a[:, :, 3]]).astype(np.uint8), "RGBA")@@ -176,116 +139,17 @@ def resize_rgba(im: Image.Image, size: int) -> Image.Image:return Image.fromarray(np.dstack([np.clip(rgb, 0, 255), b[:, :, 3]]).astype(np.uint8), "RGBA")-def resize_mask(im: Image.Image, size: int) -> Image.Image:- """缩放灰度遮罩。用 BOX(面积平均)—— 遮罩是"覆盖了多少",面积平均才是它的- 定义;LANCZOS 会在细笔画两侧振铃,把 5px 宽的嘴拆成一串亮点。"""- return im.resize((size, size), Image.BOX)--def sharpen_rgb(im: Image.Image) -> Image.Image:- """只锐化 RGB,**绝不碰 alpha** —— 碰 alpha 会把剪影弄毛,而剪影是整图对比度- 最高的地方,一锐就是一圈亮边。"""+ """只锐化 RGB,绝不碰 alpha —— 碰 alpha 会把剪影弄毛。"""r, g, b, a = im.split()rgb = Image.merge("RGB", (r, g, b)).filter(- ImageFilter.UnsharpMask(radius=SHARPEN_RADIUS, percent=SHARPEN_PERCENT, threshold=0)- )+ ImageFilter.UnsharpMask(radius=1.0, percent=SHARPEN_PERCENT, threshold=0))r2, g2, b2 = rgb.split()return Image.merge("RGBA", (r2, g2, b2, a))-def find_ball(alpha: np.ndarray):- """从 alpha 求球体的圆心与半径。-- 球是最大的圆,且耳朵**不超出球在水平方向上的宽度**(耳朵往上长、往外撇,- 但撇得没球宽),所以"最宽那一行的宽度"就是球直径。球底就是整张图的最下沿- —— 耳朵只往上长。- """- ys, xs = np.where(alpha > 8)- if len(ys) == 0:- raise SystemExit("源图是空的 —— 全是透明像素")- best = (0, None)- for y in range(ys.min(), ys.max() + 1):- xr = np.where(alpha[y] > 8)[0]- if len(xr):- w = xr.max() - xr.min() + 1- if w > best[0]:- best = (w, (int(xr.min()), int(xr.max())))- d, (x0, x1) = best- r = d / 2.0- return (x0 + x1) / 2.0, float(ys.max()) - r, r, (- int(ys.min()), int(ys.max()), int(xs.min()), int(xs.max()))---def best_shift(ys, xs, H, W, search=140):- """扫出那个让"到画布中心的最大距离"最小的下移量。-- 可见圆以画布中心为圆心,所以要最小化的就是"角色到画布中心的最大距离"- —— 不是到球心的距离,也不是 bbox 的居中。- """- ccx, ccy = (W - 1) / 2.0, (H - 1) / 2.0- base = float(np.hypot(xs - ccx, ys - ccy).max())- best = (base, 0)- for dy in range(-search, search + 1):- d = float(np.hypot(xs - ccx, (ys + dy) - ccy).max())- if d < best[0]:- best = (d, dy)- return base, best[1], best[0]---def _components(mask: np.ndarray, min_px: int, limit: int = 6):- """4-邻域连通域。不引 scipy —— 这个仓库的图标链路只依赖 numpy + PIL。"""- H, W = mask.shape- lab = np.zeros(mask.shape, np.int32)- out = []- cur = 0- for sy, sx in zip(*np.where(mask)):- if lab[sy, sx]:- continue- cur += 1- stack = [(sy, sx)]- lab[sy, sx] = cur- pix = []- while stack:- y, x = stack.pop()- pix.append((y, x))- for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):- if 0 <= ny < H and 0 <= nx < W and mask[ny, nx] and not lab[ny, nx]:- lab[ny, nx] = cur- stack.append((ny, nx))- if len(pix) >= min_px:- out.append(np.array(pix))- out.sort(key=len, reverse=True)- return out[:limit]---def ellipse_mask(shape, box, grow=1.0):- x0, y0, x1, y1 = box- cxe, cye = (x0 + x1) / 2.0, (y0 + y1) / 2.0- axe, aye = (x1 - x0 + 1) / 2.0 * grow, (y1 - y0 + 1) / 2.0 * grow- H, W = shape- yy, xx = np.mgrid[0:H, 0:W]- return ((xx - cxe) / axe) ** 2 + ((yy - cye) / aye) ** 2 <= 1.0---def close_mask(mask, iters=2):- """形态学闭运算(先膨胀再腐蚀),把嘴的暗像素连成一片 —— 嘴是弧,内部亮度- 并不完全均匀,直接取阈值会得到几段。"""- m = mask- for _ in range(iters):- m = m | np.roll(m, 1, 0) | np.roll(m, -1, 0) | np.roll(m, 1, 1) | np.roll(m, -1, 1)- for _ in range(iters):- m = m & np.roll(m, 1, 0) & np.roll(m, -1, 0) & np.roll(m, 1, 1) & np.roll(m, -1, 1)- return m--def blit(dst: Image.Image, src: Image.Image, ox: int, oy: int):- """把 src 贴到 dst 的 (ox, oy),负坐标也正确裁剪。-- **所有层都必须走这一个函数**,这是"各层共用同一次变换"在结构上的保证:- 只要 offset 是同一组整数,单色层挖掉的眼睛就不可能和美术层的眼睛差- 1px。每个调用点各写一遍 paste(或各自 round 一次),那个 1px 的偏差就会- 回来 —— 432px 上看不出来,108px 上一眼就歪。- """+ """贴图,负坐标也正确裁剪。所有层都必须走这一个函数,见文件头。"""dw, dh = dst.sizesw, sh = src.sizex0, y0 = max(0, ox), max(0, oy)@@ -293,232 +157,106 @@ def blit(dst: Image.Image, src: Image.Image, ox: int, oy: int):if x1 <= x0 or y1 <= y0:returnpatch = src.crop((x0 - ox, y0 - oy, x1 - ox, y1 - oy))- dst.paste(patch, (x0, y0), patch)-+ dst.paste(patch, (x0, y0), patch if patch.mode == "RGBA" else None)-def analyse(arr, quiet=False):- """量出球体、最优下移、五官遮罩。返回一个 dict。"""- alpha = arr[:, :, 3]- H, W = alpha.shape- cx, cy, r, bbox = find_ball(alpha)- ys, xs = np.where(alpha > 8)- base, dy, opt = best_shift(ys, xs, H, W)- rgb = arr[:, :, :3]- lum = 0.2126 * rgb[:, :, 0] + 0.7152 * rgb[:, :, 1] + 0.0722 * rgb[:, :, 2]- yy, xx = np.mgrid[0:H, 0:W]- d2c = np.hypot(xx - cx, yy - cy)- inside = (alpha > 200) & (d2c < r * BALL_INNER)-- eye_hits = _components(inside & (yy < cy) & (lum < EYE_LUM), int(r * r * 0.004))- eyes = sorted(- [(int(p[:, 1].min()), int(p[:, 0].min()), int(p[:, 1].max()), int(p[:, 0].max()))- for p in eye_hits[:2]],- key=lambda e: (e[0] + e[2]) / 2,- )- # 嘴:靠**位置**和耳朵分开,不是靠亮度 —— 耳朵中位亮度 90 vs 嘴 78,阈值分不开;- # 而耳朵整片在球心上方。- mouth_hits = _components(inside & (yy > cy) & (lum < MOUTH_LUM), int(r * r * 0.004))- mouth = mouth_hits[0] if mouth_hits else None-- eye_masks = [ellipse_mask((H, W), e, grow=1.06) for e in eyes]- if mouth is not None:- m = (lum < MOUTH_LUM) & (yy > cy) & (d2c < r * BALL_INNER)- mouth_mask = close_mask(m, 2)- else:- mouth_mask = None-- if not quiet:- print(f" 球体 球心 ({cx:.1f},{cy:.1f}) 半径 {r:.1f} 直径 {2*r:.0f}")- print(f" bbox y[{bbox[0]},{bbox[1]}] x[{bbox[2]},{bbox[3]}]"- f" 宽 {bbox[3]-bbox[2]+1} 高 {bbox[1]-bbox[0]+1}")- print(f" 构图 画布中心最大半径 {base:.1f} → 下移 {dy}px 后 {opt:.1f}"- f" (白赚 {(base-opt)/opt*100:.1f}%)")- print(f" 外接圆/球半径 = {opt/r:.3f} —— 球在图标里的尺寸上限"- f"(耳朵伸在球外,占掉这部分)")- print(f" 五官 (眼<{EYE_LUM:.0f} / 嘴<{MOUTH_LUM:.0f}, 球内 {BALL_INNER:.0%}):")- for i, e in enumerate(eyes):- print(f" 眼{i+1} bbox x[{e[0]},{e[2]}] y[{e[1]},{e[3]}]"- f" {e[2]-e[0]+1}×{e[3]-e[1]+1}")- if mouth is not None:- y0, x0 = mouth.min(axis=0)- y1, x1 = mouth.max(axis=0)- print(f" 嘴 {len(mouth)}px bbox x[{x0},{x1}] y[{y0},{y1}] {x1-x0+1}×{y1-y0+1}")- else:- print(" 嘴 没找到")- v = lum[inside]- print(f" 阈值余量 眼({EYE_LUM:.0f}) 与下一峰之间 {int(((v>EYE_LUM)&(v<70)).sum())}px")-- return dict(cx=cx, cy=cy, r=r, bbox=bbox, dy=dy, opt=opt, base=base,- eyes=eyes, eye_masks=eye_masks, mouth_mask=mouth_mask,- H=H, W=W, alpha=alpha)---def dump_masks(arr, info, path):- """把人眼核对用的遮罩图写出来。-- 这一步不是装饰:阈值落在空隙里是算出来的,但"算出来的洞是不是真的盖住了- 眼睛"只有看图才知道。耳朵那一带尤其要看 —— 它的亮度和嘴只差 12。- """- H, W = info["H"], info["W"]- base = Image.fromarray(np.clip(arr[:, :, :3], 0, 255).astype(np.uint8)).convert("RGB")- ov = np.array(base).copy()- for m in info["eye_masks"]:- ov[m] = (ov[m] * 0.25 + np.array([255, 40, 40]) * 0.75).astype(np.uint8)- if info["mouth_mask"] is not None:- m = info["mouth_mask"]- ov[m] = (ov[m] * 0.25 + np.array([40, 255, 90]) * 0.75).astype(np.uint8)- # 球心十字 + 球轮廓- im = Image.fromarray(ov)- d = ImageDraw.Draw(im)- cx, cy, r = info["cx"], info["cy"], info["r"]- d.line([(cx - 40, cy), (cx + 40, cy)], fill=(255, 255, 0), width=4)- d.line([(cx, cy - 40), (cx, cy + 40)], fill=(255, 255, 0), width=4)- d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(0, 255, 255), width=3)- d.ellipse([cx - r * BALL_INNER, cy - r * BALL_INNER,- cx + r * BALL_INNER, cy + r * BALL_INNER], outline=(255, 0, 255), width=3)- im.resize((760, 760), Image.LANCZOS).save(path)- print(f" 遮罩核对图 -> {path}")+def webp(im: Image.Image, path: Path):+ im.save(path, "WEBP", lossless=True, method=6)# ---------------------------------------------------------------- 主流程def main():ap = argparse.ArgumentParser()- ap.add_argument("--src", required=True, help="透明底源图(ball_shot.mjs 的 .alpha.png)")ap.add_argument("--res", default="app/src/main/res")- ap.add_argument("--check-only", action="store_true")- ap.add_argument("--dump-masks", default=None)- ap.add_argument("--no-sharpen", action="store_true")- ap.add_argument("--decor", default="none", choices=("none", "cosmic"),- help="背景装饰样式。none=原来的纯色底(默认,便于复现旧样式)")- ap.add_argument("--dump-backdrop", default=None,- help="把纯底片另存到该目录 —— 校验器要靠它把角色从渐变底上量出来")+ ap.add_argument("--dump", default=None, help="把源分辨率的背景/前景/单色另存到该目录")ap.add_argument("--content", type=float, default=1.0,- help="角色大小因子(乘在 CONTENT_OF_VISIBLE / LEGACY_CONTENT 上)。"- "1.0 = 沿用旧图视觉大小;调小给配景留空间。自适应层与传统层"- "同比例缩,保证两种图标视觉一致")+ help="角色大小因子,乘在 CONTENT / LEGACY_CONTENT 上")args = ap.parse_args()- src = Image.open(args.src).convert("RGBA")- arr = np.asarray(src).astype(np.float64)- print(f"源图 {src.size}")- info = analyse(arr)- if args.dump_masks:- dump_masks(arr, info, args.dump_masks)- if args.check_only:- return 0-- H, W, r, dy = info["H"], info["W"], info["r"], info["dy"]- cx, cy = info["cx"], info["cy"]+ rgba, alpha, hard, a = head.character_rgba()+ H, W = alpha.shapeccx, ccy = (W - 1) / 2.0, (H - 1) / 2.0- bbox = info["bbox"]-- # ---- 在源图分辨率上把要合成的东西都做好,之后每层只做同一次变换 ----- # 单色层的 alpha = **源图的 alpha 原样**,只把五官挖掉。- # 不二值化,理由见文件头"剪影绝不二值化"那一段 —— 描边的 alpha 是一条- # 从 202 衰减到 7 的斜坡,阈值会把它切成断开的两段。- holes = np.zeros((H, W), bool)- for m in info["eye_masks"]:- holes |= m- if info["mouth_mask"] is not None:- holes |= info["mouth_mask"]- mono = info["alpha"].copy()+ opt, dy = head.circumcircle(alpha)+ holes, boxes, _ = head.face_holes(a, hard)+ print(f"源图 {W}×{H} 外接圆半径 {opt:.1f}px,下移 {dy}px")++ char = Image.fromarray(rgba, "RGBA")+ bg_arr = glow_background(a, hard)+ bg = Image.fromarray(bg_arr.astype(np.uint8), "RGB")+ border = np.concatenate([bg_arr[0], bg_arr[-1], bg_arr[:, 0], bg_arr[:, -1]])+ pad = tuple(int(round(v)) for v in np.median(border, axis=0))++ mono = alpha.copy()mono[holes] = 0.0- mono_img = Image.fromarray(np.clip(mono, 0, 255).astype(np.uint8), "L")+ mono_img = Image.fromarray(np.clip(mono * 255.0, 0, 255).astype(np.uint8), "L")- res = Path(args.res)- outdirs = {n: res / f"mipmap-{n}" for n, _ in DENSITIES}- for d in outdirs.values():+ if args.dump:+ d = Path(args.dump)d.mkdir(parents=True, exist_ok=True)- bdir = Path(args.dump_backdrop) if args.dump_backdrop else None- if bdir:- bdir.mkdir(parents=True, exist_ok=True)+ bg.save(d / "background.png")+ char.save(d / "foreground.png")+ mono_img.save(d / "monochrome.png")- written = []- content = CONTENT_OF_VISIBLE * args.content+ res = Path(args.res)+ content = CONTENT * args.contentlegacy_content = LEGACY_CONTENT * args.content- if args.content != 1.0:- print(f"角色缩放因子 {args.content:.3g}"- f" (自适应 {CONTENT_OF_VISIBLE*100:.1f}% → {content*100:.1f}% 可见圆,"- f"传统 {LEGACY_CONTENT*100:.0f}% → {legacy_content*100:.1f}% 方形)")+ total = 0for name, dpi in DENSITIES:+ out = res / f"mipmap-{name}"+ out.mkdir(parents=True, exist_ok=True)cvs = int(round(ADAPTIVE_DP * dpi))lgs = int(round(LEGACY_DP * dpi))# ============ 自适应层 ============- # 变换的全部内容:把源图上那个**外接圆的圆心**(也就是源图中心- # (ccx,ccy))对齐到画布中心,再整体下移 dy —— 那个 dy 就是上面为了- # 让外接圆最小而算出来的量,不在这里用上它就等于白算。- #- # ⚠️ 这里踩过一次:写成 `cvs/2 + dy*scale - (cy+dy)*scale`,数学上- # 化简成 `cvs/2 - cy*scale`,**dy 整个消失了** —— 432 画布上等于把- # 角色上移了 17px,耳朵被顶出可见圆。所以下面把两项分开写。+ # 源图中心对齐画布中心再整体下移 dy。dy 要单独一项写:化简成+ # `cvs/2 - ccy*scale` 它就消失了,角会被顶出可见圆。vis_r = cvs * VISIBLE_FRACTION / 2.0- scale = (vis_r * content) / info["opt"]+ scale = vis_r * content / optn = max(8, int(round(W * scale)))off_x = int(round(cvs / 2.0 - ccx * scale))off_y = int(round(cvs / 2.0 - ccy * scale + dy * scale))fg = Image.new("RGBA", (cvs, cvs), (0, 0, 0, 0))- small = resize_rgba(src, n)- blit(fg, small, off_x, off_y)- bcx, bcy, br = off_x + cx * scale, off_y + cy * scale, r * scale- if args.decor != "none":- fg = rim_tint(fg, RIM_COLOR, br, RIM_OF_R)- fg = fg if args.no_sharpen else sharpen_rgb(fg)- bg_im = backdrop(cvs, bcx, bcy, br, args.decor)- bg_im.save(outdirs[name] / "ic_launcher_background.webp", "WEBP", lossless=True, method=6)- if bdir:- bg_im.save(bdir / f"adaptive-{name}.png")- fg.save(outdirs[name] / "ic_launcher_foreground.webp", "WEBP", lossless=True, method=6)+ blit(fg, resize_rgba(char, n), off_x, off_y)+ fg = sharpen_rgb(fg)+ webp(fg, out / "ic_launcher_foreground.webp")++ bgc = Image.new("RGB", (cvs, cvs), pad)+ blit(bgc, bg.resize((n, n), Image.LANCZOS), off_x, off_y)+ webp(bgc, out / "ic_launcher_background.webp")mono_c = Image.new("L", (cvs, cvs), 0)- blit(mono_c, resize_mask(mono_img, n), off_x, off_y)+ blit(mono_c, mono_img.resize((n, n), Image.BOX), off_x, off_y)mc = np.asarray(mono_c)- Image.fromarray(np.dstack([np.zeros_like(mc)] * 3 + [mc]), "RGBA").save(- outdirs[name] / "ic_launcher_monochrome.webp", "WEBP", lossless=True, method=6)- written += [outdirs[name] / f for f in- ("ic_launcher_background.webp", "ic_launcher_foreground.webp",- "ic_launcher_monochrome.webp")]-- # ============ 传统光栅(单独构建,不从自适应画布缩) ============- char_h = bbox[1] - bbox[0] + 1- char_w = bbox[3] - bbox[2] + 1- lscale = lgs * legacy_content / max(char_h, char_w)+ webp(Image.fromarray(np.dstack([np.zeros_like(mc)] * 3 + [mc]), "RGBA"),+ out / "ic_launcher_monochrome.webp")++ # ============ 传统光栅(单独构建) ============+ lscale = (lgs / 2.0) * legacy_content / optln = max(8, int(round(W * lscale)))- lx = int(round(lgs / 2.0 - (bbox[2] + bbox[3] + 1) / 2.0 * lscale))- ly = int(round(lgs / 2.0 - (bbox[0] + bbox[1] + 1) / 2.0 * lscale))- lsmall = resize_rgba(src, ln)+ lx = int(round(lgs / 2.0 - ccx * lscale))+ ly = int(round(lgs / 2.0 - ccy * lscale + dy * lscale))+ flat = Image.new("RGB", (lgs, lgs), pad)+ blit(flat, bg.resize((ln, ln), Image.LANCZOS), lx, ly)lc = Image.new("RGBA", (lgs, lgs), (0, 0, 0, 0))- blit(lc, lsmall, lx, ly)- if args.decor != "none":- lc = rim_tint(lc, RIM_COLOR, r * lscale, RIM_OF_R)- lc = lc if args.no_sharpen else sharpen_rgb(lc)- flat = backdrop(lgs, lx + cx * lscale, ly + cy * lscale, r * lscale, args.decor)- if bdir:- flat.save(bdir / f"legacy-{name}.png")+ blit(lc, resize_rgba(char, ln), lx, ly)+ lc = sharpen_rgb(lc)flat.paste(lc, (0, 0), lc)- flat.save(outdirs[name] / "ic_launcher.webp", "WEBP", lossless=True, method=6)+ webp(flat, out / "ic_launcher.webp")- # 圆形版:同一个内容,按圆形给 alpha(旧图实测就是满幅圆)yy, xx = np.mgrid[0:lgs, 0:lgs]cc = (lgs - 1) / 2.0- circ = Image.fromarray(- ((np.hypot(xx - cc, yy - cc) <= cc + 0.5) * 255).astype(np.uint8), "L")+ circ = Image.fromarray(((np.hypot(xx - cc, yy - cc) <= cc + 0.5) * 255).astype(np.uint8), "L")rnd = Image.new("RGBA", (lgs, lgs), (0, 0, 0, 0))rnd.paste(flat, (0, 0), circ)- rnd.save(outdirs[name] / "ic_launcher_round.webp", "WEBP", lossless=True, method=6)- written += [outdirs[name] / "ic_launcher.webp", outdirs[name] / "ic_launcher_round.webp"]-- print(f" {name:8s} 画布 {cvs:3d} 传统 {lgs:3d} 球直径 {2*r*scale:5.1f}"- f" ({2*r*scale/cvs*100:4.1f}% 画布) 角色最大半径 "- f"{vis_r*content:5.1f} / 可见 {vis_r:.0f}")-- # 中间产物不留,免得残留的 .png 在某些路径上盖住 .webp- for p in res.glob("mipmap-*/*.png"):- p.unlink()- total = sum(p.stat().st_size for p in written)- print(f"\n共 {len(written)} 个文件,{total/1024:.1f} KiB")+ webp(rnd, out / "ic_launcher_round.webp")++ total += sum((out / f).stat().st_size for f in (+ "ic_launcher.webp", "ic_launcher_round.webp", "ic_launcher_foreground.webp",+ "ic_launcher_background.webp", "ic_launcher_monochrome.webp"))+ print(f" {name:7s} 画布 {cvs:3d} 传统 {lgs:3d} 角色外接圆半径 "+ f"{opt * scale:5.1f} / 可见 {vis_r:.0f}")+ print(f"写入 {5 * len(DENSITIES)} 个文件,共 {total / 1024:.0f}KB")return 0diff --git a/tools/make_social_preview.py b/tools/make_social_preview.pyindex ef02d92..e3ead3f 100644--- a/tools/make_social_preview.py+++ b/tools/make_social_preview.py@@ -1,247 +1,106 @@#!/usr/bin/env python3-"""GitHub 社交预览图(1280×640)、README 封面(1200×630)与方形组织头像(512×512)。+"""README 封面(1200×630)、GitHub 社交预览(1280×640)与方形组织头像(512×512)。-## 为什么不是"截个图标再放大"+素材只有一份:`images/brand/andee-head.png`(白底 + 橙粉光晕 + 蓝色头部)。+头部抠图和光晕补底在 `andee_head.py`,和启动图标共用同一套,所以封面上的角色+和桌面图标是**同一张画**,不是"看起来像"。-图标里那颗球在 `ic_launcher_foreground` 里只有 221px 宽。社交预览要 430px 以上,-直接放大是 2 倍插值 —— 小尺寸下看还行,铺满 1280 宽的卡片就是糊的。+## 构图-但这个仓库的球本来就不是"一张图",是 `tools/ball_shot.mjs` 从实验室页面渲出来的。-所以这里**不放大,重新渲一张大的**:同一个渲染路径、同一个 look、同一份几何,-只是把边长从 432 提到 1000。放大倍数是 0.44 —— 是缩小,不是放大。+ * 底是纯白(源图四角就是 #FDFDFD),角色连同自带的光晕一起贴上去,+ 光晕与白底在边缘处自然融掉 —— 所以不抠光晕,贴整张。+ * 文字深色,左对齐;角色在右。文字右缘到角色**头部**左缘的间距会量出来,+ 小于 40px 就告警(标语长了 20px 悄悄压到头上,只有肉眼看得出)。+ * 头像是圆形裁切(GitHub 组织头像就是圆的):脚本量角色最远点到圆心的+ 距离,越界就告警。-## 素材全部来自仓库自己,没有一个外编+文字用 Chrome 渲 SVG(要 PingFang / SF Pro 之类系统字体,PIL 做不好字距)。- * 球体 `tools/ball_shot.mjs --look cream --mood LISTENING`(图标用的就是这一只:- 奶油身体 + 深色豆豆眼 + 深色描边 + 立耳)- * 星空底 `tools/cosmic_backdrop.py` —— 和启动图标背景层是同一个生成器,- 所以社交预览的底片和图标是同一片星空,不是"看起来像"- * 文案 README.md 自己的句子(tagline 就是文件里那句 h3)--## 两件不猜的事--1. **球体的几何是量出来的。** 球身直径、球心在渲染图里的位置,都从 alpha 通- 道实测(球身最宽行 ±20 行的平均宽度),不是"看着差不多"。落位再由这两个- 数反推,所以换 look、换 size 都不用重调偏移。-2. **文字不许压到球。** 文字层渲完之后扫一遍球体左缘之前的区域,找近白像素,- 报出文字最右缘和到球的距离;越界就打印告警。这条挡的是"标语长了 20px 就悄- 悄压到球上"这类只有肉眼才看得见的错。--## 用法-- python3 tools/make_social_preview.py # 三张全出- python3 tools/make_social_preview.py --ball-src /tmp/ball.png # 复用已渲好的球--需要 Pillow 与 numpy(`cosmic_backdrop` 要 numpy)。球体那一步要 node + 一个-能跑 headless WebGL 的 Chromium —— 见 `tools/ball_shot.mjs` 的文件头。+用法:+ python3 tools/make_social_preview.py"""import argparseimport htmlimport os-import randomimport subprocessimport sysfrom pathlib import Path+import numpy as npfrom PIL import ImageHERE = Path(__file__).resolve().parent-REPO = HERE.parentsys.path.insert(0, str(HERE))-import cosmic_backdrop # noqa: E402+import andee_head as head # noqa: E402+REPO = HERE.parentOUT_DIR = REPO / "images"CHROME = os.environ.get(- "CHROME_PATH",- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",-)-NODE = os.environ.get("NODE", "node")+ "CHROME_PATH", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")-W, H = 1280, 640 # GitHub 社交预览:1280×640 是官方推荐的最优尺寸-COVER = (1200, 630) # README 顶部封面:沿用 OG 图的常规比例+W, H = 1280, 640+COVER = (1200, 630)+AVATAR = 512-# 画布上球体的落位(球身中心)-BALL_X, BALL_Y = 966.0, 340.0-BALL_BODY = 440.0 # 球身显示直径+# 角色整图(含光晕)在 1280×640 画布上的落位:整图边长与中心。+ART_SIDE = 760+ART_CX, ART_CY = 952.0, 322.0+# 头部本身的直径(量出来的 693px)按同比例缩放后的值,用于文字间距自检。+HEAD_W_SRC = 693.0# 文字基线-Y_EYEBROW, Y_TITLE, Y_TAG = 202, 332, 394-Y_RULE, Y_FOOT, Y_FOOT2 = 430, 466, 496--STAR_SEED = cosmic_backdrop.SEED # 和图标底片同一颗种子---# ---------------------------------------------------------------- 球体-def render_ball(tmp: Path, size: int = 1000) -> Path:- """调 tools/ball_shot.mjs 渲一颗透明底的大球。"""- out = tmp / "ball.png"- alpha = tmp / "ball.alpha.png"- if alpha.exists():- return alpha- cmd = [- NODE, str(HERE / "ball_shot.mjs"),- "--look", "cream", "--mood", "LISTENING",- "--size", str(size), "--alpha", "--out", str(out),- ]- r = subprocess.run(cmd, cwd=str(REPO), capture_output=True, text=True, timeout=600)- if not alpha.exists():- print(r.stdout[-1500:], r.stderr[-1500:], sep="\n")- raise SystemExit("球体渲染失败。可以先在别处渲好,再用 --ball-src 传进来。")- return alpha---def ball_geometry(src: Path):- """量球身:用最宽行 ±20 行的平均宽度,消掉单行噪声。返回 (直径, 中心x, 中心y)。"""- im = Image.open(src).convert("RGBA")- px = im.split()[3].load()- w, h = im.size- rows = []- for y in range(h):- xs = [x for x in range(w) if px[x, y] > 8]- if xs:- rows.append((y, min(xs), max(xs), max(xs) - min(xs) + 1))- if not rows:- raise SystemExit("球体源图整张透明,什么也没量到。")- widest = max(rows, key=lambda r: r[3])- near = [r[3] for r in rows if abs(r[0] - widest[0]) <= 20]- dia = sum(near) / len(near)- cx = (widest[1] + widest[2]) / 2.0- return dia, cx, float(widest[0])---def ball_layer(src: Path):- dia, cx, cy = ball_geometry(src)- s = BALL_BODY / dia- im = Image.open(src).convert("RGBA")- side = max(1, int(round(im.size[0] * s)))- im = im.resize((side, side), Image.LANCZOS)- left = int(round(BALL_X - cx * s))- top = int(round(BALL_Y - cy * s))- return im, (left, top), (dia, cx, cy, s)---# ---------------------------------------------------------------- 星空底-def backdrop() -> Image.Image:- """拿图标那块底片的同一个生成器,渲一大张再裁成 16:9。-- 辉光要垫在球正后方,所以在**方形画布**里传球心坐标:裁切掉上半 320px,- 方形坐标里的球心就是 (BALL_X, BALL_Y + 320)。- """- sq = cosmic_backdrop.render(- W,- ball_cx=BALL_X,- ball_cy=BALL_Y + (W - H) / 2.0,- ball_r=BALL_BODY / 2.0,- seed=STAR_SEED,- )- top = int((W - H) / 2)- return sq.crop((0, top, W, top + H)).convert("RGB")-- # 曾经在这里叠过一层"文字侧压暗"(0.45 的软渐变)。撤掉了:实测底片上- # 亮度 >150 的像素有 282 个,但**距文字 8px 以内的只有 2 个**,而且是颗- # 柔和灰星(191),既没压到笔画也不影响阅读。压暗 0.45 换来的是一条肉眼- # 可见的竖直明暗分界,把整片星空的连贯性弄没了 —— 代价远大于收益。---def ball_layer(src: Path, body: float = None, cx: float = None, cy: float = None):- """把球按 `body` 的显示直径摆到 (cx, cy)。默认用横图那套落位参数。"""- body = BALL_BODY if body is None else body- cx = BALL_X if cx is None else cx- cy = BALL_Y if cy is None else cy- dia, scx, scy = ball_geometry(src)- s = body / dia- im = Image.open(src).convert("RGBA")- side = max(1, int(round(im.size[0] * s)))- im = im.resize((side, side), Image.LANCZOS)- left = int(round(cx - scx * s))- top = int(round(cy - scy * s))- return im, (left, top), (dia, scx, scy, s)---# ---------------------------------------------------------------- 方形头像-AVATAR = 512-# 球身占方图边长的比例。上限是被**圆形**裁切卡的:这个角色的耳朵往斜上方伸,-# 从球心到耳尖的距离是球半径的 1.28 倍(实测),所以球半径不能超过 边长/2/1.28。-# 0.68 给圆形裁切留出 33px 余量。-AVATAR_RATIO = 0.68---def make_avatar(tmp: Path, ball_src: Path) -> Path:- c = (AVATAR - 1) / 2.0- body = AVATAR * AVATAR_RATIO- base = cosmic_backdrop.render(- AVATAR, ball_cx=c, ball_cy=c, ball_r=body / 2.0, seed=STAR_SEED- ).convert("RGBA")- layer, pos, _ = ball_layer(ball_src, body=body, cx=c, cy=c)- base.alpha_composite(layer, pos)- final = base.convert("RGB")+Y_EYEBROW, Y_TITLE, Y_TAG = 170, 296, 356+Y_RULE, Y_FOOT = 440, 482- # 自检:角色离圆心最远的那一点在哪。圆形裁切(GitHub 头像就是圆的)的半径- # 是 边长/2,越界就是耳朵被啃掉一角 —— 这类事小尺寸下看不出来。- a = layer.split()[3].load()- lw, lh = layer.size- far = 0.0- for y in range(lh):- for x in range(lw):- if a[x, y] > 8:- d = ((x + pos[0] - c) ** 2 + (y + pos[1] - c) ** 2) ** 0.5- if d > far:- far = d- limit = AVATAR / 2.0- print(f" 角色最远点 {far:.0f}px / 圆形裁切半径 {limit:.0f}px / 余量 {limit - far:.0f}px"- + (" ⚠ 会被裁到" if far > limit - 8 else ""))+INK = "#10172A"+INK_SOFT = "#3B4768"+INK_FAINT = "#6B7794"+ACCENT = "#2F6BEA"++EN = {+ "eyebrow": "ANDROID · AI AGENT",+ "title": "Andee",+ "tagline": ["Turn any Android phone", "into an AI phone."],+ "foot": ["An individual that lives on your phone.", "No root. One APK."],+ "font": "'SF Pro Display','Helvetica Neue',Helvetica,Arial,sans-serif",+}+ZH = {+ "eyebrow": "安卓 · AI 智能体",+ "title": "Andee",+ "tagline": ["把任何一部安卓手机,", "变成 AI 手机。"],+ "foot": ["它不是跑在手机上的工具,而是住在手机里的个体。", "免 root,一个 APK。"],+ "font": "'PingFang SC','Hiragino Sans GB','Heiti SC',sans-serif",+}- OUT_DIR.mkdir(parents=True, exist_ok=True)- out = OUT_DIR / "avatar-org.png"- final.save(out, "PNG", optimize=True)- print(f" -> {out.relative_to(REPO)} {final.size[0]}x{final.size[1]} "- f"{out.stat().st_size / 1024:.0f}KB")- return out---# ---------------------------------------------------------------- 文字层-def _stars_svg():- """文字层自带的一层细星。-- 底片那套星点是按 432px 画布设计的(半径 ~1.1px),在 1280 上放大到 ~3.3px,- 偏大偏疏;这里的细星只负责"近处的小颗粒",和底片的星云叠在一起。- """- rnd = random.Random(STAR_SEED + 7)- parts = []- for _ in range(150):- x, y = rnd.uniform(0, W), rnd.uniform(0, H)- r = rnd.choice([0.4, 0.5, 0.6, 0.7, 0.9, 1.1])- o = rnd.uniform(0.08, 0.55)- if x < 745 and 140 < y < 525: # 文字区压暗,别干扰阅读- o *= 0.45- parts.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r:.2f}" fill="#fff" opacity="{o:.2f}"/>')- return "\n ".join(parts)++def art_layer(side: int):+ """整张角色图(带光晕)缩到 side×side。"""+ im = Image.open(head.SRC).convert("RGB")+ return im.resize((side, side), Image.LANCZOS)def build_svg(copy: dict) -> str:- foot = copy["foot"] if isinstance(copy["foot"], list) else [copy["foot"]]- foot_svg = "\n ".join(- f'<text x="96" y="{Y_FOOT + i * 30}" class="foot" fill="#b3a3d4">{html.escape(l)}</text>'- for i, l in enumerate(foot)- )f = copy["font"]+ tag = "\n ".join(+ f'<text x="96" y="{Y_TAG + i * 44}" class="tag" fill="{INK_SOFT}">{html.escape(l)}</text>'+ for i, l in enumerate(copy["tagline"]))+ foot = "\n ".join(+ f'<text x="96" y="{Y_FOOT + i * 32}" class="foot" fill="{INK_FAINT}">{html.escape(l)}</text>'+ for i, l in enumerate(copy["foot"]))return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}"><defs><style>.eyebrow {{ font-family: {f}; font-size: 18px; font-weight: 600; letter-spacing: 5px; }}- .wordmark {{ font-family: {f}; font-size: 126px; font-weight: 700; letter-spacing: -2.5px; }}- .tag {{ font-family: {f}; font-size: 33px; font-weight: 400; letter-spacing: -0.2px; }}+ .wordmark {{ font-family: {f}; font-size: 130px; font-weight: 700; letter-spacing: -3px; }}+ .tag {{ font-family: {f}; font-size: 33px; font-weight: 500; letter-spacing: -0.2px; }}.foot {{ font-family: {f}; font-size: 22px; font-weight: 400; letter-spacing: 0.1px; }}</style></defs>- <g>- {_stars_svg()}- </g>- <text x="96" y="{Y_EYEBROW}" class="eyebrow" fill="#c9a4ef">{html.escape(copy["eyebrow"])}</text>- <text x="94" y="{Y_TITLE}" class="wordmark" fill="#ffffff">{html.escape(copy["title"])}</text>- <text x="96" y="{Y_TAG}" class="tag" fill="#e2d7f7">{html.escape(copy["tagline"])}</text>- <rect x="96" y="{Y_RULE}" width="88" height="2" fill="#7c58a8"/>- {foot_svg}+ <text x="96" y="{Y_EYEBROW}" class="eyebrow" fill="{ACCENT}">{html.escape(copy["eyebrow"])}</text>+ <text x="92" y="{Y_TITLE}" class="wordmark" fill="{INK}">{html.escape(copy["title"])}</text>+ {tag}+ <rect x="96" y="{Y_RULE}" width="88" height="3" rx="1.5" fill="{ACCENT}"/>+ {foot}</svg>'''@@ -252,77 +111,42 @@ def render_text_layer(svg: str, tmp: Path) -> Path:'<!doctype html><html><head><meta charset="utf-8">''<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}''svg{display:block}</style></head><body>' + svg + "</body></html>",- encoding="utf-8",- )+ encoding="utf-8")shot = tmp / "text.png"+ if shot.exists():+ shot.unlink()subprocess.run([CHROME, "--headless=new", "--no-sandbox", "--disable-dev-shm-usage",- "--disable-gpu", "--hide-scrollbars",- "--default-background-color=00000000",- "--force-device-scale-factor=1",- f"--user-data-dir={tmp}/chrome-profile",+ "--disable-gpu", "--hide-scrollbars", "--default-background-color=00000000",+ "--force-device-scale-factor=1", f"--user-data-dir={tmp}/chrome-profile",f"--screenshot={shot}", f"--window-size={W},{H}", f"file://{page}"],- capture_output=True, text=True, timeout=180, check=False,- )+ capture_output=True, text=True, timeout=180, check=False)if not shot.exists():raise SystemExit("文字层截图失败(Chrome 没起来?)。")return shot-# ---------------------------------------------------------------- 自检-def text_clearance(text_layer: Path):- """文字最右缘,以及它到球体左缘还剩多少。-- 量的是**文字层自己的 alpha**,不是成品图:成品图上有底片的星(其中一批是- 淡紫和淡粉的,亮度能到 240+),拿"近白像素"当判据会被它们骗过去 —— 第一版- 就是这么误报的,把一颗粉星读成了"文字伸到 x=691"。-- 文字层里也有星,但它们都压在 0.25 透明度以下(alpha ≤ 63),文字是 255,- 阈值取 120 就把两者干净地分开了。- """- alpha = Image.open(text_layer).convert("RGBA").split()[3]- ball_left = BALL_X - BALL_BODY / 2.0- x0, x1 = 560, int(ball_left) - 3- y0, y1 = 150, 515 # 落在"文字区压暗"的范围内,避开未压暗的星- band = alpha.crop((x0, y0, x1, y1))- px = band.load()- worst = -1- for y in range(band.height):- for x in range(band.width):- if px[x, y] > 120:- worst = max(worst, x + x0)- return worst, ball_left---# ---------------------------------------------------------------- 出图-EN = {- "eyebrow": "ANDROID · AI AGENT",- "title": "Andee",- "tagline": "Turn any Android phone into an AI phone.",- "foot": "An individual that lives on your phone. No root. One APK.",- "font": "'SF Pro Display','Helvetica Neue',Helvetica,Arial,sans-serif",-}-ZH = {- "eyebrow": "安卓 · AI 智能体",- "title": "Andee",- "tagline": "把任何一部安卓手机,变成 AI 手机。",- "foot": ["它不是跑在手机上的工具,而是住在手机里的个体。", "免 root,一个 APK。"],- "font": "'PingFang SC','Hiragino Sans GB','Heiti SC',sans-serif",-}+def text_right_edge(text_layer: Path) -> int:+ alpha = np.asarray(Image.open(text_layer).convert("RGBA").split()[3])+ cols = np.where((alpha[150:520] > 120).any(axis=0))[0]+ return int(cols.max()) if len(cols) else 0-def compose(copy, name, tmp, ball_src, size=None):- base = backdrop().convert("RGBA")+def compose(copy, name, tmp, size=None):+ base = Image.new("RGB", (W, H), (253, 253, 253)).convert("RGBA")+ art = art_layer(ART_SIDE).convert("RGBA")+ left, top = int(ART_CX - ART_SIDE / 2), int(ART_CY - ART_SIDE / 2)+ base.alpha_composite(art, (left, top)) if left >= 0 and top >= 0 else base.paste(art, (left, top))text_layer = render_text_layer(build_svg(copy), tmp)base.alpha_composite(Image.open(text_layer).convert("RGBA"))- layer, pos, geo = ball_layer(ball_src)- base.alpha_composite(layer, pos)final = base.convert("RGB")- over, ball_left = text_clearance(text_layer)- gap = ball_left - over- print(f" 文字右缘 {over} / 球体左缘 {ball_left:.0f} / 间距 {gap:.0f}px"- + (" ⚠ 太挤" if gap < 20 else ""))+ s = ART_SIDE / 1254.0+ head_left = left + 277 * s+ over = text_right_edge(text_layer)+ gap = head_left - over+ print(f" 文字右缘 {over} / 头部左缘 {head_left:.0f} / 间距 {gap:.0f}px"+ + (" ⚠ 太挤" if gap < 40 else ""))if size and size != (W, H):l, t = (W - size[0]) // 2, (H - size[1]) // 2@@ -330,33 +154,46 @@ def compose(copy, name, tmp, ball_src, size=None):OUT_DIR.mkdir(parents=True, exist_ok=True)out = OUT_DIR / namefinal.save(out, "PNG", optimize=True)- print(f" -> {out.relative_to(REPO)} {final.size[0]}x{final.size[1]} "- f"{out.stat().st_size / 1024:.0f}KB")+ print(f" -> {out.relative_to(REPO)} {final.size[0]}x{final.size[1]} {out.stat().st_size / 1024:.0f}KB")+++def make_avatar():+ """方形头像:角色整图居中,圆形裁切下角(耳朵)不越界。"""+ rgba, alpha, hard, a = head.character_rgba()+ r, dy = head.circumcircle(alpha)+ # 外接圆(相对源图中心,已含最优下移)占圆形裁切半径的比例。+ ratio = 0.80+ scale = (AVATAR / 2.0) * ratio / r+ side = int(round(1254 * scale))+ art = Image.open(head.SRC).convert("RGB").resize((side, side), Image.LANCZOS)+ base = Image.new("RGB", (AVATAR, AVATAR), (253, 253, 253))+ ox = int(round(AVATAR / 2.0 - 626.5 * scale))+ oy = int(round(AVATAR / 2.0 - 626.5 * scale + dy * scale))+ base.paste(art, (ox, oy))+ far = r * scale+ print(f" 角色最远点 {far:.0f}px / 圆形裁切半径 {AVATAR / 2:.0f}px / 余量 {AVATAR / 2 - far:.0f}px")+ out = OUT_DIR / "avatar-org.png"+ base.save(out, "PNG", optimize=True)+ print(f" -> {out.relative_to(REPO)} {AVATAR}x{AVATAR} {out.stat().st_size / 1024:.0f}KB")def main():ap = argparse.ArgumentParser()- ap.add_argument("--ball-src", help="复用已渲好的透明底球体(.alpha.png)")ap.add_argument("--tmp", default="/tmp/andee-social-preview")args = ap.parse_args()-tmp = Path(args.tmp)tmp.mkdir(parents=True, exist_ok=True)- ball_src = Path(args.ball_src) if args.ball_src else render_ball(tmp)- dia, cx, cy = ball_geometry(ball_src)- print(f"球体源图 {ball_src.name}: 球身直径 {dia:.0f}px,中心 ({cx:.0f},{cy:.0f})"- f" -> 显示 {BALL_BODY:.0f}px({BALL_BODY / dia:.2f}x)")print("英文版 1280×640")- compose(EN, "social-preview.png", tmp, ball_src)+ compose(EN, "social-preview.png", tmp)print("中文版 1280×640")- compose(ZH, "social-preview.zh-CN.png", tmp, ball_src)+ compose(ZH, "social-preview.zh-CN.png", tmp)print("README 封面 1200×630(英文)")- compose(EN, "cover.png", tmp, ball_src, size=COVER)+ compose(EN, "cover.png", tmp, size=COVER)print("README 封面 1200×630(中文)")- compose(ZH, "cover.zh-CN.png", tmp, ball_src, size=COVER)+ compose(ZH, "cover.zh-CN.png", tmp, size=COVER)print(f"方形头像 {AVATAR}×{AVATAR}(GitHub 组织头像)")- make_avatar(tmp, ball_src)+ make_avatar()if __name__ == "__main__":