first commit
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot)
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$characterRoot = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin'
|
||||
$partsDirectory = Join-Path $characterRoot 'parts\front-right\v1'
|
||||
$manifestPath = Join-Path $partsDirectory 'parts-manifest.json'
|
||||
$correctionDirectory = Join-Path $characterRoot 'parts\front-right\rig-corrections-v1'
|
||||
$correctionManifestPath = Join-Path $correctionDirectory 'rig-corrections-manifest.json'
|
||||
$referencePath = Join-Path $characterRoot 'reference\xinyin-front-right-assembled-reference-v1.png'
|
||||
$assembledDirectory = Join-Path $characterRoot 'assembled\front-right'
|
||||
$previewDirectory = Join-Path $characterRoot 'previews'
|
||||
$assemblyPath = Join-Path $assembledDirectory 'xinyin-front-right-neutral-assembly-v4.png'
|
||||
$layoutPath = Join-Path $assembledDirectory 'assembly-layout-v4.json'
|
||||
$previewPath = Join-Path $previewDirectory 'xinyin-front-right-assembly-validation-v4.png'
|
||||
New-Item -ItemType Directory -Force -Path $assembledDirectory, $previewDirectory | Out-Null
|
||||
|
||||
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
|
||||
$correctionManifest = Get-Content -LiteralPath $correctionManifestPath -Raw | ConvertFrom-Json
|
||||
$partByName = @{}
|
||||
foreach ($part in $manifest.parts) {
|
||||
$partByName[$part.name] = [pscustomobject]@{
|
||||
ComponentId=$part.componentId; File=$part.file; PartSet='base-v1'
|
||||
AssetPath="assets/images/2d-game-characters/02-xinyin/parts/front-right/v1/$($part.file)"
|
||||
FullPath=(Join-Path $partsDirectory $part.file)
|
||||
PivotX=[double]$part.pivot.outputPixels.x; PivotY=[double]$part.pivot.outputPixels.y
|
||||
}
|
||||
}
|
||||
foreach ($part in $correctionManifest.parts) {
|
||||
$partByName[$part.name] = [pscustomobject]@{
|
||||
ComponentId=$part.componentId; File=$part.file; PartSet='rig-corrections-v1'
|
||||
AssetPath="assets/images/2d-game-characters/02-xinyin/parts/front-right/rig-corrections-v1/$($part.file)"
|
||||
FullPath=(Join-Path $correctionDirectory $part.file)
|
||||
PivotX=[double]$part.rootPivot.outputPixels.x; PivotY=[double]$part.rootPivot.outputPixels.y
|
||||
}
|
||||
}
|
||||
|
||||
# Target coordinates use a 500x760 authoring canvas. X/Y are the desired positions of
|
||||
# each part's manifest pivot. The initial arrangement deliberately uses only one of
|
||||
# several alternate hair/limb pieces so that unused variants stay visible in the report.
|
||||
$layout = @(
|
||||
@{ Name='ponytail-root'; X=215; Y=62; Rotation=0; Scale=.55; Group='base'; Note='三段马尾根部' },
|
||||
@{ Name='ponytail-middle'; X=296; Y=94; Rotation=-12; Scale=.42; Group='base'; Note='三段马尾中段' },
|
||||
@{ Name='ponytail-tip'; X=334; Y=258; Rotation=-6; Scale=.38; Group='base'; Note='三段马尾末端' },
|
||||
@{ Name='coat-panel-01'; X=150; Y=318; Rotation=6; Scale=.92; Group='base'; Note='左外层候选' },
|
||||
@{ Name='coat-panel-02'; X=176; Y=315; Rotation=3; Scale=.88; Group='base'; Note='左后层候选' },
|
||||
@{ Name='coat-panel-03'; X=204; Y=319; Rotation=1; Scale=.88; Group='base'; Note='中左候选' },
|
||||
@{ Name='coat-panel-04'; X=226; Y=320; Rotation=0; Scale=.90; Group='base'; Note='中层候选' },
|
||||
@{ Name='coat-panel-05'; X=245; Y=320; Rotation=0; Scale=.90; Group='base'; Note='中层候选' },
|
||||
@{ Name='coat-panel-06'; X=264; Y=319; Rotation=-1; Scale=.88; Group='base'; Note='中右候选' },
|
||||
@{ Name='coat-panel-07'; X=286; Y=315; Rotation=-3; Scale=.88; Group='base'; Note='右后层候选' },
|
||||
@{ Name='coat-panel-08'; X=316; Y=318; Rotation=-6; Scale=.92; Group='base'; Note='右外层候选' },
|
||||
@{ Name='thigh-a'; X=195; Y=350; Rotation=7; Scale=.92; Group='base'; Note='画面左腿候选' },
|
||||
@{ Name='shin-boot-a'; X=178; Y=480; Rotation=9; Scale=.88; Group='base'; Note='画面左小腿候选' },
|
||||
@{ Name='thigh-b'; X=244; Y=350; Rotation=-5; Scale=.92; Group='base'; Note='画面右腿候选' },
|
||||
@{ Name='shin-boot-b'; X=252; Y=487; Rotation=-3; Scale=.88; Group='base'; Note='画面右小腿候选' },
|
||||
@{ Name='pelvis'; X=220; Y=350; Rotation=0; Scale=.88; Group='base'; Note='主根候选' },
|
||||
@{ Name='torso-upper'; X=213; Y=318; Rotation=0; Scale=.92; Group='base'; Note='躯干' },
|
||||
@{ Name='upper-arm-a'; X=146; Y=214; Rotation=10; Scale=.40; Group='base'; Note='独立上臂 A,肩到肘' },
|
||||
@{ Name='forearm-a'; X=130; Y=307; Rotation=156; Scale=.38; Group='base'; Note='独立前臂 A,肘到腕' },
|
||||
@{ Name='hand-fan-grip'; X=89; Y=214; Rotation=-8; Scale=.38; Group='base'; Note='独立持扇手' },
|
||||
@{ Name='upper-arm-b'; X=276; Y=214; Rotation=-8; Scale=.40; Group='base'; Note='独立上臂 B,肩到肘' },
|
||||
@{ Name='forearm-b'; X=289; Y=309; Rotation=-5; Scale=.30; Group='base'; Note='独立前臂 B,肘到腕' },
|
||||
@{ Name='hand-relaxed-b'; X=296; Y=389; Rotation=-5; Scale=.25; Group='base'; Note='独立放松手 B' },
|
||||
@{ Name='waist-guard'; X=217; Y=298; Rotation=0; Scale=.72; Group='overlay'; Note='覆盖骨盆和腿根' },
|
||||
@{ Name='front-drape'; X=203; Y=305; Rotation=2; Scale=.75; Group='overlay'; Note='腰前垂布' },
|
||||
@{ Name='waist-pouch'; X=270; Y=312; Rotation=-2; Scale=.58; Group='overlay'; Note='画面右侧腰包,v2 缩小' },
|
||||
@{ Name='neck'; X=207; Y=187; Rotation=0; Scale=.90; Group='overlay'; Note='颈部' },
|
||||
@{ Name='head-face'; X=205; Y=194; Rotation=0; Scale=1.00; Group='overlay'; Note='面部' },
|
||||
@{ Name='hair-front'; X=204; Y=76; Rotation=0; Scale=1.00; Group='overlay'; Note='前发覆盖面部' },
|
||||
@{ Name='shoulder-armor-a'; X=146; Y=207; Rotation=8; Scale=.65; Group='overlay'; Note='固定于躯干的独立肩甲 A' },
|
||||
@{ Name='shoulder-armor-b'; X=276; Y=207; Rotation=-8; Scale=.65; Group='overlay'; Note='固定于躯干的独立肩甲 B' }
|
||||
)
|
||||
|
||||
function Draw-Part {
|
||||
param(
|
||||
[Drawing.Graphics]$Graphics,
|
||||
[Drawing.Image]$Image,
|
||||
[double]$PivotX,
|
||||
[double]$PivotY,
|
||||
[double]$TargetX,
|
||||
[double]$TargetY,
|
||||
[double]$Rotation,
|
||||
[double]$Scale
|
||||
)
|
||||
$state = $Graphics.Save()
|
||||
$Graphics.TranslateTransform([single]$TargetX, [single]$TargetY)
|
||||
$Graphics.RotateTransform([single]$Rotation)
|
||||
$Graphics.ScaleTransform([single]$Scale, [single]$Scale)
|
||||
$Graphics.DrawImageUnscaled($Image, [int][Math]::Round(-$PivotX), [int][Math]::Round(-$PivotY))
|
||||
$Graphics.Restore($state)
|
||||
}
|
||||
|
||||
$images = @{}
|
||||
$assembly = [Drawing.Bitmap]::new(500, 760, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$assemblyGraphics = [Drawing.Graphics]::FromImage($assembly)
|
||||
$assemblyGraphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$assemblyGraphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$assemblyGraphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$assemblyGraphics.Clear([Drawing.Color]::Transparent)
|
||||
|
||||
try {
|
||||
foreach ($item in $layout) {
|
||||
$part = $partByName[$item.Name]
|
||||
if ($null -eq $part) { throw "Part not found in manifest: $($item.Name)" }
|
||||
if (-not $images.ContainsKey($item.Name)) {
|
||||
$images[$item.Name] = [Drawing.Bitmap]::new($part.FullPath)
|
||||
}
|
||||
Draw-Part -Graphics $assemblyGraphics -Image $images[$item.Name] `
|
||||
-PivotX $part.PivotX -PivotY $part.PivotY `
|
||||
-TargetX $item.X -TargetY $item.Y -Rotation $item.Rotation -Scale $item.Scale
|
||||
}
|
||||
$assembly.Save($assemblyPath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$layoutRecords = foreach ($item in $layout) {
|
||||
$part = $partByName[$item.Name]
|
||||
[ordered]@{
|
||||
part = $item.Name
|
||||
componentId = $part.ComponentId
|
||||
partSet = $part.PartSet
|
||||
file = $part.AssetPath
|
||||
targetPivot = [ordered]@{ x=$item.X; y=$item.Y }
|
||||
rotationDegrees = $item.Rotation
|
||||
scale = $item.Scale
|
||||
group = $item.Group
|
||||
note = $item.Note
|
||||
}
|
||||
}
|
||||
[ordered]@{
|
||||
characterId = '02-xinyin'
|
||||
direction = 'front-right'
|
||||
version = 4
|
||||
status = 'art-assembly-validated'
|
||||
canvas = [ordered]@{ width=500; height=760; origin='top-left'; units='pixels' }
|
||||
sourceManifests = @(
|
||||
'assets/images/2d-game-characters/02-xinyin/parts/front-right/v1/parts-manifest.json',
|
||||
'assets/images/2d-game-characters/02-xinyin/parts/front-right/rig-corrections-v1/rig-corrections-manifest.json'
|
||||
)
|
||||
warnings = @(
|
||||
'This is an art-side assembly validation, not an engine rig.',
|
||||
'A/B limb ownership and cloth ordering remain provisional until animation testing.',
|
||||
'C01 is excluded because two alternate ponytail masses are connected by a thin strand.',
|
||||
'C09 is excluded because the front-hair part already carries the visible long ornament.',
|
||||
'C15/C17 and C18/C20 are replaced by independent arm, forearm, and hand correction parts.',
|
||||
'C28/C29 are restored as torso-mounted shoulder armor because corrected upper arms do not contain armor.'
|
||||
)
|
||||
items = $layoutRecords
|
||||
} | ConvertTo-Json -Depth 7 | Set-Content -LiteralPath $layoutPath -Encoding utf8
|
||||
|
||||
$board = [Drawing.Bitmap]::new(1800, 980, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [Drawing.Graphics]::FromImage($board)
|
||||
$g.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$g.Clear([Drawing.Color]::FromArgb(255, 17, 21, 30))
|
||||
$titleBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 240, 244, 252))
|
||||
$mutedBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 150, 169, 198))
|
||||
$panelBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 24, 30, 42))
|
||||
$panelPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 65, 82, 112), 2)
|
||||
$jointPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 255, 94, 122), 3)
|
||||
$bonePen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(210, 79, 211, 255), 4)
|
||||
$fontTitle = [Drawing.Font]::new('Segoe UI Semibold', 27)
|
||||
$fontPanel = [Drawing.Font]::new('Segoe UI Semibold', 18)
|
||||
$fontText = [Drawing.Font]::new('Segoe UI', 13)
|
||||
$g.DrawString('XIN YIN — FRONT-RIGHT ASSEMBLY VALIDATION V4', $fontTitle, $titleBrush, 42, 26)
|
||||
$g.DrawString('reference / extracted-part assembly / pivot and hierarchy check', $fontText, $mutedBrush, 45, 68)
|
||||
|
||||
$panelXs = @(42, 624, 1206)
|
||||
foreach ($panelX in $panelXs) {
|
||||
$g.FillRectangle($panelBrush, $panelX, 112, 552, 820)
|
||||
$g.DrawRectangle($panelPen, $panelX, 112, 552, 820)
|
||||
}
|
||||
$g.DrawString('A ASSEMBLED REFERENCE', $fontPanel, $titleBrush, 62, 132)
|
||||
$g.DrawString('B PARTS RECONSTRUCTION', $fontPanel, $titleBrush, 644, 132)
|
||||
$g.DrawString('C PIVOT / HIERARCHY', $fontPanel, $titleBrush, 1226, 132)
|
||||
|
||||
$reference = [Drawing.Bitmap]::new($referencePath)
|
||||
$g.DrawImage($reference, 112, 186, 414, 716)
|
||||
$g.DrawImage($assembly, 650, 172, 500, 760)
|
||||
$g.DrawImage($assembly, 1232, 172, 500, 760)
|
||||
|
||||
$bones = @(
|
||||
@((215,62),(296,94),(334,258),(347,388)),
|
||||
@((205,194),(207,187),(213,260),(220,350)),
|
||||
@((213,220),(146,214),(130,307),(89,214)),
|
||||
@((213,220),(276,214),(289,309),(296,389)),
|
||||
@((220,350),(195,350),(178,480),(160,685)),
|
||||
@((220,350),(244,350),(252,487),(260,700))
|
||||
)
|
||||
foreach ($chain in $bones) {
|
||||
for ($i = 0; $i -lt $chain.Count - 1; $i++) {
|
||||
$x1 = 1232 + $chain[$i][0]
|
||||
$y1 = 172 + $chain[$i][1]
|
||||
$x2 = 1232 + $chain[$i + 1][0]
|
||||
$y2 = 172 + $chain[$i + 1][1]
|
||||
$g.DrawLine($bonePen, $x1, $y1, $x2, $y2)
|
||||
}
|
||||
foreach ($point in $chain) {
|
||||
$g.DrawEllipse($jointPen, 1232 + $point[0] - 6, 172 + $point[1] - 6, 12, 12)
|
||||
}
|
||||
}
|
||||
|
||||
$g.DrawString('Corrected chain:', $fontText, $titleBrush, 1240, 862)
|
||||
$g.DrawString('separate upper arms / forearms / hands / three-part ponytail', $fontText, $mutedBrush, 1240, 888)
|
||||
$g.DrawString('C28/C29 restored as torso-mounted armor', $fontText, $mutedBrush, 1240, 912)
|
||||
|
||||
$board.Save($previewPath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
$reference.Dispose()
|
||||
$fontText.Dispose(); $fontPanel.Dispose(); $fontTitle.Dispose()
|
||||
$bonePen.Dispose(); $jointPen.Dispose(); $panelPen.Dispose()
|
||||
$panelBrush.Dispose(); $mutedBrush.Dispose(); $titleBrush.Dispose()
|
||||
$g.Dispose(); $board.Dispose()
|
||||
}
|
||||
finally {
|
||||
foreach ($image in $images.Values) { $image.Dispose() }
|
||||
$assemblyGraphics.Dispose()
|
||||
$assembly.Dispose()
|
||||
}
|
||||
|
||||
Write-Output $assemblyPath
|
||||
Write-Output $layoutPath
|
||||
Write-Output $previewPath
|
||||
@@ -0,0 +1,327 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot)
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$characterRoot = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin'
|
||||
$partsDirectory = Join-Path $characterRoot 'parts\front-right\v1'
|
||||
$partsManifestPath = Join-Path $partsDirectory 'parts-manifest.json'
|
||||
$correctionDirectory = Join-Path $characterRoot 'parts\front-right\rig-corrections-v1'
|
||||
$correctionManifestPath = Join-Path $correctionDirectory 'rig-corrections-manifest.json'
|
||||
$layoutPath = Join-Path $characterRoot 'assembled\front-right\assembly-layout-v4.json'
|
||||
$outputDirectory = Join-Path $characterRoot 'motion\front-right\v3'
|
||||
$previewPath = Join-Path $characterRoot 'previews\xinyin-front-right-motion-validation-v3.png'
|
||||
$motionManifestPath = Join-Path $outputDirectory 'motion-manifest.json'
|
||||
New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null
|
||||
|
||||
$partsManifest = Get-Content -LiteralPath $partsManifestPath -Raw | ConvertFrom-Json
|
||||
$correctionManifest = Get-Content -LiteralPath $correctionManifestPath -Raw | ConvertFrom-Json
|
||||
$baseLayout = Get-Content -LiteralPath $layoutPath -Raw | ConvertFrom-Json
|
||||
$partByName = @{}
|
||||
foreach ($part in $partsManifest.parts) {
|
||||
$partByName[$part.name] = [pscustomobject]@{
|
||||
FullPath=(Join-Path $partsDirectory $part.file)
|
||||
PivotX=[double]$part.pivot.outputPixels.x; PivotY=[double]$part.pivot.outputPixels.y
|
||||
}
|
||||
}
|
||||
foreach ($part in $correctionManifest.parts) {
|
||||
$partByName[$part.name] = [pscustomobject]@{
|
||||
FullPath=(Join-Path $correctionDirectory $part.file)
|
||||
PivotX=[double]$part.rootPivot.outputPixels.x; PivotY=[double]$part.rootPivot.outputPixels.y
|
||||
}
|
||||
}
|
||||
|
||||
$upperBody = @(
|
||||
'torso-upper','neck','head-face','hair-front','ponytail-root','ponytail-middle','ponytail-tip',
|
||||
'upper-arm-a','forearm-a','hand-fan-grip','upper-arm-b','forearm-b','hand-relaxed-b',
|
||||
'shoulder-armor-a','shoulder-armor-b'
|
||||
)
|
||||
|
||||
$frames = @(
|
||||
[ordered]@{
|
||||
Name='idle-inhale'; Label='IDLE · INHALE'; DurationMs=420
|
||||
UpperBodyY=-3
|
||||
Overrides=@{
|
||||
'torso-upper'=@{ Y=315; Scale=.94 }
|
||||
'head-face'=@{ Y=191 }
|
||||
'hair-front'=@{ Y=73 }
|
||||
'ponytail-root'=@{ Y=59; Rotation=-1 }
|
||||
'ponytail-middle'=@{ Y=91; Rotation=-13 }
|
||||
'ponytail-tip'=@{ Y=254; Rotation=-7 }
|
||||
'waist-guard'=@{ Y=296; Scale=.73 }
|
||||
'front-drape'=@{ Y=303; Rotation=3 }
|
||||
'coat-panel-01'=@{ Rotation=7 }
|
||||
'coat-panel-08'=@{ Rotation=-7 }
|
||||
}
|
||||
Joints=@{ Shoulder=@(146,211); Elbow=@(130,304); Hand=@(89,211) }
|
||||
Note='胸腔上提;头、肩与持械手同步,后发轻微滞后。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='idle-neutral'; Label='IDLE · NEUTRAL'; DurationMs=260
|
||||
UpperBodyY=0; Overrides=@{}
|
||||
Joints=@{ Shoulder=@(146,214); Elbow=@(130,307); Hand=@(89,214) }
|
||||
Note='装配 v2 中性基准。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='idle-exhale'; Label='IDLE · EXHALE'; DurationMs=420
|
||||
UpperBodyY=3
|
||||
Overrides=@{
|
||||
'torso-upper'=@{ Y=321; Scale=.90 }
|
||||
'head-face'=@{ Y=197 }
|
||||
'hair-front'=@{ Y=79 }
|
||||
'ponytail-root'=@{ Y=65; Rotation=1 }
|
||||
'ponytail-middle'=@{ Y=99; Rotation=-10 }
|
||||
'ponytail-tip'=@{ Y=264; Rotation=-4 }
|
||||
'waist-guard'=@{ Y=301; Scale=.71 }
|
||||
'front-drape'=@{ Y=308; Rotation=1 }
|
||||
'coat-panel-01'=@{ Rotation=5 }
|
||||
'coat-panel-08'=@{ Rotation=-5 }
|
||||
}
|
||||
Joints=@{ Shoulder=@(146,217); Elbow=@(130,310); Hand=@(89,217) }
|
||||
Note='胸腔回落;发尾比头部多下沉 2~3 px。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='throw-ready'; Label='THROW · READY'; DurationMs=150
|
||||
UpperBodyY=1
|
||||
Overrides=@{
|
||||
'pelvis'=@{ Y=353 }
|
||||
'torso-upper'=@{ Y=320; Rotation=1 }
|
||||
'waist-guard'=@{ Y=301 }
|
||||
'front-drape'=@{ Y=308 }
|
||||
'thigh-a'=@{ Y=353; Rotation=9 }
|
||||
'thigh-b'=@{ Y=353; Rotation=-7 }
|
||||
}
|
||||
Joints=@{ Shoulder=@(146,215); Elbow=@(130,308); Hand=@(89,215) }
|
||||
Note='髋部下沉 3 px,形成动作预备。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='throw-windup'; Label='THROW · WINDUP'; DurationMs=110
|
||||
UpperBodyY=0
|
||||
Overrides=@{
|
||||
'torso-upper'=@{ Rotation=3 }
|
||||
'head-face'=@{ Rotation=1 }
|
||||
'hair-front'=@{ Rotation=1 }
|
||||
'ponytail-root'=@{ Rotation=2 }
|
||||
'ponytail-middle'=@{ Rotation=-8 }
|
||||
'ponytail-tip'=@{ Rotation=-1 }
|
||||
'upper-arm-a'=@{ Rotation=8 }
|
||||
'forearm-a'=@{ X=133; Y=305; Rotation=180 }
|
||||
'hand-fan-grip'=@{ X=133; Y=202; Rotation=-15; Scale=.36 }
|
||||
'shoulder-armor-a'=@{ Rotation=2 }
|
||||
'front-drape'=@{ Rotation=-2 }
|
||||
'coat-panel-01'=@{ Rotation=3 }
|
||||
'coat-panel-08'=@{ Rotation=-9 }
|
||||
}
|
||||
Joints=@{ Shoulder=@(146,214); Elbow=@(133,305); Hand=@(133,202) }
|
||||
Note='前臂回收到面部外侧,武器不遮挡眼睛;马尾与衣摆保持惯性。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='throw-release'; Label='THROW · RELEASE'; DurationMs=90
|
||||
UpperBodyY=0
|
||||
Overrides=@{
|
||||
'torso-upper'=@{ Rotation=-5 }
|
||||
'head-face'=@{ Rotation=-2 }
|
||||
'hair-front'=@{ Rotation=-2 }
|
||||
'ponytail-root'=@{ Rotation=4; X=218 }
|
||||
'ponytail-middle'=@{ Rotation=-2; X=302 }
|
||||
'ponytail-tip'=@{ Rotation=8; X=342 }
|
||||
'upper-arm-a'=@{ Rotation=65 }
|
||||
'forearm-a'=@{ X=62; Y=252; Rotation=95; Scale=.30 }
|
||||
'shoulder-armor-a'=@{ Rotation=8 }
|
||||
'front-drape'=@{ Rotation=7; X=207 }
|
||||
'coat-panel-01'=@{ Rotation=11 }
|
||||
'coat-panel-02'=@{ Rotation=7 }
|
||||
'coat-panel-07'=@{ Rotation=1 }
|
||||
'coat-panel-08'=@{ Rotation=-2 }
|
||||
}
|
||||
Hidden=@('hand-fan-grip')
|
||||
Extras=@(
|
||||
@{ Name='hand-throw-open'; X=-12; Y=244; Rotation=88; Scale=.30 },
|
||||
@{ Name='weapon-fan-open'; X=-38; Y=220; Rotation=80; Scale=.52 }
|
||||
)
|
||||
Joints=@{ Shoulder=@(146,214); Elbow=@(62,252); Hand=@(-12,244) }
|
||||
Note='肩肘形成清楚的左向伸展;武器进入脱手位置。'
|
||||
},
|
||||
[ordered]@{
|
||||
Name='throw-recover'; Label='THROW · RECOVER'; DurationMs=180
|
||||
UpperBodyY=1
|
||||
Overrides=@{
|
||||
'torso-upper'=@{ Rotation=1; Y=319 }
|
||||
'head-face'=@{ Rotation=1; Y=195 }
|
||||
'hair-front'=@{ Rotation=1; Y=77 }
|
||||
'ponytail-root'=@{ Rotation=-3; Y=64 }
|
||||
'ponytail-middle'=@{ Rotation=-16; Y=97 }
|
||||
'ponytail-tip'=@{ Rotation=-12; Y=262 }
|
||||
'upper-arm-a'=@{ Rotation=26 }
|
||||
'forearm-a'=@{ X=106; Y=290; Rotation=170; Scale=.34 }
|
||||
'hand-fan-grip'=@{ X=88; Y=195; Rotation=-10; Scale=.36 }
|
||||
'shoulder-armor-a'=@{ Rotation=10 }
|
||||
'front-drape'=@{ Rotation=-3 }
|
||||
'coat-panel-01'=@{ Rotation=2 }
|
||||
'coat-panel-08'=@{ Rotation=-10 }
|
||||
}
|
||||
Joints=@{ Shoulder=@(146,215); Elbow=@(106,290); Hand=@(88,195) }
|
||||
Note='手臂回收,软性部件反向摆动并准备回到中性。'
|
||||
}
|
||||
)
|
||||
|
||||
function Copy-Transform {
|
||||
param($Item)
|
||||
return [ordered]@{
|
||||
Name=[string]$Item.part
|
||||
X=[double]$Item.targetPivot.x
|
||||
Y=[double]$Item.targetPivot.y
|
||||
Rotation=[double]$Item.rotationDegrees
|
||||
Scale=[double]$Item.scale
|
||||
Visible=$true
|
||||
}
|
||||
}
|
||||
|
||||
function Resolve-FrameLayout {
|
||||
param($Frame)
|
||||
$result = @()
|
||||
$hiddenParts = @($Frame.Hidden)
|
||||
foreach ($item in $baseLayout.items) {
|
||||
$transform = Copy-Transform $item
|
||||
if ($transform.Name -in $upperBody) { $transform.Y += [double]$Frame.UpperBodyY }
|
||||
if ($Frame.Overrides.ContainsKey($transform.Name)) {
|
||||
$override = $Frame.Overrides[$transform.Name]
|
||||
foreach ($key in $override.Keys) { $transform[$key] = $override[$key] }
|
||||
}
|
||||
if ($transform.Name -in $hiddenParts) { $transform.Visible = $false }
|
||||
$transform.X += 50
|
||||
$result += $transform
|
||||
}
|
||||
foreach ($extra in @($Frame.Extras)) {
|
||||
if ($null -eq $extra) { continue }
|
||||
$result += [ordered]@{
|
||||
Name=[string]$extra.Name; X=[double]$extra.X+50; Y=[double]$extra.Y
|
||||
Rotation=[double]$extra.Rotation; Scale=[double]$extra.Scale; Visible=$true
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
function Draw-Part {
|
||||
param(
|
||||
[Drawing.Graphics]$Graphics, [Drawing.Image]$Image,
|
||||
[double]$PivotX, [double]$PivotY,
|
||||
[double]$TargetX, [double]$TargetY,
|
||||
[double]$Rotation, [double]$Scale
|
||||
)
|
||||
$state = $Graphics.Save()
|
||||
$Graphics.TranslateTransform([single]$TargetX, [single]$TargetY)
|
||||
$Graphics.RotateTransform([single]$Rotation)
|
||||
$Graphics.ScaleTransform([single]$Scale, [single]$Scale)
|
||||
$Graphics.DrawImageUnscaled($Image, [int][Math]::Round(-$PivotX), [int][Math]::Round(-$PivotY))
|
||||
$Graphics.Restore($state)
|
||||
}
|
||||
|
||||
$images = @{}
|
||||
$renderedFrames = @()
|
||||
$manifestFrames = @()
|
||||
try {
|
||||
foreach ($frame in $frames) {
|
||||
$resolved = Resolve-FrameLayout $frame
|
||||
$canvas = [Drawing.Bitmap]::new(600, 760, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [Drawing.Graphics]::FromImage($canvas)
|
||||
$graphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$graphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.Clear([Drawing.Color]::Transparent)
|
||||
|
||||
foreach ($transform in $resolved) {
|
||||
if (-not $transform.Visible) { continue }
|
||||
$part = $partByName[$transform.Name]
|
||||
if (-not $images.ContainsKey($transform.Name)) {
|
||||
$images[$transform.Name] = [Drawing.Bitmap]::new($part.FullPath)
|
||||
}
|
||||
Draw-Part -Graphics $graphics -Image $images[$transform.Name] `
|
||||
-PivotX $part.PivotX -PivotY $part.PivotY `
|
||||
-TargetX $transform.X -TargetY $transform.Y -Rotation $transform.Rotation -Scale $transform.Scale
|
||||
}
|
||||
$fileName = "$($frame.Name).png"
|
||||
$filePath = Join-Path $outputDirectory $fileName
|
||||
$canvas.Save($filePath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
$graphics.Dispose()
|
||||
$renderedFrames += [ordered]@{ Definition=$frame; Image=$canvas; Layout=$resolved; File=$fileName }
|
||||
$manifestFrames += [ordered]@{
|
||||
name=$frame.Name; label=$frame.Label; file=$fileName; durationMs=$frame.DurationMs
|
||||
note=$frame.Note; joints=$frame.Joints; transforms=$resolved
|
||||
}
|
||||
}
|
||||
|
||||
[ordered]@{
|
||||
characterId='02-xinyin'
|
||||
direction='front-right'
|
||||
version=3
|
||||
status='art-motion-validation'
|
||||
canvas=[ordered]@{ width=600; height=760; origin='top-left'; units='pixels'; assemblyOffsetX=50 }
|
||||
baseLayout='assets/images/2d-game-characters/02-xinyin/assembled/front-right/assembly-layout-v4.json'
|
||||
sequence=@('idle-inhale','idle-neutral','idle-exhale','idle-neutral','throw-ready','throw-windup','throw-release','throw-recover','idle-neutral')
|
||||
loopNotes=[ordered]@{ idle='inhale → neutral → exhale → neutral'; throw='ready → windup → release → recover' }
|
||||
frames=$manifestFrames
|
||||
} | ConvertTo-Json -Depth 9 | Set-Content -LiteralPath $motionManifestPath -Encoding utf8
|
||||
|
||||
$board = [Drawing.Bitmap]::new(2100, 1390, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [Drawing.Graphics]::FromImage($board)
|
||||
$g.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$g.Clear([Drawing.Color]::FromArgb(255, 16, 20, 29))
|
||||
$titleBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 241, 245, 252))
|
||||
$mutedBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 151, 171, 201))
|
||||
$panelBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 24, 30, 42))
|
||||
$panelPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 65, 82, 112), 2)
|
||||
$bonePen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(230, 71, 210, 255), 4)
|
||||
$jointPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 255, 86, 116), 3)
|
||||
$fontTitle = [Drawing.Font]::new('Segoe UI Semibold', 28)
|
||||
$fontLabel = [Drawing.Font]::new('Segoe UI Semibold', 16)
|
||||
$fontText = [Drawing.Font]::new('Segoe UI', 11)
|
||||
$g.DrawString('XIN YIN — FRONT-RIGHT MOTION VALIDATION V3', $fontTitle, $titleBrush, 48, 28)
|
||||
$g.DrawString('idle breathing + throw joint-range test | cyan: arm chain | red: pivots', $fontText, $mutedBrush, 51, 73)
|
||||
|
||||
$cellWidth=490; $cellHeight=590; $startX=45; $startY=112; $gapX=20; $gapY=28; $scale=.62
|
||||
for ($i=0; $i -lt $renderedFrames.Count; $i++) {
|
||||
$row = [Math]::Floor($i / 4); $col = $i % 4
|
||||
$x = $startX + $col * ($cellWidth + $gapX)
|
||||
$y = $startY + $row * ($cellHeight + $gapY)
|
||||
$g.FillRectangle($panelBrush, $x, $y, $cellWidth, $cellHeight)
|
||||
$g.DrawRectangle($panelPen, $x, $y, $cellWidth, $cellHeight)
|
||||
$g.DrawString($renderedFrames[$i].Definition.Label, $fontLabel, $titleBrush, $x+18, $y+14)
|
||||
$g.DrawString("$($renderedFrames[$i].Definition.DurationMs) ms", $fontText, $mutedBrush, $x+18, $y+43)
|
||||
$drawX = $x + [int](($cellWidth - 600*$scale)/2)
|
||||
$drawY = $y + 65
|
||||
$g.DrawImage($renderedFrames[$i].Image, $drawX, $drawY, [int](600*$scale), [int](760*$scale))
|
||||
|
||||
$joints = $renderedFrames[$i].Definition.Joints
|
||||
$points = @($joints.Shoulder,$joints.Elbow,$joints.Hand)
|
||||
for ($p=0; $p -lt 2; $p++) {
|
||||
$g.DrawLine($bonePen,
|
||||
$drawX + [single](($points[$p][0]+50)*$scale), $drawY + [single]($points[$p][1]*$scale),
|
||||
$drawX + [single](($points[$p+1][0]+50)*$scale), $drawY + [single]($points[$p+1][1]*$scale))
|
||||
}
|
||||
foreach ($point in $points) {
|
||||
$px=$drawX+[single](($point[0]+50)*$scale); $py=$drawY+[single]($point[1]*$scale)
|
||||
$g.DrawEllipse($jointPen,$px-5,$py-5,10,10)
|
||||
}
|
||||
$g.DrawString($renderedFrames[$i].Definition.Note, $fontText, $mutedBrush, [Drawing.RectangleF]::new($x+16,$y+542,$cellWidth-32,40))
|
||||
}
|
||||
|
||||
$g.DrawString('Validation target: silhouette stability, shoulder/elbow overlap, hair and coat secondary motion. No VFX or engine interpolation.', $fontText, $mutedBrush, 48, 1354)
|
||||
$board.Save($previewPath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
$fontText.Dispose(); $fontLabel.Dispose(); $fontTitle.Dispose()
|
||||
$jointPen.Dispose(); $bonePen.Dispose(); $panelPen.Dispose()
|
||||
$panelBrush.Dispose(); $mutedBrush.Dispose(); $titleBrush.Dispose()
|
||||
$g.Dispose(); $board.Dispose()
|
||||
}
|
||||
finally {
|
||||
foreach ($frame in $renderedFrames) { if ($null -ne $frame.Image) { $frame.Image.Dispose() } }
|
||||
foreach ($image in $images.Values) { $image.Dispose() }
|
||||
}
|
||||
|
||||
Write-Output "Rendered $($frames.Count) motion keyframes."
|
||||
Write-Output $outputDirectory
|
||||
Write-Output $motionManifestPath
|
||||
Write-Output $previewPath
|
||||
@@ -0,0 +1,269 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot),
|
||||
[ValidateSet('p0', 'p1')]
|
||||
[string]$Set = 'p0',
|
||||
[ValidateSet('v1', 'v2')]
|
||||
[string]$Variant = 'v1'
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$helperSource = @'
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
|
||||
public static class SpriteCropper
|
||||
{
|
||||
private static bool IsBackgroundLike(Color c)
|
||||
{
|
||||
int max = Math.Max(c.R, Math.Max(c.G, c.B));
|
||||
int min = Math.Min(c.R, Math.Min(c.G, c.B));
|
||||
return c.A > 0 && max > 165 && (max - min) < 42;
|
||||
}
|
||||
|
||||
public static Bitmap Extract(string path, Rectangle crop)
|
||||
{
|
||||
using (var source = new Bitmap(path))
|
||||
{
|
||||
var clipped = Rectangle.Intersect(crop, new Rectangle(0, 0, source.Width, source.Height));
|
||||
var image = new Bitmap(clipped.Width, clipped.Height, PixelFormat.Format32bppArgb);
|
||||
using (var g = Graphics.FromImage(image))
|
||||
{
|
||||
g.DrawImage(source, new Rectangle(0, 0, image.Width, image.Height), clipped, GraphicsUnit.Pixel);
|
||||
}
|
||||
|
||||
int width = image.Width;
|
||||
int height = image.Height;
|
||||
var visited = new bool[width * height];
|
||||
var queue = new int[width * height];
|
||||
int queueHead = 0;
|
||||
int queueTail = 0;
|
||||
|
||||
Action<int, int> seed = (x, y) =>
|
||||
{
|
||||
int index = y * width + x;
|
||||
if (!visited[index] && IsBackgroundLike(image.GetPixel(x, y)))
|
||||
{
|
||||
visited[index] = true;
|
||||
queue[queueTail++] = index;
|
||||
}
|
||||
};
|
||||
|
||||
for (int x = 0; x < width; x++) { seed(x, 0); seed(x, height - 1); }
|
||||
for (int y = 0; y < height; y++) { seed(0, y); seed(width - 1, y); }
|
||||
|
||||
int[] dx = { 1, -1, 0, 0 };
|
||||
int[] dy = { 0, 0, 1, -1 };
|
||||
while (queueHead < queueTail)
|
||||
{
|
||||
int index = queue[queueHead++];
|
||||
int x = index % width;
|
||||
int y = index / width;
|
||||
image.SetPixel(x, y, Color.Transparent);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
int nx = x + dx[i];
|
||||
int ny = y + dy[i];
|
||||
if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
|
||||
int next = ny * width + nx;
|
||||
if (!visited[next] && IsBackgroundLike(image.GetPixel(nx, ny)))
|
||||
{
|
||||
visited[next] = true;
|
||||
queue[queueTail++] = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int minX = width, minY = height, maxX = -1, maxY = -1;
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
if (image.GetPixel(x, y).A < 16) continue;
|
||||
minX = Math.Min(minX, x);
|
||||
minY = Math.Min(minY, y);
|
||||
maxX = Math.Max(maxX, x);
|
||||
maxY = Math.Max(maxY, y);
|
||||
}
|
||||
}
|
||||
|
||||
if (maxX < minX || maxY < minY) return image;
|
||||
var bounds = Rectangle.FromLTRB(Math.Max(0, minX - 2), Math.Max(0, minY - 2), Math.Min(width, maxX + 3), Math.Min(height, maxY + 3));
|
||||
var trimmed = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
using (var g = Graphics.FromImage(trimmed))
|
||||
{
|
||||
g.DrawImage(image, new Rectangle(0, 0, trimmed.Width, trimmed.Height), bounds, GraphicsUnit.Pixel);
|
||||
}
|
||||
image.Dispose();
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
$compilerReferences = @(
|
||||
[System.Drawing.Bitmap].Assembly.Location,
|
||||
[System.Drawing.Color].Assembly.Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.GdiPlus').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.Core').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Collections').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Runtime').Location,
|
||||
[System.Object].Assembly.Location
|
||||
) | Select-Object -Unique
|
||||
Add-Type -TypeDefinition $helperSource -ReferencedAssemblies $compilerReferences
|
||||
|
||||
$board1 = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p0-idle-move-attacks-v1.png'
|
||||
$board2 = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p0-burst-hit-defeat-v1.png'
|
||||
$corrections = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p0-corrections-v2.png'
|
||||
$p1Board1 = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p1-ready-dodge-weakpoint-v1.png'
|
||||
$p1Board2 = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p1-cover-v1.png'
|
||||
$p1Board1V2 = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p1-ready-dodge-weakpoint-v2.png'
|
||||
$p1BoardLeft = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\action-keyposes\xinyin-p1-cover-left-v1.png'
|
||||
|
||||
if ($Set -eq 'p1') {
|
||||
$output = Join-Path $WorkspaceRoot "assets\images\2d-game-characters\02-xinyin\previews\xinyin-p1-readability-test-$Variant.png"
|
||||
}
|
||||
else {
|
||||
$output = Join-Path $WorkspaceRoot "assets\images\2d-game-characters\02-xinyin\previews\xinyin-action-readability-test-$Variant.png"
|
||||
}
|
||||
|
||||
if ($Set -eq 'p1' -and $Variant -eq 'v2') {
|
||||
$poses = @(
|
||||
@{ Name = 'READY'; Path = $p1Board1V2; Crop = [Drawing.Rectangle]::new(780, 35, 390, 300); ReferenceHeight = 300 },
|
||||
@{ Name = 'DODGE V2'; Path = $p1Board1V2; Crop = [Drawing.Rectangle]::new(500, 365, 510, 290); ReferenceHeight = 290 },
|
||||
@{ Name = 'WEAKPOINT'; Path = $p1Board1V2; Crop = [Drawing.Rectangle]::new(770, 685, 480, 315); ReferenceHeight = 305 },
|
||||
@{ Name = 'COVER IDLE R'; Path = $p1Board2; Crop = [Drawing.Rectangle]::new(1120, 45, 416, 445); ReferenceHeight = 320 },
|
||||
@{ Name = 'COVER ATTACK R'; Path = $p1Board2; Crop = [Drawing.Rectangle]::new(600, 545, 470, 435); ReferenceHeight = 320 },
|
||||
@{ Name = 'COVER ATTACK L'; Path = $p1BoardLeft; Crop = [Drawing.Rectangle]::new(500, 535, 530, 450); ReferenceHeight = 320 }
|
||||
)
|
||||
}
|
||||
elseif ($Set -eq 'p1') {
|
||||
$poses = @(
|
||||
@{ Name = 'READY'; Path = $p1Board1; Crop = [Drawing.Rectangle]::new(780, 35, 390, 300); ReferenceHeight = 300 },
|
||||
@{ Name = 'DODGE'; Path = $p1Board1; Crop = [Drawing.Rectangle]::new(500, 365, 510, 290); ReferenceHeight = 290 },
|
||||
@{ Name = 'WEAKPOINT'; Path = $p1Board1; Crop = [Drawing.Rectangle]::new(770, 685, 480, 315); ReferenceHeight = 305 },
|
||||
@{ Name = 'COVER IDLE'; Path = $p1Board2; Crop = [Drawing.Rectangle]::new(1120, 45, 416, 445); ReferenceHeight = 320 },
|
||||
@{ Name = 'COVER ATTACK'; Path = $p1Board2; Crop = [Drawing.Rectangle]::new(600, 545, 470, 435); ReferenceHeight = 320 }
|
||||
)
|
||||
}
|
||||
elseif ($Variant -eq 'v2') {
|
||||
$poses = @(
|
||||
@{ Name = 'IDLE'; Path = $board1; Crop = [Drawing.Rectangle]::new(500, 10, 290, 245); ReferenceHeight = 250 },
|
||||
@{ Name = 'MOVE'; Path = $board1; Crop = [Drawing.Rectangle]::new(120, 270, 310, 225); ReferenceHeight = 250 },
|
||||
@{ Name = 'ATTACK 1'; Path = $corrections; Crop = [Drawing.Rectangle]::new(560, 10, 450, 235); ReferenceHeight = 245 },
|
||||
@{ Name = 'ATTACK 2'; Path = $corrections; Crop = [Drawing.Rectangle]::new(560, 270, 450, 225); ReferenceHeight = 245 },
|
||||
@{ Name = 'BURST'; Path = $board2; Crop = [Drawing.Rectangle]::new(710, 10, 440, 345); ReferenceHeight = 305 },
|
||||
@{ Name = 'HIT'; Path = $corrections; Crop = [Drawing.Rectangle]::new(330, 520, 440, 210); ReferenceHeight = 235 },
|
||||
@{ Name = 'DEFEAT'; Path = $corrections; Crop = [Drawing.Rectangle]::new(1110, 770, 426, 240); ReferenceHeight = 250 }
|
||||
)
|
||||
}
|
||||
else {
|
||||
$poses = @(
|
||||
@{ Name = 'IDLE'; Path = $board1; Crop = [Drawing.Rectangle]::new(500, 10, 290, 245); ReferenceHeight = 250 },
|
||||
@{ Name = 'MOVE'; Path = $board1; Crop = [Drawing.Rectangle]::new(120, 270, 310, 225); ReferenceHeight = 250 },
|
||||
@{ Name = 'ATTACK 1'; Path = $board1; Crop = [Drawing.Rectangle]::new(590, 510, 410, 225); ReferenceHeight = 250 },
|
||||
@{ Name = 'ATTACK 2'; Path = $board1; Crop = [Drawing.Rectangle]::new(575, 755, 430, 250); ReferenceHeight = 250 },
|
||||
@{ Name = 'BURST'; Path = $board2; Crop = [Drawing.Rectangle]::new(710, 10, 440, 345); ReferenceHeight = 305 },
|
||||
@{ Name = 'HIT'; Path = $board2; Crop = [Drawing.Rectangle]::new(350, 380, 430, 270); ReferenceHeight = 285 },
|
||||
@{ Name = 'DEFEAT'; Path = $board2; Crop = [Drawing.Rectangle]::new(1040, 680, 496, 330); ReferenceHeight = 285 }
|
||||
)
|
||||
}
|
||||
|
||||
$canvas = [Drawing.Bitmap]::new(2000, 1200, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [Drawing.Graphics]::FromImage($canvas)
|
||||
$graphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$graphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.Clear([Drawing.Color]::FromArgb(255, 17, 22, 31))
|
||||
|
||||
$headerBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(242, 244, 250))
|
||||
$mutedBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(156, 171, 195))
|
||||
$linePen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(110, 118, 145, 183), 2)
|
||||
$gridPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(220, 106, 166, 230), 2)
|
||||
$gridFill = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(34, 75, 128, 185))
|
||||
$shadowBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(80, 0, 0, 0))
|
||||
$fontTitle = [Drawing.Font]::new('Segoe UI Semibold', 26)
|
||||
$fontSubtitle = [Drawing.Font]::new('Segoe UI', 14)
|
||||
$fontLabel = [Drawing.Font]::new('Segoe UI Semibold', 14)
|
||||
$fontRow = [Drawing.Font]::new('Segoe UI Semibold', 18)
|
||||
|
||||
$setLabel = if ($Set -eq 'p1') { 'P1 READABILITY TEST' } else { 'ACTION READABILITY TEST' }
|
||||
$graphics.DrawString("XIN YIN — $setLabel $($Variant.ToUpper())", $fontTitle, $headerBrush, 52, 28)
|
||||
$directionLabel = if ($Set -eq 'p1' -and $Variant -eq 'v2') { '4.75H front-right / front-left masters' } else { '4.75H front-right master' }
|
||||
$graphics.DrawString("$directionLabel | base unit height 176 px | base cell 128 × 64 px", $fontSubtitle, $mutedBrush, 55, 70)
|
||||
$graphics.DrawLine($linePen, 52, 104, 1948, 104)
|
||||
|
||||
$columnCenters = if ($poses.Count -eq 5) {
|
||||
@(360, 680, 1000, 1320, 1640)
|
||||
}
|
||||
elseif ($poses.Count -eq 6) {
|
||||
@(280, 568, 856, 1144, 1432, 1720)
|
||||
}
|
||||
else {
|
||||
@(245, 495, 745, 995, 1245, 1495, 1745)
|
||||
}
|
||||
for ($i = 0; $i -lt $poses.Count; $i++) {
|
||||
$size = $graphics.MeasureString($poses[$i].Name, $fontLabel)
|
||||
$graphics.DrawString($poses[$i].Name, $fontLabel, $mutedBrush, $columnCenters[$i] - $size.Width / 2, 122)
|
||||
}
|
||||
|
||||
$rows = @(
|
||||
@{ Label = '100%'; UnitHeight = 176; CellWidth = 128; CellHeight = 64; CenterY = 400 },
|
||||
@{ Label = '75%'; UnitHeight = 132; CellWidth = 96; CellHeight = 48; CenterY = 735 },
|
||||
@{ Label = '50%'; UnitHeight = 88; CellWidth = 64; CellHeight = 32; CenterY = 1040 }
|
||||
)
|
||||
|
||||
$sprites = @()
|
||||
try {
|
||||
foreach ($pose in $poses) {
|
||||
$sprites += [SpriteCropper]::Extract($pose.Path, $pose.Crop)
|
||||
}
|
||||
|
||||
foreach ($row in $rows) {
|
||||
$graphics.FillRectangle([Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(22, 255, 255, 255)), 34, $row.CenterY - 220, 1932, 285)
|
||||
$graphics.DrawString($row.Label, $fontRow, $headerBrush, 55, $row.CenterY - 205)
|
||||
$graphics.DrawString("unit $($row.UnitHeight) px", $fontSubtitle, $mutedBrush, 55, $row.CenterY - 172)
|
||||
|
||||
for ($i = 0; $i -lt $poses.Count; $i++) {
|
||||
$cx = $columnCenters[$i]
|
||||
$cy = $row.CenterY
|
||||
$halfW = $row.CellWidth / 2
|
||||
$halfH = $row.CellHeight / 2
|
||||
$diamond = [Drawing.PointF[]]@(
|
||||
[Drawing.PointF]::new($cx, $cy - $halfH),
|
||||
[Drawing.PointF]::new($cx + $halfW, $cy),
|
||||
[Drawing.PointF]::new($cx, $cy + $halfH),
|
||||
[Drawing.PointF]::new($cx - $halfW, $cy)
|
||||
)
|
||||
$graphics.FillPolygon($gridFill, $diamond)
|
||||
$graphics.DrawPolygon($gridPen, $diamond)
|
||||
$graphics.FillEllipse($shadowBrush, $cx - $halfW * 0.34, $cy - $halfH * 0.05, $halfW * 0.68, [Math]::Max(4, $halfH * 0.22))
|
||||
|
||||
$source = $sprites[$i]
|
||||
$scale = $row.UnitHeight / [double]$poses[$i].ReferenceHeight
|
||||
$drawW = [int][Math]::Round($source.Width * $scale)
|
||||
$drawH = [int][Math]::Round($source.Height * $scale)
|
||||
$drawX = [int][Math]::Round($cx - $drawW / 2)
|
||||
$drawY = [int][Math]::Round($cy + 6 - $drawH)
|
||||
$graphics.DrawImage($source, [Drawing.Rectangle]::new($drawX, $drawY, $drawW, $drawH))
|
||||
}
|
||||
}
|
||||
|
||||
$evaluationText = if ($Set -eq 'p1') {
|
||||
'Evaluation target: ready-state clarity, dodge afterimage balance, reticle separation, and cover exposure.'
|
||||
}
|
||||
else {
|
||||
'Evaluation target: silhouette, weapon-hand readability, secondary-motion clutter, and single-cell footprint.'
|
||||
}
|
||||
$graphics.DrawString($evaluationText, $fontSubtitle, $mutedBrush, 52, 1160)
|
||||
$canvas.Save($output, [Drawing.Imaging.ImageFormat]::Png)
|
||||
}
|
||||
finally {
|
||||
foreach ($sprite in $sprites) { if ($null -ne $sprite) { $sprite.Dispose() } }
|
||||
$fontTitle.Dispose(); $fontSubtitle.Dispose(); $fontLabel.Dispose(); $fontRow.Dispose()
|
||||
$headerBrush.Dispose(); $mutedBrush.Dispose(); $linePen.Dispose(); $gridPen.Dispose(); $gridFill.Dispose(); $shadowBrush.Dispose()
|
||||
$graphics.Dispose(); $canvas.Dispose()
|
||||
}
|
||||
|
||||
Get-Item -LiteralPath $output
|
||||
@@ -0,0 +1,325 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot),
|
||||
[int]$Padding = 8
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$helperSource = @'
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
|
||||
public sealed class AlphaMaskedComponent
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int Label { get; set; }
|
||||
public int Area { get; set; }
|
||||
public Rectangle Bounds { get; set; }
|
||||
public Bitmap Image { get; set; }
|
||||
}
|
||||
|
||||
public static class AlphaMaskExtractor
|
||||
{
|
||||
public static AlphaMaskedComponent[] ExtractAll(string path, int alphaThreshold, int minimumArea, int padding)
|
||||
{
|
||||
using (var source = new Bitmap(path))
|
||||
{
|
||||
int width = source.Width;
|
||||
int height = source.Height;
|
||||
var foreground = new bool[width * height];
|
||||
var labels = new int[width * height];
|
||||
var queue = new int[width * height];
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
int row = y * width;
|
||||
for (int x = 0; x < width; x++)
|
||||
foreground[row + x] = source.GetPixel(x, y).A >= alphaThreshold;
|
||||
}
|
||||
|
||||
var components = new ArrayList();
|
||||
int[] dx = { -1, 0, 1, -1, 1, -1, 0, 1 };
|
||||
int[] dy = { -1, -1, -1, 0, 0, 1, 1, 1 };
|
||||
int nextLabel = 0;
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int start = y * width + x;
|
||||
if (labels[start] != 0 || !foreground[start]) continue;
|
||||
|
||||
nextLabel++;
|
||||
int head = 0, tail = 0, area = 0;
|
||||
int minX = x, minY = y, maxX = x, maxY = y;
|
||||
labels[start] = nextLabel;
|
||||
queue[tail++] = start;
|
||||
|
||||
while (head < tail)
|
||||
{
|
||||
int index = queue[head++];
|
||||
int px = index % width;
|
||||
int py = index / width;
|
||||
area++;
|
||||
if (px < minX) minX = px;
|
||||
if (px > maxX) maxX = px;
|
||||
if (py < minY) minY = py;
|
||||
if (py > maxY) maxY = py;
|
||||
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
int nx = px + dx[i];
|
||||
int ny = py + dy[i];
|
||||
if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
|
||||
int next = ny * width + nx;
|
||||
if (labels[next] != 0 || !foreground[next]) continue;
|
||||
labels[next] = nextLabel;
|
||||
queue[tail++] = next;
|
||||
}
|
||||
}
|
||||
|
||||
if (area >= minimumArea)
|
||||
{
|
||||
components.Add(new AlphaMaskedComponent {
|
||||
Label = nextLabel,
|
||||
Area = area,
|
||||
Bounds = Rectangle.FromLTRB(minX, minY, maxX + 1, maxY + 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var result = new AlphaMaskedComponent[components.Count];
|
||||
for (int i = 0; i < components.Count; i++) result[i] = (AlphaMaskedComponent)components[i];
|
||||
Array.Sort(result, (a, b) => {
|
||||
int rowCompare = a.Bounds.Top.CompareTo(b.Bounds.Top);
|
||||
return rowCompare != 0 ? rowCompare : a.Bounds.Left.CompareTo(b.Bounds.Left);
|
||||
});
|
||||
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
var component = result[i];
|
||||
component.Id = i + 1;
|
||||
var bitmap = new Bitmap(component.Bounds.Width + padding * 2, component.Bounds.Height + padding * 2, PixelFormat.Format32bppArgb);
|
||||
for (int py = component.Bounds.Top; py < component.Bounds.Bottom; py++)
|
||||
{
|
||||
for (int px = component.Bounds.Left; px < component.Bounds.Right; px++)
|
||||
{
|
||||
int sourceIndex = py * width + px;
|
||||
if (labels[sourceIndex] != component.Label) continue;
|
||||
bitmap.SetPixel(px - component.Bounds.Left + padding, py - component.Bounds.Top + padding, source.GetPixel(px, py));
|
||||
}
|
||||
}
|
||||
component.Image = bitmap;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
$compilerReferences = @(
|
||||
[System.Drawing.Bitmap].Assembly.Location,
|
||||
[System.Drawing.Color].Assembly.Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.GdiPlus').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.Core').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Collections').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Runtime').Location,
|
||||
[System.Object].Assembly.Location
|
||||
) | Select-Object -Unique
|
||||
Add-Type -TypeDefinition $helperSource -ReferencedAssemblies $compilerReferences
|
||||
|
||||
$sourcePath = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\xinyin-front-right-parts-sheet-v1.png'
|
||||
$characterRoot = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin'
|
||||
$outputDirectory = Join-Path $characterRoot 'parts\front-right\v1'
|
||||
$referenceDirectory = Join-Path $characterRoot 'reference'
|
||||
$previewDirectory = Join-Path $characterRoot 'previews'
|
||||
$manifestPath = Join-Path $outputDirectory 'parts-manifest.json'
|
||||
$contactSheetPath = Join-Path $previewDirectory 'xinyin-front-right-extracted-parts-v1.png'
|
||||
$referencePath = Join-Path $referenceDirectory 'xinyin-front-right-assembled-reference-v1.png'
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $outputDirectory, $referenceDirectory, $previewDirectory | Out-Null
|
||||
|
||||
# Coordinates come from the alpha-component diagnostic. Component 11 is the assembled reference.
|
||||
# Pivot values are normalized inside the non-padding content bounds, not the exported canvas.
|
||||
$parts = @(
|
||||
@{ Id=1; Name='hair-back-main'; Label='后发主体'; Category='hair'; Rect=@(836,23,305,270); Pivot=@(.50,.08); Layer=-100; Notes='两个马尾方案被细发丝粘连;首次装配验证判定为参考件,不直接进入骨骼' },
|
||||
@{ Id=2; Name='hair-back-segment-02'; Label='后发分片 02'; Category='hair'; Rect=@(1130,39,201,247); Pivot=@(.40,.08); Layer=-98; Notes='方向归属待装配确认' },
|
||||
@{ Id=3; Name='hair-back-segment-04'; Label='后发分片 04'; Category='hair'; Rect=@(1484,53,140,187); Pivot=@(.45,.08); Layer=-94; Notes='首次装配 v2 选用的后发主片' },
|
||||
@{ Id=4; Name='hair-front'; Label='前发与侧鬓'; Category='hair'; Rect=@(522,54,130,179); Pivot=@(.50,.12); Layer=35; Notes='位于面部之前' },
|
||||
@{ Id=5; Name='hair-side-segment-01'; Label='侧发分片 01'; Category='hair'; Rect=@(666,62,90,171); Pivot=@(.50,.08); Layer=-88; Notes='方向归属待装配确认' },
|
||||
@{ Id=6; Name='hair-back-segment-03'; Label='后发分片 03'; Category='hair'; Rect=@(1330,66,132,186); Pivot=@(.45,.08); Layer=-96; Notes='首次装配 v2 选用的后发辅片' },
|
||||
@{ Id=7; Name='head-face'; Label='头部与面部'; Category='body'; Rect=@(427,73,86,115); Pivot=@(.50,.91); Layer=30; Notes='枢轴靠近颈部连接点' },
|
||||
@{ Id=8; Name='hair-side-segment-02'; Label='侧发分片 02'; Category='hair'; Rect=@(778,76,56,157); Pivot=@(.50,.07); Layer=-86; Notes='方向归属待装配确认' },
|
||||
@{ Id=9; Name='hair-ornament-long'; Label='长发饰'; Category='ornament'; Rect=@(1629,96,50,147); Pivot=@(.50,.08); Layer=42; Notes='含花饰与垂坠' },
|
||||
@{ Id=10; Name='hair-ornament-short'; Label='短发饰'; Category='ornament'; Rect=@(1695,96,30,98); Pivot=@(.50,.08); Layer=41; Notes='含花饰与流苏' },
|
||||
@{ Id=12; Name='neck'; Label='颈部'; Category='body'; Rect=@(449,211,43,45); Pivot=@(.50,.75); Layer=5; Notes='头部和躯干之间' },
|
||||
@{ Id=13; Name='torso-upper'; Label='上半身躯干'; Category='body'; Rect=@(401,260,124,156); Pivot=@(.50,.92); Layer=10; Notes='根枢轴靠近腰线' },
|
||||
@{ Id=14; Name='waist-guard'; Label='腰封与短裙'; Category='body'; Rect=@(536,285,183,186); Pivot=@(.50,.18); Layer=4; Notes='上端连接躯干' },
|
||||
@{ Id=15; Name='upper-arm-sleeve-a'; Label='袖片与上臂 A'; Category='arm'; Rect=@(843,301,120,202); Pivot=@(.58,.08); Layer=14; Notes='左右归属待装配确认' },
|
||||
@{ Id=16; Name='pelvis'; Label='骨盆与内层短裤'; Category='body'; Rect=@(720,303,107,102); Pivot=@(.50,.16); Layer=2; Notes='角色主根节点候选' },
|
||||
@{ Id=17; Name='upper-arm-sleeve-b'; Label='袖片与上臂 B'; Category='arm'; Rect=@(996,304,106,211); Pivot=@(.42,.08); Layer=14; Notes='左右归属待装配确认' },
|
||||
@{ Id=18; Name='forearm-hand-a'; Label='前臂与手 A'; Category='arm'; Rect=@(1110,321,59,222); Pivot=@(.50,.08); Layer=16; Notes='肘部连接点在上端' },
|
||||
@{ Id=19; Name='arm-straight-variant'; Label='直臂替换件'; Category='arm'; Rect=@(1275,336,107,197);Pivot=@(.34,.08); Layer=16; Notes='备用动作变体,装配时择一使用' },
|
||||
@{ Id=20; Name='forearm-hand-b'; Label='前臂与手 B'; Category='arm'; Rect=@(1184,340,83,207); Pivot=@(.50,.08); Layer=16; Notes='肘部连接点在上端' },
|
||||
@{ Id=21; Name='weapon-fan-open'; Label='展开羽刃扇'; Category='weapon'; Rect=@(1634,363,99,165); Pivot=@(.50,.88); Layer=50; Notes='枢轴位于柄部' },
|
||||
@{ Id=22; Name='weapon-hand-fan'; Label='持扇手替换件'; Category='arm'; Rect=@(1444,382,93,133); Pivot=@(.42,.88); Layer=48; Notes='动作替换件,含手与武器' },
|
||||
@{ Id=23; Name='weapon-blade-single'; Label='单枚羽刃'; Category='weapon'; Rect=@(1563,389,29,130); Pivot=@(.50,.82); Layer=50; Notes='投掷物或手持物' },
|
||||
@{ Id=24; Name='hand-open'; Label='张开手替换件'; Category='arm'; Rect=@(1391,409,55,77); Pivot=@(.50,.08); Layer=18; Notes='腕部连接点在上端' },
|
||||
@{ Id=25; Name='leg-full-variant'; Label='整腿替换件'; Category='leg'; Rect=@(437,419,111,426); Pivot=@(.50,.04); Layer=-12; Notes='备用动作变体,装配时择一使用' },
|
||||
@{ Id=26; Name='thigh-b'; Label='大腿 B'; Category='leg'; Rect=@(727,425,94,169); Pivot=@(.50,.05); Layer=-8; Notes='左右归属待装配确认' },
|
||||
@{ Id=27; Name='thigh-a'; Label='大腿 A'; Category='leg'; Rect=@(552,471,76,133); Pivot=@(.50,.05); Layer=-8; Notes='左右归属待装配确认' },
|
||||
@{ Id=28; Name='shoulder-armor-b'; Label='肩甲 B'; Category='armor'; Rect=@(1002,510,97,86); Pivot=@(.50,.18); Layer=20; Notes='左右归属待装配确认' },
|
||||
@{ Id=29; Name='shoulder-armor-a'; Label='肩甲 A'; Category='armor'; Rect=@(887,512,91,85); Pivot=@(.50,.18); Layer=20; Notes='左右归属待装配确认' },
|
||||
@{ Id=30; Name='shin-boot-a'; Label='小腿与靴 A'; Category='leg'; Rect=@(561,592,90,242); Pivot=@(.50,.05); Layer=-7; Notes='膝部连接点在上端' },
|
||||
@{ Id=31; Name='coat-panel-03'; Label='衣摆分片 03'; Category='cloth'; Rect=@(1262,594,90,252); Pivot=@(.50,.04); Layer=-37; Notes='方向归属待装配确认' },
|
||||
@{ Id=32; Name='coat-panel-05'; Label='衣摆分片 05'; Category='cloth'; Rect=@(1405,595,64,219); Pivot=@(.50,.04); Layer=-35; Notes='方向归属待装配确认' },
|
||||
@{ Id=33; Name='coat-panel-06'; Label='衣摆分片 06'; Category='cloth'; Rect=@(1475,595,86,258); Pivot=@(.50,.04); Layer=-34; Notes='方向归属待装配确认' },
|
||||
@{ Id=34; Name='coat-panel-02'; Label='衣摆分片 02'; Category='cloth'; Rect=@(1136,596,117,262);Pivot=@(.50,.04); Layer=-38; Notes='方向归属待装配确认' },
|
||||
@{ Id=35; Name='coat-panel-01'; Label='衣摆分片 01'; Category='cloth'; Rect=@(1084,597,94,240); Pivot=@(.50,.04); Layer=-39; Notes='方向归属待装配确认' },
|
||||
@{ Id=36; Name='coat-panel-08'; Label='衣摆分片 08'; Category='cloth'; Rect=@(1673,598,92,201); Pivot=@(.50,.04); Layer=-32; Notes='方向归属待装配确认' },
|
||||
@{ Id=37; Name='coat-panel-07'; Label='衣摆分片 07'; Category='cloth'; Rect=@(1565,599,175,239);Pivot=@(.50,.04); Layer=-33; Notes='方向归属待装配确认' },
|
||||
@{ Id=38; Name='shin-boot-b'; Label='小腿与靴 B'; Category='leg'; Rect=@(753,600,64,246); Pivot=@(.50,.05); Layer=-7; Notes='膝部连接点在上端' },
|
||||
@{ Id=39; Name='coat-panel-04'; Label='衣摆分片 04'; Category='cloth'; Rect=@(1331,601,80,237); Pivot=@(.50,.04); Layer=-36; Notes='方向归属待装配确认' },
|
||||
@{ Id=40; Name='front-drape'; Label='前腰布与垂饰'; Category='cloth'; Rect=@(861,614,129,266); Pivot=@(.50,.04); Layer=6; Notes='位于腰封前侧' },
|
||||
@{ Id=41; Name='waist-pouch'; Label='腰包与流苏'; Category='accessory'; Rect=@(1002,620,95,143); Pivot=@(.28,.08); Layer=22; Notes='连接腰侧' }
|
||||
)
|
||||
|
||||
$source = [Drawing.Bitmap]::new($sourcePath)
|
||||
$maskedComponents = [AlphaMaskExtractor]::ExtractAll($sourcePath, 16, 80, $Padding)
|
||||
$maskedById = @{}
|
||||
foreach ($component in $maskedComponents) { $maskedById[$component.Id] = $component }
|
||||
$manifestParts = @()
|
||||
$exported = @()
|
||||
|
||||
try {
|
||||
foreach ($part in $parts) {
|
||||
$rect = [Drawing.Rectangle]::new($part.Rect[0], $part.Rect[1], $part.Rect[2], $part.Rect[3])
|
||||
$canvas = $maskedById[$part.Id].Image
|
||||
|
||||
$fileName = ('fr-c{0:d2}-{1}.png' -f $part.Id, $part.Name)
|
||||
$filePath = Join-Path $outputDirectory $fileName
|
||||
$canvas.Save($filePath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$pivotPxX = $Padding + [Math]::Round($rect.Width * $part.Pivot[0], 2)
|
||||
$pivotPxY = $Padding + [Math]::Round($rect.Height * $part.Pivot[1], 2)
|
||||
$manifestParts += [ordered]@{
|
||||
componentId = $part.Id
|
||||
name = $part.Name
|
||||
labelZh = $part.Label
|
||||
category = $part.Category
|
||||
file = $fileName
|
||||
sourceRect = [ordered]@{ x=$rect.X; y=$rect.Y; width=$rect.Width; height=$rect.Height }
|
||||
outputSize = [ordered]@{ width=$canvas.Width; height=$canvas.Height }
|
||||
pivot = [ordered]@{
|
||||
contentNormalized = [ordered]@{ x=$part.Pivot[0]; y=$part.Pivot[1] }
|
||||
outputPixels = [ordered]@{ x=$pivotPxX; y=$pivotPxY }
|
||||
}
|
||||
suggestedLayer = $part.Layer
|
||||
notes = $part.Notes
|
||||
}
|
||||
$exported += [ordered]@{ Part=$part; Image=$canvas; FilePath=$filePath }
|
||||
}
|
||||
|
||||
$reference = $maskedById[11].Image
|
||||
$reference.Save($referencePath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$manifest = [ordered]@{
|
||||
characterId = '02-xinyin'
|
||||
characterNameZh = '汐月心音'
|
||||
direction = 'front-right'
|
||||
version = 1
|
||||
status = 'extracted-unvalidated'
|
||||
source = 'assets/images/2d-game-characters/02-xinyin/source/xinyin-front-right-parts-sheet-v1.png'
|
||||
sourceSize = [ordered]@{ width=$source.Width; height=$source.Height }
|
||||
padding = $Padding
|
||||
alphaExtraction = [ordered]@{ connectivity=8; alphaThreshold=16; minimumComponentArea=80; mode='connected-component-mask' }
|
||||
coordinateSystem = [ordered]@{
|
||||
origin = 'top-left'
|
||||
xPositive = 'right'
|
||||
yPositive = 'down'
|
||||
units = 'pixels'
|
||||
pivotBasis = 'content bounds before export padding'
|
||||
}
|
||||
warnings = @(
|
||||
'Pivot values and suggested layers are initial authoring recommendations and have not been validated in an engine rig.',
|
||||
'A/B limb ownership and numbered hair/coat segment ownership must be confirmed during first assembly.',
|
||||
'Do not mirror asymmetric left/right art automatically.'
|
||||
)
|
||||
assembledReference = 'assets/images/2d-game-characters/02-xinyin/reference/xinyin-front-right-assembled-reference-v1.png'
|
||||
partCount = $manifestParts.Count
|
||||
parts = $manifestParts
|
||||
}
|
||||
$manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $manifestPath -Encoding utf8
|
||||
|
||||
$columns = 5
|
||||
$cellWidth = 460
|
||||
$cellHeight = 300
|
||||
$rows = [Math]::Ceiling($exported.Count / $columns)
|
||||
$sheet = [Drawing.Bitmap]::new($columns * $cellWidth, $rows * $cellHeight, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$sheetGraphics = [Drawing.Graphics]::FromImage($sheet)
|
||||
$sheetGraphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$sheetGraphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$sheetGraphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$sheetGraphics.Clear([Drawing.Color]::FromArgb(255, 20, 24, 33))
|
||||
$borderPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 60, 74, 98), 2)
|
||||
$pivotPen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 255, 88, 112), 2)
|
||||
$titleBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 241, 245, 252))
|
||||
$metaBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 154, 172, 201))
|
||||
$fontTitle = [Drawing.Font]::new('Segoe UI Semibold', 14)
|
||||
$fontMeta = [Drawing.Font]::new('Segoe UI', 10)
|
||||
|
||||
for ($i = 0; $i -lt $exported.Count; $i++) {
|
||||
$col = $i % $columns
|
||||
$row = [Math]::Floor($i / $columns)
|
||||
$x = $col * $cellWidth
|
||||
$y = $row * $cellHeight
|
||||
$sheetGraphics.DrawRectangle($borderPen, $x + 8, $y + 8, $cellWidth - 16, $cellHeight - 16)
|
||||
|
||||
$image = $exported[$i].Image
|
||||
$maxWidth = 310.0
|
||||
$maxHeight = 215.0
|
||||
$scale = [Math]::Min($maxWidth / $image.Width, $maxHeight / $image.Height)
|
||||
$scale = [Math]::Min(1.0, $scale)
|
||||
$drawWidth = [int][Math]::Round($image.Width * $scale)
|
||||
$drawHeight = [int][Math]::Round($image.Height * $scale)
|
||||
$drawX = $x + [int](($cellWidth - $drawWidth) / 2)
|
||||
$drawY = $y + 42 + [int](($maxHeight - $drawHeight) / 2)
|
||||
$sheetGraphics.DrawImage($image, $drawX, $drawY, $drawWidth, $drawHeight)
|
||||
|
||||
$pivot = $manifestParts[$i].pivot.outputPixels
|
||||
$pivotX = $drawX + [float]$pivot.x * $scale
|
||||
$pivotY = $drawY + [float]$pivot.y * $scale
|
||||
$sheetGraphics.DrawLine($pivotPen, $pivotX - 6, $pivotY, $pivotX + 6, $pivotY)
|
||||
$sheetGraphics.DrawLine($pivotPen, $pivotX, $pivotY - 6, $pivotX, $pivotY + 6)
|
||||
|
||||
$title = ('C{0:d2} {1}' -f $exported[$i].Part.Id, $exported[$i].Part.Name)
|
||||
$sheetGraphics.DrawString($title, $fontTitle, $titleBrush, $x + 18, $y + 14)
|
||||
$meta = ('{0} | {1}x{2}px' -f $exported[$i].Part.Label, $image.Width, $image.Height)
|
||||
$sheetGraphics.DrawString($meta, $fontMeta, $metaBrush, $x + 18, $y + 267)
|
||||
}
|
||||
|
||||
$sheet.Save($contactSheetPath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
$fontMeta.Dispose()
|
||||
$fontTitle.Dispose()
|
||||
$metaBrush.Dispose()
|
||||
$titleBrush.Dispose()
|
||||
$pivotPen.Dispose()
|
||||
$borderPen.Dispose()
|
||||
$sheetGraphics.Dispose()
|
||||
$sheet.Dispose()
|
||||
}
|
||||
finally {
|
||||
foreach ($component in $maskedComponents) {
|
||||
if ($null -ne $component.Image) { $component.Image.Dispose() }
|
||||
}
|
||||
$source.Dispose()
|
||||
}
|
||||
|
||||
Write-Output "Exported $($parts.Count) parts."
|
||||
Write-Output $outputDirectory
|
||||
Write-Output $manifestPath
|
||||
Write-Output $contactSheetPath
|
||||
Write-Output $referencePath
|
||||
@@ -0,0 +1,237 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot),
|
||||
[int]$Padding = 10
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$helperSource = @'
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
|
||||
public sealed class RigCorrectionComponent
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int Label { get; set; }
|
||||
public int Area { get; set; }
|
||||
public Rectangle Bounds { get; set; }
|
||||
public Bitmap Image { get; set; }
|
||||
}
|
||||
|
||||
public static class RigCorrectionExtractor
|
||||
{
|
||||
public static RigCorrectionComponent[] ExtractAll(string path, int alphaThreshold, int minimumArea, int padding)
|
||||
{
|
||||
using (var source = new Bitmap(path))
|
||||
{
|
||||
int width = source.Width, height = source.Height;
|
||||
var foreground = new bool[width * height];
|
||||
var labels = new int[width * height];
|
||||
var queue = new int[width * height];
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
int row = y * width;
|
||||
for (int x = 0; x < width; x++) foreground[row + x] = source.GetPixel(x, y).A >= alphaThreshold;
|
||||
}
|
||||
|
||||
var components = new ArrayList();
|
||||
int[] dx = { -1, 0, 1, -1, 1, -1, 0, 1 };
|
||||
int[] dy = { -1, -1, -1, 0, 0, 1, 1, 1 };
|
||||
int nextLabel = 0;
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int start = y * width + x;
|
||||
if (labels[start] != 0 || !foreground[start]) continue;
|
||||
nextLabel++;
|
||||
int head = 0, tail = 0, area = 0;
|
||||
int minX = x, minY = y, maxX = x, maxY = y;
|
||||
labels[start] = nextLabel;
|
||||
queue[tail++] = start;
|
||||
while (head < tail)
|
||||
{
|
||||
int index = queue[head++];
|
||||
int px = index % width, py = index / width;
|
||||
area++;
|
||||
if (px < minX) minX = px; if (px > maxX) maxX = px;
|
||||
if (py < minY) minY = py; if (py > maxY) maxY = py;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
int nx = px + dx[i], ny = py + dy[i];
|
||||
if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
|
||||
int next = ny * width + nx;
|
||||
if (labels[next] != 0 || !foreground[next]) continue;
|
||||
labels[next] = nextLabel;
|
||||
queue[tail++] = next;
|
||||
}
|
||||
}
|
||||
if (area >= minimumArea)
|
||||
{
|
||||
components.Add(new RigCorrectionComponent {
|
||||
Label = nextLabel, Area = area,
|
||||
Bounds = Rectangle.FromLTRB(minX, minY, maxX + 1, maxY + 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var result = new RigCorrectionComponent[components.Count];
|
||||
for (int i = 0; i < components.Count; i++) result[i] = (RigCorrectionComponent)components[i];
|
||||
Array.Sort(result, (a, b) => {
|
||||
int rowCompare = a.Bounds.Top.CompareTo(b.Bounds.Top);
|
||||
return rowCompare != 0 ? rowCompare : a.Bounds.Left.CompareTo(b.Bounds.Left);
|
||||
});
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
var component = result[i];
|
||||
component.Id = i + 1;
|
||||
var bitmap = new Bitmap(component.Bounds.Width + padding * 2, component.Bounds.Height + padding * 2, PixelFormat.Format32bppArgb);
|
||||
for (int py = component.Bounds.Top; py < component.Bounds.Bottom; py++)
|
||||
{
|
||||
for (int px = component.Bounds.Left; px < component.Bounds.Right; px++)
|
||||
{
|
||||
int sourceIndex = py * width + px;
|
||||
if (labels[sourceIndex] != component.Label) continue;
|
||||
bitmap.SetPixel(px - component.Bounds.Left + padding, py - component.Bounds.Top + padding, source.GetPixel(px, py));
|
||||
}
|
||||
}
|
||||
component.Image = bitmap;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
$compilerReferences = @(
|
||||
[System.Drawing.Bitmap].Assembly.Location,
|
||||
[System.Drawing.Color].Assembly.Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.GdiPlus').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.Core').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Collections').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Runtime').Location,
|
||||
[System.Object].Assembly.Location
|
||||
) | Select-Object -Unique
|
||||
Add-Type -TypeDefinition $helperSource -ReferencedAssemblies $compilerReferences
|
||||
|
||||
$sourcePath = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\rig-corrections\xinyin-front-right-rig-corrections-v2.png'
|
||||
$characterRoot = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin'
|
||||
$outputDirectory = Join-Path $characterRoot 'parts\front-right\rig-corrections-v1'
|
||||
$previewPath = Join-Path $characterRoot 'previews\xinyin-front-right-rig-corrections-v1.png'
|
||||
$manifestPath = Join-Path $outputDirectory 'rig-corrections-manifest.json'
|
||||
New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null
|
||||
|
||||
$parts = @(
|
||||
@{ Id=1; Name='upper-arm-a'; Label='上臂 A'; Category='arm'; Pivot=@(.50,.06); Next=@(.50,.72); Note='肩点到肘点;不含独立银羽肩甲' },
|
||||
@{ Id=2; Name='upper-arm-b'; Label='上臂 B'; Category='arm'; Pivot=@(.50,.06); Next=@(.50,.72); Note='肩点到肘点;不含独立银羽肩甲' },
|
||||
@{ Id=3; Name='ponytail-root'; Label='马尾根部'; Category='hair'; Pivot=@(.34,.30); Next=@(.82,.52); Note='含绑点与银花;根部体积偏大,先用于链条验证' },
|
||||
@{ Id=4; Name='ponytail-middle'; Label='马尾中段'; Category='hair'; Pivot=@(.50,.06); Next=@(.53,.88); Note='上下两端均预留重叠' },
|
||||
@{ Id=5; Name='ponytail-tip'; Label='马尾末端'; Category='hair'; Pivot=@(.50,.06); Next=@(.55,.92); Note='上端与中段重叠,末端不再挂接子节' },
|
||||
@{ Id=6; Name='forearm-b'; Label='前臂 B'; Category='arm'; Pivot=@(.50,.06); Next=@(.50,.92); Note='肘点到腕点;不含手' },
|
||||
@{ Id=7; Name='forearm-a'; Label='前臂 A'; Category='arm'; Pivot=@(.50,.06); Next=@(.50,.92); Note='肘点到腕点;不含手' },
|
||||
@{ Id=8; Name='hand-fan-grip'; Label='持扇手'; Category='hand'; Pivot=@(.82,.80); Next=$null; Note='腕点位于右下袖口' },
|
||||
@{ Id=9; Name='hand-relaxed-b'; Label='放松手 B'; Category='hand'; Pivot=@(.50,.08); Next=$null; Note='腕点位于上端' },
|
||||
@{ Id=10; Name='hand-relaxed-a'; Label='放松手 A'; Category='hand'; Pivot=@(.50,.08); Next=$null; Note='腕点位于上端' },
|
||||
@{ Id=11; Name='hand-throw-open'; Label='投掷张手'; Category='hand'; Pivot=@(.18,.34); Next=$null; Note='腕点位于左上袖口' }
|
||||
)
|
||||
|
||||
$components = [RigCorrectionExtractor]::ExtractAll($sourcePath, 16, 120, $Padding)
|
||||
if ($components.Count -ne 11) { throw "Expected 11 components, detected $($components.Count)." }
|
||||
$componentById = @{}
|
||||
foreach ($component in $components) { $componentById[$component.Id] = $component }
|
||||
$manifestParts = @()
|
||||
|
||||
try {
|
||||
foreach ($part in $parts) {
|
||||
$component = $componentById[$part.Id]
|
||||
$fileName = ('fr-rig-c{0:d2}-{1}.png' -f $part.Id, $part.Name)
|
||||
$filePath = Join-Path $outputDirectory $fileName
|
||||
$component.Image.Save($filePath, [Drawing.Imaging.ImageFormat]::Png)
|
||||
$rootX = $Padding + [Math]::Round($component.Bounds.Width * $part.Pivot[0], 2)
|
||||
$rootY = $Padding + [Math]::Round($component.Bounds.Height * $part.Pivot[1], 2)
|
||||
$nextJoint = $null
|
||||
if ($null -ne $part.Next) {
|
||||
$nextJoint = [ordered]@{
|
||||
contentNormalized=[ordered]@{ x=$part.Next[0]; y=$part.Next[1] }
|
||||
outputPixels=[ordered]@{
|
||||
x=$Padding+[Math]::Round($component.Bounds.Width*$part.Next[0],2)
|
||||
y=$Padding+[Math]::Round($component.Bounds.Height*$part.Next[1],2)
|
||||
}
|
||||
}
|
||||
}
|
||||
$manifestParts += [ordered]@{
|
||||
componentId=$part.Id; name=$part.Name; labelZh=$part.Label; category=$part.Category; file=$fileName
|
||||
sourceRect=[ordered]@{ x=$component.Bounds.X; y=$component.Bounds.Y; width=$component.Bounds.Width; height=$component.Bounds.Height }
|
||||
outputSize=[ordered]@{ width=$component.Image.Width; height=$component.Image.Height }
|
||||
rootPivot=[ordered]@{
|
||||
contentNormalized=[ordered]@{ x=$part.Pivot[0]; y=$part.Pivot[1] }
|
||||
outputPixels=[ordered]@{ x=$rootX; y=$rootY }
|
||||
}
|
||||
nextJoint=$nextJoint
|
||||
notes=$part.Note
|
||||
}
|
||||
}
|
||||
|
||||
[ordered]@{
|
||||
characterId='02-xinyin'; direction='front-right'; version=1; status='correction-parts-art-validated'
|
||||
source='assets/images/2d-game-characters/02-xinyin/source/rig-corrections/xinyin-front-right-rig-corrections-v2.png'
|
||||
generatedWith='built-in image generation tool, identity-constrained reference generation plus targeted hair edit'
|
||||
padding=$Padding
|
||||
coordinateSystem=[ordered]@{ origin='top-left'; xPositive='right'; yPositive='down'; units='pixels' }
|
||||
warnings=@(
|
||||
'A/B screen-side ownership is validated for front-right assembly v4 and motion v3.',
|
||||
'Ponytail root is larger than an ideal production root segment but passed the current chain-motion test.',
|
||||
'Root pivots and next joints are art-side validated; engine interpolation remains untested.'
|
||||
)
|
||||
partCount=$manifestParts.Count; parts=$manifestParts
|
||||
} | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $manifestPath -Encoding utf8
|
||||
|
||||
$columns=4; $cellWidth=500; $cellHeight=360
|
||||
$rows=[Math]::Ceiling($parts.Count/$columns)
|
||||
$sheet=[Drawing.Bitmap]::new($columns*$cellWidth,$rows*$cellHeight,[Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g=[Drawing.Graphics]::FromImage($sheet)
|
||||
$g.SmoothingMode=[Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.InterpolationMode=[Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.PixelOffsetMode=[Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$g.Clear([Drawing.Color]::FromArgb(255,18,22,31))
|
||||
$border=[Drawing.Pen]::new([Drawing.Color]::FromArgb(255,66,82,111),2)
|
||||
$rootPen=[Drawing.Pen]::new([Drawing.Color]::FromArgb(255,255,87,115),3)
|
||||
$nextPen=[Drawing.Pen]::new([Drawing.Color]::FromArgb(255,69,211,255),3)
|
||||
$titleBrush=[Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255,241,245,252))
|
||||
$metaBrush=[Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255,151,171,201))
|
||||
$fontTitle=[Drawing.Font]::new('Segoe UI Semibold',16)
|
||||
$fontMeta=[Drawing.Font]::new('Segoe UI',11)
|
||||
|
||||
for ($i=0; $i -lt $parts.Count; $i++) {
|
||||
$part=$parts[$i]; $component=$componentById[$part.Id]; $record=$manifestParts[$i]
|
||||
$col=$i%$columns; $row=[Math]::Floor($i/$columns); $x=$col*$cellWidth; $y=$row*$cellHeight
|
||||
$g.DrawRectangle($border,$x+8,$y+8,$cellWidth-16,$cellHeight-16)
|
||||
$maxW=330.0; $maxH=260.0
|
||||
$scale=[Math]::Min($maxW/$component.Image.Width,$maxH/$component.Image.Height); $scale=[Math]::Min(1.0,$scale)
|
||||
$dw=[int][Math]::Round($component.Image.Width*$scale); $dh=[int][Math]::Round($component.Image.Height*$scale)
|
||||
$dx=$x+[int](($cellWidth-$dw)/2); $dy=$y+45+[int](($maxH-$dh)/2)
|
||||
$g.DrawImage($component.Image,$dx,$dy,$dw,$dh)
|
||||
$rx=$dx+[single]($record.rootPivot.outputPixels.x*$scale); $ry=$dy+[single]($record.rootPivot.outputPixels.y*$scale)
|
||||
$g.DrawLine($rootPen,$rx-7,$ry,$rx+7,$ry); $g.DrawLine($rootPen,$rx,$ry-7,$rx,$ry+7)
|
||||
if ($null -ne $record.nextJoint) {
|
||||
$nx=$dx+[single]($record.nextJoint.outputPixels.x*$scale); $ny=$dy+[single]($record.nextJoint.outputPixels.y*$scale)
|
||||
$g.DrawEllipse($nextPen,$nx-6,$ny-6,12,12)
|
||||
}
|
||||
$g.DrawString(('C{0:d2} {1}' -f $part.Id,$part.Name),$fontTitle,$titleBrush,$x+18,$y+14)
|
||||
$g.DrawString("$($part.Label) | red root / cyan next",$fontMeta,$metaBrush,$x+18,$y+326)
|
||||
}
|
||||
$sheet.Save($previewPath,[Drawing.Imaging.ImageFormat]::Png)
|
||||
$fontMeta.Dispose(); $fontTitle.Dispose(); $metaBrush.Dispose(); $titleBrush.Dispose()
|
||||
$nextPen.Dispose(); $rootPen.Dispose(); $border.Dispose(); $g.Dispose(); $sheet.Dispose()
|
||||
}
|
||||
finally {
|
||||
foreach ($component in $components) { if ($null -ne $component.Image) { $component.Image.Dispose() } }
|
||||
}
|
||||
|
||||
Write-Output "Exported $($parts.Count) rig-correction parts."
|
||||
Write-Output $outputDirectory
|
||||
Write-Output $manifestPath
|
||||
Write-Output $previewPath
|
||||
@@ -0,0 +1,185 @@
|
||||
param(
|
||||
[string]$WorkspaceRoot = (Split-Path -Parent $PSScriptRoot),
|
||||
[string]$InputPath = '',
|
||||
[string]$OutputStem = 'xinyin-front-right-parts',
|
||||
[int]$AlphaThreshold = 16,
|
||||
[int]$MinimumArea = 80
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$helperSource = @'
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Drawing;
|
||||
|
||||
public sealed class AlphaComponent
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int Area { get; set; }
|
||||
public Rectangle Bounds { get; set; }
|
||||
}
|
||||
|
||||
public static class AlphaComponentScanner
|
||||
{
|
||||
public static AlphaComponent[] Scan(string path, int alphaThreshold, int minimumArea)
|
||||
{
|
||||
using (var image = new Bitmap(path))
|
||||
{
|
||||
int width = image.Width;
|
||||
int height = image.Height;
|
||||
var foreground = new bool[width * height];
|
||||
var visited = new bool[width * height];
|
||||
var queue = new int[width * height];
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
int row = y * width;
|
||||
for (int x = 0; x < width; x++)
|
||||
foreground[row + x] = image.GetPixel(x, y).A >= alphaThreshold;
|
||||
}
|
||||
|
||||
var components = new ArrayList();
|
||||
int[] dx = { -1, 0, 1, -1, 1, -1, 0, 1 };
|
||||
int[] dy = { -1, -1, -1, 0, 0, 1, 1, 1 };
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int start = y * width + x;
|
||||
if (visited[start] || !foreground[start]) continue;
|
||||
|
||||
int head = 0, tail = 0, area = 0;
|
||||
int minX = x, minY = y, maxX = x, maxY = y;
|
||||
visited[start] = true;
|
||||
queue[tail++] = start;
|
||||
|
||||
while (head < tail)
|
||||
{
|
||||
int index = queue[head++];
|
||||
int px = index % width;
|
||||
int py = index / width;
|
||||
area++;
|
||||
if (px < minX) minX = px;
|
||||
if (px > maxX) maxX = px;
|
||||
if (py < minY) minY = py;
|
||||
if (py > maxY) maxY = py;
|
||||
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
int nx = px + dx[i];
|
||||
int ny = py + dy[i];
|
||||
if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
|
||||
int next = ny * width + nx;
|
||||
if (visited[next] || !foreground[next]) continue;
|
||||
visited[next] = true;
|
||||
queue[tail++] = next;
|
||||
}
|
||||
}
|
||||
|
||||
if (area >= minimumArea)
|
||||
{
|
||||
components.Add(new AlphaComponent {
|
||||
Area = area,
|
||||
Bounds = Rectangle.FromLTRB(minX, minY, maxX + 1, maxY + 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var result = new AlphaComponent[components.Count];
|
||||
for (int i = 0; i < components.Count; i++) result[i] = (AlphaComponent)components[i];
|
||||
Array.Sort(result, (a, b) => {
|
||||
int rowCompare = a.Bounds.Top.CompareTo(b.Bounds.Top);
|
||||
return rowCompare != 0 ? rowCompare : a.Bounds.Left.CompareTo(b.Bounds.Left);
|
||||
});
|
||||
for (int i = 0; i < result.Length; i++) result[i].Id = i + 1;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
$compilerReferences = @(
|
||||
[System.Drawing.Bitmap].Assembly.Location,
|
||||
[System.Drawing.Color].Assembly.Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.GdiPlus').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Private.Windows.Core').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Collections').Location,
|
||||
[System.Reflection.Assembly]::Load('System.Runtime').Location,
|
||||
[System.Object].Assembly.Location
|
||||
) | Select-Object -Unique
|
||||
Add-Type -TypeDefinition $helperSource -ReferencedAssemblies $compilerReferences
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($InputPath)) {
|
||||
$InputPath = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\source\xinyin-front-right-parts-sheet-v1.png'
|
||||
}
|
||||
elseif (-not [IO.Path]::IsPathRooted($InputPath)) {
|
||||
$InputPath = Join-Path $WorkspaceRoot $InputPath
|
||||
}
|
||||
$InputPath = (Resolve-Path -LiteralPath $InputPath).Path
|
||||
$diagnosticDirectory = Join-Path $WorkspaceRoot 'assets\images\2d-game-characters\02-xinyin\diagnostics'
|
||||
$diagnosticImage = Join-Path $diagnosticDirectory "$OutputStem-components.png"
|
||||
$diagnosticJson = Join-Path $diagnosticDirectory "$OutputStem-components.json"
|
||||
New-Item -ItemType Directory -Force -Path $diagnosticDirectory | Out-Null
|
||||
|
||||
$components = [AlphaComponentScanner]::Scan($InputPath, $AlphaThreshold, $MinimumArea)
|
||||
$source = [Drawing.Bitmap]::new($InputPath)
|
||||
$canvasWidth = $source.Width
|
||||
$canvasHeight = $source.Height
|
||||
$canvas = [Drawing.Bitmap]::new($source.Width, $source.Height, [Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [Drawing.Graphics]::FromImage($canvas)
|
||||
$graphics.Clear([Drawing.Color]::FromArgb(255, 22, 25, 34))
|
||||
$graphics.DrawImageUnscaled($source, 0, 0)
|
||||
$pen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(255, 52, 220, 255), 2)
|
||||
$labelFill = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(230, 8, 12, 19))
|
||||
$labelText = [Drawing.SolidBrush]::new([Drawing.Color]::White)
|
||||
$font = [Drawing.Font]::new('Segoe UI Semibold', 11)
|
||||
|
||||
try {
|
||||
foreach ($component in $components) {
|
||||
$bounds = $component.Bounds
|
||||
$graphics.DrawRectangle($pen, $bounds.X, $bounds.Y, $bounds.Width - 1, $bounds.Height - 1)
|
||||
$label = [string]$component.Id
|
||||
$size = $graphics.MeasureString($label, $font)
|
||||
$labelX = [Math]::Max(0, $bounds.X)
|
||||
$labelY = [Math]::Max(0, $bounds.Y - [int]$size.Height)
|
||||
$graphics.FillRectangle($labelFill, $labelX, $labelY, [int]$size.Width + 8, [int]$size.Height)
|
||||
$graphics.DrawString($label, $font, $labelText, $labelX + 4, $labelY)
|
||||
}
|
||||
$canvas.Save($diagnosticImage, [Drawing.Imaging.ImageFormat]::Png)
|
||||
}
|
||||
finally {
|
||||
$font.Dispose()
|
||||
$labelText.Dispose()
|
||||
$labelFill.Dispose()
|
||||
$pen.Dispose()
|
||||
$graphics.Dispose()
|
||||
$canvas.Dispose()
|
||||
$source.Dispose()
|
||||
}
|
||||
|
||||
$records = foreach ($component in $components) {
|
||||
[ordered]@{
|
||||
id = $component.Id
|
||||
area = $component.Area
|
||||
x = $component.Bounds.X
|
||||
y = $component.Bounds.Y
|
||||
width = $component.Bounds.Width
|
||||
height = $component.Bounds.Height
|
||||
}
|
||||
}
|
||||
[ordered]@{
|
||||
source = $InputPath
|
||||
imageWidth = $canvasWidth
|
||||
imageHeight = $canvasHeight
|
||||
alphaThreshold = $AlphaThreshold
|
||||
minimumArea = $MinimumArea
|
||||
componentCount = $components.Count
|
||||
components = $records
|
||||
} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $diagnosticJson -Encoding utf8
|
||||
|
||||
Write-Output "Detected $($components.Count) alpha components."
|
||||
Write-Output $diagnosticImage
|
||||
Write-Output $diagnosticJson
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,96 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
LEFT = CHARACTER / "assembled/front-right/xinyin-front-right-neutral-assembly-v4.png"
|
||||
RIGHT = CHARACTER / "assembled/front-left/xinyin-front-left-neutral-assembly-v4.png"
|
||||
OUTPUT = CHARACTER / "previews/xinyin-4way-direction-map-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
|
||||
|
||||
def font(size):
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def fit(image, size):
|
||||
result = image.copy()
|
||||
result.thumbnail(size, Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def checker(size, cell=20):
|
||||
image = Image.new("RGB", size, (239, 243, 248))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(219, 226, 234))
|
||||
return image
|
||||
|
||||
|
||||
def paste_character(canvas, path, rect):
|
||||
x0, y0, x1, y1 = rect
|
||||
panel = checker((x1 - x0, y1 - y0))
|
||||
character = fit(Image.open(path).convert("RGBA"), (x1 - x0 - 30, y1 - y0 - 30))
|
||||
panel.paste(character, ((panel.width - character.width) // 2, (panel.height - character.height) // 2), character)
|
||||
canvas.paste(panel, (x0, y0))
|
||||
|
||||
|
||||
def placeholder(draw, rect, arrow, title, subtitle):
|
||||
x0, y0, x1, y1 = rect
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(32, 40, 55), outline=(71, 88, 113), width=2)
|
||||
draw.text(((x0 + x1) // 2, y0 + 36), arrow, font=font(70), fill=(103, 203, 255), anchor="ma")
|
||||
draw.text(((x0 + x1) // 2, y0 + 122), title, font=font(28), fill=(242, 246, 252), anchor="ma")
|
||||
draw.text(((x0 + x1) // 2, y0 + 166), subtitle, font=font(18), fill=(163, 178, 199), anchor="ma")
|
||||
|
||||
|
||||
def main():
|
||||
canvas = Image.new("RGB", (1800, 1160), (18, 23, 32))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252)
|
||||
muted = (163, 178, 199)
|
||||
blue = (103, 203, 255)
|
||||
green = (121, 224, 167)
|
||||
|
||||
draw.text((60, 38), "心音|四方向移动映射 v1", font=font(44), fill=white)
|
||||
draw.text((62, 99), "运行时只使用 up / down / left / right;旧制作目录保留为兼容别名", font=font(22), fill=muted)
|
||||
|
||||
placeholder(draw, (660, 150, 1140, 370), "↑", "UP|向上", "待制作:全新背面母版与分解包")
|
||||
placeholder(draw, (660, 895, 1140, 1115), "↓", "DOWN|向下", "待制作:全新正面母版与分解包")
|
||||
|
||||
left_panel = (65, 270, 565, 970)
|
||||
right_panel = (1235, 270, 1735, 970)
|
||||
for rect in (left_panel, right_panel):
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(32, 40, 55), outline=(71, 88, 113), width=2)
|
||||
draw.text((90, 292), "← LEFT|向左", font=font(29), fill=blue)
|
||||
draw.text((90, 337), "旧目录:front-right", font=font(18), fill=muted)
|
||||
draw.text((90, 368), "状态:动作美术已验证", font=font(18), fill=green)
|
||||
paste_character(canvas, LEFT, (90, 410, 540, 940))
|
||||
|
||||
draw.text((1260, 292), "RIGHT|向右 →", font=font(29), fill=blue)
|
||||
draw.text((1260, 337), "旧目录:front-left", font=font(18), fill=muted)
|
||||
draw.text((1260, 368), "状态:静态美术已验证", font=font(18), fill=green)
|
||||
paste_character(canvas, RIGHT, (1260, 410, 1710, 940))
|
||||
|
||||
draw.rounded_rectangle((615, 410, 1185, 835), radius=18, fill=(27, 34, 47), outline=(71, 88, 113), width=2)
|
||||
draw.text((650, 442), "运行时规则", font=font(28), fill=white)
|
||||
rules = [
|
||||
"1. 取移动输入的主轴决定身体朝向",
|
||||
"2. 斜向临界区保持上一朝向,避免闪烁",
|
||||
"3. 左右独立绘制,禁止水平镜像",
|
||||
"4. 身体四向;投射物与 VFX 可自由角度瞄准",
|
||||
"5. 脚底中心是所有方向的统一原点",
|
||||
]
|
||||
for index, rule in enumerate(rules):
|
||||
draw.text((650, 505 + index * 58), rule, font=font(20), fill=muted)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.save(OUTPUT, quality=95)
|
||||
print(OUTPUT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,316 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
PARTS_DIR = CHARACTER / "parts/down/v1"
|
||||
MANIFEST_PATH = PARTS_DIR / "parts-manifest.json"
|
||||
MASTER_PATH = CHARACTER / "source/down/xinyin-down-neutral-master-v1.png"
|
||||
ASSEMBLED_DIR = CHARACTER / "assembled/down"
|
||||
ASSEMBLY_PATH = ASSEMBLED_DIR / "xinyin-down-neutral-assembly-v1.png"
|
||||
LAYOUT_PATH = ASSEMBLED_DIR / "assembly-layout-v1.json"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-down-assembly-validation-v1.png"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
CANVAS_SIZE = (600, 760)
|
||||
|
||||
|
||||
def item(name, x, y, rotation, scale, group, note):
|
||||
return {
|
||||
"name": name,
|
||||
"x": x,
|
||||
"y": y,
|
||||
"rotation": rotation,
|
||||
"scale": scale,
|
||||
"group": group,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
# Draw order is the list order. X/Y are root-pivot positions on a 600x760 canvas.
|
||||
# DOWN side ownership is frozen: A = screen-left fan side, B = screen-right relaxed side.
|
||||
LAYOUT = [
|
||||
item("ponytail-root", 325, 104, 0, .33, "hair-back", "三段马尾根;位于后脑之后"),
|
||||
item("ponytail-middle", 353, 170, 48, .33, "hair-back", "向画面右侧延伸并与根部内压重叠"),
|
||||
item("ponytail-tip", 405, 273, 48, .33, "hair-back", "末端继续向画面右侧延伸"),
|
||||
item("hair-cap", 300, 205, 0, .55, "hair-back", "后脑发帽;遮盖马尾根接缝"),
|
||||
|
||||
item("coat-panel-01", 205, 358, -14, .74, "cloth-back", "画面左外后层"),
|
||||
item("coat-panel-02", 232, 356, -10, .71, "cloth-back", "画面左后层"),
|
||||
item("coat-panel-03", 260, 357, -6, .71, "cloth-back", "中左后层"),
|
||||
item("coat-panel-04", 282, 358, -2, .71, "cloth-back", "中左层"),
|
||||
item("coat-panel-05", 318, 358, 2, .71, "cloth-back", "中右层"),
|
||||
item("coat-panel-06", 340, 357, 6, .71, "cloth-back", "中右后层"),
|
||||
item("coat-panel-07", 368, 356, 10, .71, "cloth-back", "画面右后层"),
|
||||
item("coat-panel-08", 395, 358, 14, .74, "cloth-back", "画面右外后层"),
|
||||
|
||||
item("thigh-a", 266, 382, -2, .62, "legs", "A 腿髋点;画面左"),
|
||||
item("shin-boot-a", 260, 564, -3, .50, "legs", "A 腿膝点;脚底基线候选"),
|
||||
item("thigh-b", 334, 382, 2, .62, "legs", "B 腿髋点;画面右"),
|
||||
item("shin-boot-b", 340, 563, 3, .50, "legs", "B 腿膝点;脚底基线候选"),
|
||||
|
||||
item("outer-sleeve-cape-a", 226, 241, -10, .34, "arms-back", "持扇手侧独立外袖披"),
|
||||
item("outer-sleeve-cape-b", 374, 241, 10, .34, "arms-back", "放松手侧独立外袖披"),
|
||||
item("upper-arm-a", 226, 241, -10, .33, "arms-back", "A 上臂;肩到肘"),
|
||||
item("forearm-a", 219, 289, -154, .38, "arms-back", "A 前臂;肘点与上臂末端内压重叠"),
|
||||
item("hand-fan-grip-a", 182, 214, -7, .28, "weapon", "A 持扇手;腕点与前臂末端内压重叠"),
|
||||
item("upper-arm-b", 374, 241, 10, .33, "arms-back", "B 上臂;肩到肘"),
|
||||
item("forearm-b", 381, 289, 6, .38, "arms-back", "B 前臂;肘点与上臂末端内压重叠"),
|
||||
item("hand-relaxed-b", 390, 372, 5, .28, "arms-back", "B 放松手;腕点与前臂末端内压重叠"),
|
||||
|
||||
item("torso-upper", 300, 360, 0, .60, "body", "躯干根位于腰线"),
|
||||
item("pelvis-hip-core", 300, 359, 0, .60, "body-overlay", "腰封、骨盆与中性腰饰"),
|
||||
item("shoulder-armor-a", 228, 237, -10, .30, "body-overlay", "画面左持扇侧肩甲"),
|
||||
item("shoulder-armor-b", 372, 237, 10, .30, "body-overlay", "画面右放松侧肩甲"),
|
||||
item("neck", 300, 220, 0, .50, "body-overlay", "颈部连接"),
|
||||
item("head-face", 300, 215, 0, .52, "head", "严格正面头部与面部"),
|
||||
item("hair-front", 300, 114, 0, .57, "head-overlay", "前发与双侧鬓发"),
|
||||
item("hair-ornament-long", 348, 112, 3, .46, "head-overlay", "母版画面右侧长银花发饰"),
|
||||
]
|
||||
|
||||
|
||||
EXCLUDED = {
|
||||
"coat-panel-alt-09": "九选八中的动作替换候选",
|
||||
"front-drape": "pelvis-hip-core 已含中性腰前布与系绳",
|
||||
"waist-pouch": "pelvis-hip-core 已含画面右侧腰包",
|
||||
"red-tassel-a": "中性站姿不重复叠加动作替换流苏",
|
||||
"red-tassel-b": "中性站姿不重复叠加动作替换流苏",
|
||||
"hand-throw-open-a": "投掷动作替换手",
|
||||
"weapon-fan-open": "hand-fan-grip-a 已包含中性持握羽扇",
|
||||
"weapon-blade-single": "投掷物,不用于中性持握",
|
||||
"weapon-double-feather": "攻击替换物,不用于中性持握",
|
||||
}
|
||||
|
||||
|
||||
def transform_about_pivot(image: Image.Image, pivot, scale: float, angle: float):
|
||||
resized = image.resize(
|
||||
(max(1, round(image.width * scale)), max(1, round(image.height * scale))),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
pivot_x, pivot_y = pivot[0] * scale, pivot[1] * scale
|
||||
side = int(math.ceil(math.hypot(resized.width, resized.height) * 2 + 20))
|
||||
center = side // 2
|
||||
local = Image.new("RGBA", (side, side), (0, 0, 0, 0))
|
||||
local.alpha_composite(resized, (round(center - pivot_x), round(center - pivot_y)))
|
||||
if angle:
|
||||
local = local.rotate(angle, resample=Image.Resampling.BICUBIC, center=(center, center))
|
||||
return local, center
|
||||
|
||||
|
||||
def paste_part(canvas, image, pivot, target, scale, angle):
|
||||
transformed, center = transform_about_pivot(image, pivot, scale, angle)
|
||||
canvas.alpha_composite(
|
||||
transformed,
|
||||
(round(target[0] - center), round(target[1] - center)),
|
||||
)
|
||||
|
||||
|
||||
def render_single(image, pivot, entry):
|
||||
result = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
paste_part(
|
||||
result,
|
||||
image,
|
||||
pivot,
|
||||
(entry["x"], entry["y"]),
|
||||
entry["scale"],
|
||||
entry["rotation"],
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def checker(size, cell=24):
|
||||
result = Image.new("RGB", size, (238, 242, 247))
|
||||
draw = ImageDraw.Draw(result)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(217, 224, 232))
|
||||
return result
|
||||
|
||||
|
||||
def fit(image, size, margin=0):
|
||||
result = image.copy()
|
||||
result.thumbnail(
|
||||
(size[0] - margin * 2, size[1] - margin * 2),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
by_name = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {
|
||||
name: Image.open(PARTS_DIR / record["file"]).convert("RGBA")
|
||||
for name, record in by_name.items()
|
||||
}
|
||||
layout_names = {entry["name"] for entry in LAYOUT}
|
||||
all_names = set(by_name)
|
||||
if layout_names | set(EXCLUDED) != all_names:
|
||||
missing = sorted(all_names - layout_names - set(EXCLUDED))
|
||||
unknown = sorted(layout_names | set(EXCLUDED) - all_names)
|
||||
raise ValueError(f"Part accounting mismatch. missing={missing}, unknown={unknown}")
|
||||
|
||||
assembly = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
records = []
|
||||
entry_by_name = {entry["name"]: entry for entry in LAYOUT}
|
||||
for entry in LAYOUT:
|
||||
record = by_name[entry["name"]]
|
||||
pivot_record = record["rootPivot"]["outputPixels"]
|
||||
pivot = (pivot_record["x"], pivot_record["y"])
|
||||
paste_part(
|
||||
assembly,
|
||||
images[entry["name"]],
|
||||
pivot,
|
||||
(entry["x"], entry["y"]),
|
||||
entry["scale"],
|
||||
entry["rotation"],
|
||||
)
|
||||
records.append({
|
||||
"part": entry["name"],
|
||||
"file": f"assets/images/2d-game-characters/02-xinyin/parts/down/v1/{record['file']}",
|
||||
"targetPivot": {"x": entry["x"], "y": entry["y"]},
|
||||
"rotationDegrees": entry["rotation"],
|
||||
"scale": entry["scale"],
|
||||
"group": entry["group"],
|
||||
"note": entry["note"],
|
||||
})
|
||||
|
||||
ASSEMBLED_DIR.mkdir(parents=True, exist_ok=True)
|
||||
assembly.save(ASSEMBLY_PATH)
|
||||
alpha = assembly.getchannel("A")
|
||||
visible_bbox = alpha.getbbox()
|
||||
edge_clear = not any((
|
||||
alpha.crop((0, 0, CANVAS_SIZE[0], 1)).getbbox(),
|
||||
alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])).getbbox(),
|
||||
alpha.crop((0, 0, 1, CANVAS_SIZE[1])).getbbox(),
|
||||
alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])).getbbox(),
|
||||
))
|
||||
|
||||
baselines = {}
|
||||
for name in ("shin-boot-a", "shin-boot-b"):
|
||||
entry = entry_by_name[name]
|
||||
record = by_name[name]
|
||||
pivot_record = record["rootPivot"]["outputPixels"]
|
||||
single = render_single(
|
||||
images[name],
|
||||
(pivot_record["x"], pivot_record["y"]),
|
||||
entry,
|
||||
)
|
||||
bbox = single.getchannel("A").getbbox()
|
||||
baselines[name] = bbox[3] - 1 if bbox else None
|
||||
|
||||
layout_manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "down",
|
||||
"version": 1,
|
||||
"status": "art-assembly-validated",
|
||||
"canvas": {
|
||||
"width": CANVAS_SIZE[0],
|
||||
"height": CANVAS_SIZE[1],
|
||||
"origin": "top-left",
|
||||
"units": "pixels",
|
||||
"footOrigin": {"x": CANVAS_SIZE[0] // 2, "y": max(baselines.values())},
|
||||
},
|
||||
"sideConvention": manifest["sideConvention"],
|
||||
"sourceManifests": [
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/down/v1/parts-manifest.json"
|
||||
],
|
||||
"items": records,
|
||||
"excludedParts": EXCLUDED,
|
||||
"validation": {
|
||||
"usedPartCount": len(records),
|
||||
"excludedPartCount": len(EXCLUDED),
|
||||
"allPartsAccountedFor": len(records) + len(EXCLUDED) == manifest["partCount"],
|
||||
"visibleAlphaBounds": {
|
||||
"x": visible_bbox[0],
|
||||
"y": visible_bbox[1],
|
||||
"width": visible_bbox[2] - visible_bbox[0],
|
||||
"height": visible_bbox[3] - visible_bbox[1],
|
||||
},
|
||||
"edgeTransparent": edge_clear,
|
||||
"leftBootBaselineY": baselines["shin-boot-a"],
|
||||
"rightBootBaselineY": baselines["shin-boot-b"],
|
||||
"baselineDeltaPixels": abs(
|
||||
baselines["shin-boot-a"] - baselines["shin-boot-b"]
|
||||
),
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side assembly candidate, not an engine rig.",
|
||||
"A/B ownership is frozen for DOWN and must not be mirrored.",
|
||||
"The pelvis core already contains neutral waist cloth, cords, tassels, and the side pouch; standalone waist pieces remain action replacements.",
|
||||
"The three-part ponytail chain is validated for the neutral pose; rotation extremes still require motion validation.",
|
||||
],
|
||||
}
|
||||
LAYOUT_PATH.write_text(
|
||||
json.dumps(layout_manifest, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
board = Image.new("RGB", (1920, 980), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
panel_font = ImageFont.truetype(str(FONT_PATH), 25)
|
||||
text_font = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
muted = (151, 169, 198)
|
||||
draw.text((42, 24), "心音|DOWN 正面中性站姿装配验证 v1", font=title, fill=(240, 244, 252))
|
||||
draw.text((44, 78), "冻结母版 / 41 件中的 32 件中性选择 / 正面枢轴、层级与双脚基线", font=text_font, fill=muted)
|
||||
|
||||
panel_rects = [(42, 122, 622, 930), (654, 122, 1234, 930), (1266, 122, 1878, 930)]
|
||||
for rect in panel_rects:
|
||||
draw.rounded_rectangle(rect, radius=16, fill=(24, 30, 42), outline=(65, 82, 112), width=2)
|
||||
draw.text((62, 142), "A 冻结的 DOWN 母版", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((674, 142), "B 32 件部件重建", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((1286, 142), "C 枢轴、侧别与基线", font=panel_font, fill=(240, 244, 252))
|
||||
|
||||
master = fit(Image.open(MASTER_PATH).convert("RGBA"), (530, 720), 18)
|
||||
master_bg = checker((530, 720))
|
||||
master_bg.paste(master, ((530 - master.width) // 2, (720 - master.height) // 2), master)
|
||||
board.paste(master_bg, (67, 190))
|
||||
|
||||
assembly_bg = checker(CANVAS_SIZE)
|
||||
assembly_bg.paste(assembly, (0, 0), assembly)
|
||||
display = fit(assembly_bg, (540, 740))
|
||||
board.paste(display, (674 + (540 - display.width) // 2, 180))
|
||||
board.paste(display, (1302 + (540 - display.width) // 2, 180))
|
||||
|
||||
# Skeleton positions in the third panel follow the scaled 600x760 assembly display.
|
||||
ox, oy = 1302, 180
|
||||
sx = display.width / CANVAS_SIZE[0]
|
||||
sy = display.height / CANVAS_SIZE[1]
|
||||
def pt(x, y):
|
||||
return (round(ox + x * sx), round(oy + y * sy))
|
||||
|
||||
overlay = ImageDraw.Draw(board)
|
||||
chains = [
|
||||
[pt(300, 90), pt(300, 215), pt(300, 360)],
|
||||
[pt(228, 237), pt(219, 289), pt(182, 214)],
|
||||
[pt(372, 237), pt(381, 289), pt(390, 372)],
|
||||
[pt(300, 359), pt(266, 382), pt(260, 563), pt(260, baselines["shin-boot-a"])],
|
||||
[pt(300, 359), pt(334, 382), pt(340, 563), pt(340, baselines["shin-boot-b"])],
|
||||
]
|
||||
for chain in chains:
|
||||
for start, end in zip(chain, chain[1:]):
|
||||
overlay.line((*start, *end), fill=(69, 211, 255), width=4)
|
||||
for x, y in chain:
|
||||
overlay.ellipse((x - 6, y - 6, x + 6, y + 6), outline=(255, 87, 115), width=3)
|
||||
baseline_y = pt(300, max(baselines.values()))[1]
|
||||
overlay.line((1318, baseline_y, 1826, baseline_y), fill=(255, 204, 75), width=3)
|
||||
draw.text((1286, 853), f"A/B 固定:画面左持扇,画面右放松|脚底差 {abs(baselines['shin-boot-a'] - baselines['shin-boot-b'])} px", font=text_font, fill=(240, 244, 252))
|
||||
draw.text((1286, 883), "腰部替换件不重复叠加;三段马尾与八片衣摆进入动作极限测试。", font=text_font, fill=muted)
|
||||
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
print(ASSEMBLY_PATH)
|
||||
print(LAYOUT_PATH)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(layout_manifest["validation"], ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
GENERATED = ASSET_ROOT / "source/down/xinyin-down-neutral-master-generation-v1.png"
|
||||
MASTER = ASSET_ROOT / "source/down/xinyin-down-neutral-master-v1.png"
|
||||
MANIFEST = ASSET_ROOT / "source/down/master-manifest-v1.json"
|
||||
TURNAROUND = ASSET_ROOT / "previews/xinyin-4dir-turnaround-v1.png"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-down-master-validation-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
MASTER_SIZE = (1152, 1664)
|
||||
MASTER_OFFSET = (64, 64)
|
||||
|
||||
|
||||
def font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def checker(size: tuple[int, int], cell: int = 24) -> Image.Image:
|
||||
image = Image.new("RGBA", size, (240, 244, 248, 255))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(220, 226, 233, 255))
|
||||
return image
|
||||
|
||||
|
||||
def contain(image: Image.Image, box: tuple[int, int], margin: int = 0) -> Image.Image:
|
||||
result = image.copy()
|
||||
result.thumbnail((box[0] - margin * 2, box[1] - margin * 2), Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def paste_center(canvas: Image.Image, image: Image.Image, rect: tuple[int, int, int, int]) -> None:
|
||||
x0, y0, x1, y1 = rect
|
||||
canvas.alpha_composite(image, (x0 + (x1 - x0 - image.width) // 2, y0 + (y1 - y0 - image.height) // 2))
|
||||
|
||||
|
||||
def alpha_edges_clear(alpha: Image.Image) -> bool:
|
||||
width, height = alpha.size
|
||||
edges = (
|
||||
alpha.crop((0, 0, width, 1)),
|
||||
alpha.crop((0, height - 1, width, height)),
|
||||
alpha.crop((0, 0, 1, height)),
|
||||
alpha.crop((width - 1, 0, width, height)),
|
||||
)
|
||||
return all(edge.getbbox() is None for edge in edges)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
generated = Image.open(GENERATED).convert("RGBA")
|
||||
master = Image.new("RGBA", MASTER_SIZE, (0, 0, 0, 0))
|
||||
master.alpha_composite(generated, MASTER_OFFSET)
|
||||
MASTER.parent.mkdir(parents=True, exist_ok=True)
|
||||
master.save(MASTER)
|
||||
|
||||
alpha = master.getchannel("A")
|
||||
bbox = alpha.getbbox()
|
||||
if bbox is None:
|
||||
raise ValueError("DOWN master is fully transparent")
|
||||
visible = master.crop(bbox)
|
||||
|
||||
turnaround = Image.open(TURNAROUND).convert("RGBA")
|
||||
old_reference = turnaround.crop((0, 0, turnaround.width // 4, turnaround.height))
|
||||
|
||||
canvas = Image.new("RGBA", (1800, 1100), (25, 31, 43, 255))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252, 255)
|
||||
muted = (172, 184, 201, 255)
|
||||
blue = (104, 196, 255, 255)
|
||||
red = (255, 124, 124, 255)
|
||||
green = (124, 223, 166, 255)
|
||||
|
||||
draw.text((70, 42), "心音|运行时 DOWN 正面母版校验 v1", font=font(42), fill=white)
|
||||
draw.text((72, 98), "严格正面 · 约 4.75 头身 · 固定角色右手持扇 · 透明高分辨率母版", font=font(22), fill=muted)
|
||||
|
||||
panels = [(60, 160, 535, 890), (570, 160, 1110, 890), (1145, 160, 1740, 890)]
|
||||
titles = ["A 旧斜向造型参考", "B DOWN 正面母版 v1", "C 三档游戏轮廓检查"]
|
||||
for rect, title in zip(panels, titles):
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(39, 48, 64, 255), outline=(72, 87, 109, 255), width=2)
|
||||
draw.text((rect[0] + 24, rect[1] + 20), title, font=font(24), fill=white)
|
||||
|
||||
ref = contain(old_reference, (427, 632), margin=8)
|
||||
paste_center(canvas, ref, (84, 218, 511, 850))
|
||||
|
||||
master_box = (594, 218, 1086, 850)
|
||||
canvas.alpha_composite(checker((master_box[2] - master_box[0], master_box[3] - master_box[1])), (master_box[0], master_box[1]))
|
||||
master_large = contain(visible, (master_box[2] - master_box[0], master_box[3] - master_box[1]), margin=18)
|
||||
paste_center(canvas, master_large, master_box)
|
||||
|
||||
scale_specs = [
|
||||
(352, "工作缩放 352 px", 1210, 240, (1180, 222, 1710, 610), (1450, 390)),
|
||||
(176, "游戏基准 176 px", 1210, 650, (1180, 630, 1445, 850), (1190, 610)),
|
||||
(88, "50% 检查 88 px", 1510, 730, (1470, 700, 1710, 850), (1478, 665)),
|
||||
]
|
||||
for height, label, x, y, background, label_pos in scale_specs:
|
||||
width = max(1, round(visible.width * height / visible.height))
|
||||
resized = visible.resize((width, height), Image.Resampling.LANCZOS)
|
||||
draw.rounded_rectangle(background, radius=12, fill=(31, 39, 53, 255))
|
||||
canvas.alpha_composite(resized, (x, y))
|
||||
draw.text(label_pos, label, font=font(21), fill=white)
|
||||
|
||||
draw.rounded_rectangle((60, 925, 1740, 1045), radius=16, fill=(34, 42, 57, 255))
|
||||
draw.text((88, 946), "冻结关系:", font=font(24), fill=white)
|
||||
draw.text((245, 946), "角色右手/画面左侧持扇", font=font(24), fill=blue)
|
||||
draw.text((570, 946), "腰包与放松手在画面右侧", font=font(24), fill=red)
|
||||
draw.text((936, 946), "头胸骨盆严格朝前", font=font(24), fill=green)
|
||||
draw.text((88, 992), "高马尾与外衣允许轮廓不对称;双脚基线和身体主轴保持对称,供后续分解与四向切换使用。", font=font(20), fill=muted)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.convert("RGB").save(OUTPUT, quality=95)
|
||||
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "down",
|
||||
"version": 1,
|
||||
"status": "master-art-validated",
|
||||
"master": MASTER.relative_to(ROOT).as_posix(),
|
||||
"generationSource": GENERATED.relative_to(ROOT).as_posix(),
|
||||
"canvas": {"width": master.width, "height": master.height, "origin": "top-left", "units": "pixels"},
|
||||
"visibleAlphaBounds": {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]},
|
||||
"validation": {
|
||||
"edgeTransparent": alpha_edges_clear(alpha),
|
||||
"strictFrontFacing": True,
|
||||
"targetHeadRatio": 4.75,
|
||||
"scaleChecks": [352, 176, 88],
|
||||
"weaponSide": "character-right / screen-left",
|
||||
"pouchSide": "character-left / screen-right",
|
||||
"footOrigin": "bottom-center",
|
||||
},
|
||||
"referenceRoles": [
|
||||
{"file": "assets/images/characters/cards/汐月心音:银月刺客卡.png", "role": "identity, face, costume, palette, accessories"},
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/previews/xinyin-4dir-turnaround-v1.png", "role": "legacy asymmetry and styling reference only"},
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-neutral-master-v2.png", "role": "approved light-chibi proportion and rendering reference"},
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/assembled/front-right/xinyin-front-right-neutral-assembly-v4.png", "role": "approved gameplay silhouette and detail-density reference"},
|
||||
],
|
||||
"notes": [
|
||||
"The generation result is preserved separately; the production master adds a 64 px transparent safety margin.",
|
||||
"DOWN is a new strict-front direction and is not mirrored or relabeled from either legacy diagonal direction.",
|
||||
"This master is ready for source-sheet decomposition, but is not yet a runtime rig or sprite sequence.",
|
||||
],
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(MASTER)
|
||||
print(MANIFEST)
|
||||
print(OUTPUT)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,402 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
TOOLS_DIR = ROOT / "tools"
|
||||
if str(TOOLS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(TOOLS_DIR))
|
||||
|
||||
from build_xinyin_down_assembly import ( # noqa: E402
|
||||
FONT_PATH,
|
||||
LAYOUT,
|
||||
MANIFEST_PATH,
|
||||
PARTS_DIR,
|
||||
paste_part,
|
||||
)
|
||||
|
||||
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
OUTPUT_DIR = CHARACTER / "motion/down/v1"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-down-motion-validation-v1.png"
|
||||
CANVAS_SIZE = (600, 760)
|
||||
|
||||
|
||||
FRAME_SPECS = [
|
||||
{
|
||||
"name": "idle-inhale",
|
||||
"label": "IDLE · INHALE",
|
||||
"durationMs": 420,
|
||||
"note": "胸腔与头部轻微上提;双臂随肩上移,右后方马尾略晚跟随。",
|
||||
"body_y": -3,
|
||||
"head_y": -4,
|
||||
"hair": (1, 45, 44),
|
||||
"arm": (-10, -153),
|
||||
"cape": -9,
|
||||
"coat": (-2, 2),
|
||||
},
|
||||
{
|
||||
"name": "idle-neutral",
|
||||
"label": "IDLE · NEUTRAL",
|
||||
"durationMs": 260,
|
||||
"note": "DOWN 装配 v1 的固定正面基准姿势。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"hair": (0, 48, 48),
|
||||
"arm": (-10, -154),
|
||||
"cape": -10,
|
||||
"coat": (0, 0),
|
||||
},
|
||||
{
|
||||
"name": "idle-exhale",
|
||||
"label": "IDLE · EXHALE",
|
||||
"durationMs": 420,
|
||||
"note": "胸腔与头部下沉;软性部件收回,双脚基线保持不动。",
|
||||
"body_y": 2,
|
||||
"head_y": 3,
|
||||
"hair": (-1, 51, 53),
|
||||
"arm": (-11, -155),
|
||||
"cape": -11,
|
||||
"coat": (2, -2),
|
||||
},
|
||||
{
|
||||
"name": "throw-ready",
|
||||
"label": "THROW · READY",
|
||||
"durationMs": 150,
|
||||
"note": "画面左侧持扇手上提,身体主轴仍保持正面。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"torso_rotation": -1,
|
||||
"hair": (1, 45, 43),
|
||||
"arm": (-22, -151),
|
||||
"cape": -22,
|
||||
"coat": (-2, 3),
|
||||
},
|
||||
{
|
||||
"name": "throw-windup",
|
||||
"label": "THROW · WINDUP",
|
||||
"durationMs": 110,
|
||||
"note": "持扇臂收至头侧蓄势;右后方马尾与衣摆反向压缩。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": 3,
|
||||
"head_rotation": 1,
|
||||
"hair": (3, 40, 36),
|
||||
"arm": (-30, 170),
|
||||
"cape": -28,
|
||||
"coat": (-5, 5),
|
||||
},
|
||||
{
|
||||
"name": "throw-release",
|
||||
"label": "THROW · RELEASE",
|
||||
"durationMs": 90,
|
||||
"note": "身体保持正面,持扇臂向画面左侧完全展开;张手和单枚脱手羽刃替换中性持握。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": -3,
|
||||
"head_rotation": -1,
|
||||
"hair": (5, 56, 62),
|
||||
"arm": (-90, -90),
|
||||
"cape": -78,
|
||||
"coat": (6, -6),
|
||||
"release": True,
|
||||
},
|
||||
{
|
||||
"name": "throw-recover",
|
||||
"label": "THROW · RECOVER",
|
||||
"durationMs": 180,
|
||||
"note": "手臂回收;马尾与衣摆越过中位后准备回到待机。",
|
||||
"body_y": 1,
|
||||
"head_y": 1,
|
||||
"torso_rotation": -1,
|
||||
"head_rotation": 1,
|
||||
"hair": (-3, 54, 58),
|
||||
"arm": (-38, -151),
|
||||
"cape": -34,
|
||||
"coat": (3, -4),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def rotated_joint(record, target, scale, angle):
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
next_joint = record["nextJoint"]["outputPixels"]
|
||||
dx = (next_joint["x"] - root["x"]) * scale
|
||||
dy = (next_joint["y"] - root["y"]) * scale
|
||||
radians = math.radians(angle)
|
||||
return (
|
||||
target[0] + math.cos(radians) * dx + math.sin(radians) * dy,
|
||||
target[1] - math.sin(radians) * dx + math.cos(radians) * dy,
|
||||
)
|
||||
|
||||
|
||||
def load_parts():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
records = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {
|
||||
name: Image.open(PARTS_DIR / record["file"]).convert("RGBA")
|
||||
for name, record in records.items()
|
||||
}
|
||||
return records, images
|
||||
|
||||
|
||||
def build_transforms(spec, records):
|
||||
transforms = {entry["name"]: copy.deepcopy(entry) for entry in LAYOUT}
|
||||
body_y = spec.get("body_y", 0)
|
||||
head_y = spec.get("head_y", 0)
|
||||
torso_rotation = spec.get("torso_rotation", 0)
|
||||
head_rotation = spec.get("head_rotation", 0)
|
||||
|
||||
# The pelvis and legs remain locked to the ground. Breathing occurs above the waist.
|
||||
transforms["torso-upper"]["y"] += body_y
|
||||
transforms["torso-upper"]["rotation"] += torso_rotation
|
||||
for name in ("shoulder-armor-a", "shoulder-armor-b"):
|
||||
transforms[name]["y"] += body_y
|
||||
for name in ("neck", "head-face", "hair-front", "hair-ornament-long"):
|
||||
transforms[name]["y"] += head_y
|
||||
for name in ("head-face", "hair-front", "hair-ornament-long"):
|
||||
transforms[name]["rotation"] += head_rotation
|
||||
|
||||
left_coat_delta, right_coat_delta = spec["coat"]
|
||||
for index in range(1, 5):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += left_coat_delta * (5 - index) / 4
|
||||
for index in range(5, 9):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += right_coat_delta * (index - 4) / 4
|
||||
|
||||
# Relaxed B arm follows the breathing motion but does not participate in the throw.
|
||||
for name in ("outer-sleeve-cape-b", "upper-arm-b", "forearm-b", "hand-relaxed-b"):
|
||||
transforms[name]["y"] += body_y
|
||||
transforms["outer-sleeve-cape-b"]["rotation"] += torso_rotation * 0.5
|
||||
transforms["upper-arm-b"]["rotation"] += torso_rotation * 0.5
|
||||
|
||||
# Preserve the overlap offsets validated by the neutral assembly while adding lag.
|
||||
root_angle, middle_angle, tip_angle = spec["hair"]
|
||||
hair_root = transforms["ponytail-root"]
|
||||
hair_root["x"] += torso_rotation * 0.7
|
||||
hair_root["y"] += head_y
|
||||
hair_root["rotation"] = root_angle
|
||||
hair_middle = transforms["ponytail-middle"]
|
||||
hair_middle["x"] += torso_rotation * 1.2
|
||||
hair_middle["y"] += head_y * 0.7
|
||||
hair_middle["rotation"] = middle_angle
|
||||
hair_tip = transforms["ponytail-tip"]
|
||||
hair_tip["x"] += torso_rotation * 2.0
|
||||
hair_tip["y"] += head_y * 0.4
|
||||
hair_tip["rotation"] = tip_angle
|
||||
|
||||
upper_rotation, forearm_rotation = spec["arm"]
|
||||
shoulder = (226 + torso_rotation * 0.8, 241 + body_y)
|
||||
upper = transforms["upper-arm-a"]
|
||||
upper.update({"x": shoulder[0], "y": shoulder[1], "rotation": upper_rotation})
|
||||
elbow_joint = rotated_joint(records["upper-arm-a"], shoulder, upper["scale"], upper_rotation)
|
||||
elbow = (elbow_joint[0] + 2, elbow_joint[1] - 4)
|
||||
forearm = transforms["forearm-a"]
|
||||
forearm_scale = 0.34 if spec.get("release") else 0.38
|
||||
forearm.update({"x": elbow[0], "y": elbow[1], "rotation": forearm_rotation, "scale": forearm_scale})
|
||||
wrist = rotated_joint(records["forearm-a"], elbow, forearm_scale, forearm_rotation)
|
||||
hand = transforms["hand-fan-grip-a"]
|
||||
hand.update({"x": wrist[0], "y": wrist[1], "rotation": forearm_rotation + 147})
|
||||
cape = transforms["outer-sleeve-cape-a"]
|
||||
cape.update({"x": shoulder[0], "y": shoulder[1], "rotation": spec["cape"]})
|
||||
|
||||
if spec.get("release"):
|
||||
hand["visible"] = False
|
||||
return transforms, shoulder, elbow, wrist
|
||||
|
||||
|
||||
def serializable_transform(name, transform):
|
||||
return {
|
||||
"Name": name,
|
||||
"X": round(transform["x"], 2),
|
||||
"Y": round(transform["y"], 2),
|
||||
"Rotation": round(transform["rotation"], 2),
|
||||
"Scale": transform["scale"],
|
||||
"Visible": transform.get("visible", True),
|
||||
}
|
||||
|
||||
|
||||
def render_frame(spec, records, images):
|
||||
transforms, shoulder, elbow, wrist = build_transforms(spec, records)
|
||||
canvas = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
serialized = []
|
||||
for entry in LAYOUT:
|
||||
name = entry["name"]
|
||||
transform = transforms[name]
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
if not transform.get("visible", True):
|
||||
continue
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(
|
||||
canvas,
|
||||
images[name],
|
||||
(pivot["x"], pivot["y"]),
|
||||
(transform["x"], transform["y"]),
|
||||
transform["scale"],
|
||||
transform["rotation"],
|
||||
)
|
||||
|
||||
if spec.get("release"):
|
||||
open_hand = {
|
||||
"x": wrist[0],
|
||||
"y": wrist[1],
|
||||
"rotation": -95,
|
||||
"scale": 0.27,
|
||||
"visible": True,
|
||||
}
|
||||
blade = {
|
||||
"x": max(24, wrist[0] - 68),
|
||||
"y": wrist[1] - 8,
|
||||
"rotation": -90,
|
||||
"scale": 0.32,
|
||||
"visible": True,
|
||||
}
|
||||
for name, transform in (("weapon-blade-single", blade), ("hand-throw-open-a", open_hand)):
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(
|
||||
canvas,
|
||||
images[name],
|
||||
(pivot["x"], pivot["y"]),
|
||||
(transform["x"], transform["y"]),
|
||||
transform["scale"],
|
||||
transform["rotation"],
|
||||
)
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
|
||||
joints = {
|
||||
"Shoulder": [round(shoulder[0], 2), round(shoulder[1], 2)],
|
||||
"Elbow": [round(elbow[0], 2), round(elbow[1], 2)],
|
||||
"Wrist": [round(wrist[0], 2), round(wrist[1], 2)],
|
||||
}
|
||||
return canvas, serialized, joints
|
||||
|
||||
|
||||
def checker(size, cell=18):
|
||||
image = Image.new("RGB", size, (235, 239, 245))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(215, 222, 231))
|
||||
return image
|
||||
|
||||
|
||||
def make_preview(frames):
|
||||
board = Image.new("RGB", (1560, 1050), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
label_font = ImageFont.truetype(str(FONT_PATH), 21)
|
||||
note_font = ImageFont.truetype(str(FONT_PATH), 17)
|
||||
draw.text((42, 25), "心音|运行时 DOWN 动作验证 v1", font=title_font, fill=(242, 246, 252))
|
||||
draw.text((44, 78), "严格正面身体 · 固定脚底基线 · 待机呼吸 3 帧 + 向画面左侧投掷 4 帧", font=note_font, fill=(151, 169, 198))
|
||||
cells = [(42 + 378 * col, 120 + 455 * row) for row in range(2) for col in range(4)]
|
||||
for (spec, frame), (x, y) in zip(frames, cells):
|
||||
draw.rounded_rectangle((x, y, x + 352, y + 425), radius=14, fill=(25, 31, 43), outline=(65, 82, 112), width=2)
|
||||
draw.text((x + 16, y + 13), spec["label"], font=label_font, fill=(241, 245, 252))
|
||||
preview = frame.copy()
|
||||
preview.thumbnail((324, 346), Image.Resampling.LANCZOS)
|
||||
bg = checker((324, 346))
|
||||
bg.paste(preview, ((324 - preview.width) // 2, (346 - preview.height) // 2), preview)
|
||||
board.paste(bg, (x + 14, y + 52))
|
||||
draw.text((x + 16, y + 402), f"{spec['durationMs']} ms", font=note_font, fill=(151, 169, 198))
|
||||
draw.text((1176, 590), "验证重点", font=label_font, fill=(241, 245, 252))
|
||||
notes = [
|
||||
"• 身体主轴保持正面,不借侧身强化动作",
|
||||
"• 双脚与地面原点在全部帧中锁定",
|
||||
"• A 手臂按肩—肘—腕链自动连接",
|
||||
"• 释放帧使用张手与单枚脱手羽刃替换件",
|
||||
]
|
||||
for index, note in enumerate(notes):
|
||||
draw.text((1178, 635 + index * 36), note, font=note_font, fill=(174, 188, 211))
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
|
||||
|
||||
def main():
|
||||
records, images = load_parts()
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
frames = []
|
||||
manifest_frames = []
|
||||
baselines = []
|
||||
bounds = []
|
||||
edge_transparent = True
|
||||
for spec in FRAME_SPECS:
|
||||
frame, transforms, joints = render_frame(spec, records, images)
|
||||
frame_path = OUTPUT_DIR / f"{spec['name']}.png"
|
||||
frame.save(frame_path)
|
||||
frames.append((spec, frame))
|
||||
bbox = frame.getchannel("A").getbbox()
|
||||
if bbox is None:
|
||||
raise ValueError(f"Frame {spec['name']} is fully transparent")
|
||||
bounds.append(bbox)
|
||||
baselines.append(bbox[3] - 1)
|
||||
alpha = frame.getchannel("A")
|
||||
edges = [
|
||||
alpha.crop((0, 0, CANVAS_SIZE[0], 1)),
|
||||
alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])),
|
||||
alpha.crop((0, 0, 1, CANVAS_SIZE[1])),
|
||||
alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])),
|
||||
]
|
||||
edge_transparent = edge_transparent and all(edge.getbbox() is None for edge in edges)
|
||||
manifest_frames.append({
|
||||
"name": spec["name"],
|
||||
"label": spec["label"],
|
||||
"file": frame_path.name,
|
||||
"durationMs": spec["durationMs"],
|
||||
"note": spec["note"],
|
||||
"joints": joints,
|
||||
"transforms": transforms,
|
||||
})
|
||||
|
||||
make_preview(frames)
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "down",
|
||||
"runtimeDirection": "down",
|
||||
"version": 1,
|
||||
"status": "art-motion-validated",
|
||||
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels"},
|
||||
"baseLayout": "assets/images/2d-game-characters/02-xinyin/assembled/down/assembly-layout-v1.json",
|
||||
"sourceManifests": [
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/down/v1/parts-manifest.json"
|
||||
],
|
||||
"sequence": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral", "throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"],
|
||||
"loopNotes": {
|
||||
"idle": "inhale → neutral → exhale → neutral",
|
||||
"throw": "ready → windup → release → recover",
|
||||
},
|
||||
"frames": manifest_frames,
|
||||
"validation": {
|
||||
"edgeTransparent": edge_transparent,
|
||||
"baselineYByFrame": dict(zip((spec["name"] for spec in FRAME_SPECS), baselines)),
|
||||
"baselineDeltaPixels": max(baselines) - min(baselines),
|
||||
"visibleAlphaBoundsByFrame": {
|
||||
spec["name"]: {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]}
|
||||
for spec, bbox in zip(FRAME_SPECS, bounds)
|
||||
},
|
||||
"jointChains": [
|
||||
"upper-arm-a → forearm-a → hand",
|
||||
"ponytail-root / ponytail-middle / ponytail-tip with neutral-overlap offsets",
|
||||
],
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side motion validation set, not an engine animation resource.",
|
||||
"DOWN keeps the torso front-facing while the fan-side arm releases toward screen-left for readability.",
|
||||
"Projectile and VFX aim remain free-angle at runtime; the body animation is four-cardinal.",
|
||||
],
|
||||
}
|
||||
manifest_path = OUTPUT_DIR / "motion-manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(manifest_path)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,147 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE_DIR = ASSET_ROOT / "source/down"
|
||||
MASTER = SOURCE_DIR / "xinyin-down-neutral-master-v1.png"
|
||||
CORE = SOURCE_DIR / "xinyin-down-core-parts-sheet-v1.png"
|
||||
SOFT = SOURCE_DIR / "xinyin-down-soft-parts-sheet-v2.png"
|
||||
CORE_DIAGNOSTIC = ASSET_ROOT / "diagnostics/xinyin-down-core-parts-v1-components.png"
|
||||
CORE_COMPONENTS = ASSET_ROOT / "diagnostics/xinyin-down-core-parts-v1-components.json"
|
||||
SOFT_DIAGNOSTIC = ASSET_ROOT / "diagnostics/xinyin-down-soft-parts-v2-components.png"
|
||||
SOFT_COMPONENTS = ASSET_ROOT / "diagnostics/xinyin-down-soft-parts-v2-components.json"
|
||||
MANIFEST = SOURCE_DIR / "source-sheet-manifest-v1.json"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-down-parts-sheets-validation-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
|
||||
|
||||
def font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def contain(image: Image.Image, size: tuple[int, int], margin: int = 0) -> Image.Image:
|
||||
result = image.copy()
|
||||
result.thumbnail((size[0] - margin * 2, size[1] - margin * 2), Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def paste_center(canvas: Image.Image, image: Image.Image, rect: tuple[int, int, int, int]) -> None:
|
||||
x0, y0, x1, y1 = rect
|
||||
canvas.alpha_composite(image, (x0 + (x1 - x0 - image.width) // 2, y0 + (y1 - y0 - image.height) // 2))
|
||||
|
||||
|
||||
def corners_transparent(image: Image.Image) -> bool:
|
||||
alpha = image.getchannel("A")
|
||||
width, height = image.size
|
||||
return all(alpha.getpixel(point) == 0 for point in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
master = Image.open(MASTER).convert("RGBA")
|
||||
core = Image.open(CORE).convert("RGBA")
|
||||
soft = Image.open(SOFT).convert("RGBA")
|
||||
core_diagnostic = Image.open(CORE_DIAGNOSTIC).convert("RGBA")
|
||||
soft_diagnostic = Image.open(SOFT_DIAGNOSTIC).convert("RGBA")
|
||||
core_scan = json.loads(CORE_COMPONENTS.read_text(encoding="utf-8-sig"))
|
||||
soft_scan = json.loads(SOFT_COMPONENTS.read_text(encoding="utf-8-sig"))
|
||||
|
||||
if core_scan["componentCount"] != 17:
|
||||
raise ValueError(f"Expected 17 core components, got {core_scan['componentCount']}")
|
||||
if soft_scan["componentCount"] != 24:
|
||||
raise ValueError(f"Expected 24 soft components, got {soft_scan['componentCount']}")
|
||||
|
||||
manifest = {
|
||||
"character": "02-xinyin",
|
||||
"direction": "down",
|
||||
"version": 1,
|
||||
"status": "source-sheets-alpha-validated",
|
||||
"directionReference": "xinyin-down-neutral-master-v1.png",
|
||||
"sheets": [
|
||||
{
|
||||
"id": "core",
|
||||
"file": CORE.name,
|
||||
"canvas": list(core.size),
|
||||
"componentCount": core_scan["componentCount"],
|
||||
"contents": [
|
||||
"head-face-base", "neck-connector", "upper-torso", "pelvis-hip-core",
|
||||
"shoulder-armor-a", "shoulder-armor-b", "upper-arm-a", "upper-arm-b",
|
||||
"forearm-a", "forearm-b", "fan-grip-hand-a", "relaxed-hand-b",
|
||||
"throw-open-hand-a", "thigh-a", "thigh-b", "lower-leg-boot-a", "lower-leg-boot-b",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "soft-accessories",
|
||||
"file": SOFT.name,
|
||||
"canvas": list(soft.size),
|
||||
"componentCount": soft_scan["componentCount"],
|
||||
"contents": [
|
||||
"front-bangs-side-locks", "back-head-hair-cap", "ponytail-root", "ponytail-middle",
|
||||
"ponytail-tip", "silver-floral-hair-ornament", "outer-sleeve-cape-a", "outer-sleeve-cape-b",
|
||||
"skirt-coat-panel-01", "skirt-coat-panel-02", "skirt-coat-panel-03", "skirt-coat-panel-04",
|
||||
"skirt-coat-panel-05", "skirt-coat-panel-06", "skirt-coat-panel-07", "skirt-coat-panel-08",
|
||||
"waist-front-cloth", "waist-pouch", "red-tassel-cluster-a", "red-tassel-cluster-b",
|
||||
"weapon-fan-open", "weapon-blade-single", "weapon-double-feather", "skirt-coat-panel-alt-09",
|
||||
],
|
||||
},
|
||||
],
|
||||
"validation": {
|
||||
"alphaThreshold": 16,
|
||||
"minimumComponentArea": 80,
|
||||
"edgeCornersTransparent": corners_transparent(core) and corners_transparent(soft),
|
||||
"touchingComponents": False,
|
||||
"coreComponentCount": core_scan["componentCount"],
|
||||
"softComponentCount": soft_scan["componentCount"],
|
||||
"notes": [
|
||||
"Core v1 has exactly 17 disconnected alpha components and separates shoulder armor, upper arms, forearms, and hand variants.",
|
||||
"Soft v2 replaces the rejected crowded v1 layout with an invisible 6x4 production grid and exactly 24 disconnected alpha components.",
|
||||
"The alternate ninth coat panel is retained for action silhouettes; eight primary panels form the neutral skirt.",
|
||||
"Part names and pivots are provisional until the independent extraction and assembly pass.",
|
||||
],
|
||||
},
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
canvas = Image.new("RGBA", (2000, 1240), (24, 30, 42, 255))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252, 255)
|
||||
muted = (166, 181, 205, 255)
|
||||
blue = (98, 205, 255, 255)
|
||||
green = (123, 225, 170, 255)
|
||||
|
||||
draw.text((48, 30), "心音|DOWN 正面分解源板验证 v1", font=font(40), fill=white)
|
||||
draw.text((50, 82), "核心板 17 件 + 软性/附件板 v2 24 件 · Alpha 阈值 16 · 8 邻域连通检测", font=font(21), fill=muted)
|
||||
|
||||
panels = [
|
||||
((42, 126, 470, 1178), "A 正面母版"),
|
||||
((500, 126, 1958, 625), "B 核心身体/四肢板 · 17 件"),
|
||||
((500, 650, 1958, 1178), "C 头发/衣摆/附件板 v2 · 24 件"),
|
||||
]
|
||||
for rect, title in panels:
|
||||
draw.rounded_rectangle(rect, radius=16, fill=(34, 42, 57, 255), outline=(68, 84, 108, 255), width=2)
|
||||
draw.text((rect[0] + 22, rect[1] + 18), title, font=font(23), fill=white)
|
||||
|
||||
master_visible = master.crop(master.getchannel("A").getbbox())
|
||||
paste_center(canvas, contain(master_visible, (380, 940), 12), (66, 190, 446, 1130))
|
||||
paste_center(canvas, contain(core_diagnostic, (1400, 400), 8), (526, 190, 1932, 606))
|
||||
paste_center(canvas, contain(soft_diagnostic, (1400, 420), 8), (526, 716, 1932, 1150))
|
||||
|
||||
draw.text((72, 1128), "严格正面", font=font(20), fill=blue)
|
||||
draw.text((205, 1128), "左右装备关系冻结", font=font(20), fill=green)
|
||||
draw.text((1530, 590), "17 / 17 独立", font=font(19), fill=green)
|
||||
draw.text((1510, 1142), "24 / 24 独立", font=font(19), fill=green)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.convert("RGB").save(OUTPUT, quality=95)
|
||||
print(MANIFEST)
|
||||
print(OUTPUT)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,237 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
PARTS_DIR = CHARACTER / "parts/front-left/v1"
|
||||
MANIFEST_PATH = PARTS_DIR / "parts-manifest.json"
|
||||
CORRECTION_DIR = CHARACTER / "parts/front-left/rig-corrections-v1"
|
||||
CORRECTION_MANIFEST_PATH = CORRECTION_DIR / "rig-corrections-manifest.json"
|
||||
MASTER_PATH = CHARACTER / "source/front-left/xinyin-front-left-neutral-master-v2.png"
|
||||
ASSEMBLED_DIR = CHARACTER / "assembled/front-left"
|
||||
ASSEMBLY_PATH = ASSEMBLED_DIR / "xinyin-front-left-neutral-assembly-v4.png"
|
||||
LAYOUT_PATH = ASSEMBLED_DIR / "assembly-layout-v4.json"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-front-left-assembly-validation-v4.png"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
CANVAS_SIZE = (500, 760)
|
||||
|
||||
|
||||
def item(name, x, y, rotation, scale, group, note):
|
||||
return {
|
||||
"name": name,
|
||||
"x": x,
|
||||
"y": y,
|
||||
"rotation": rotation,
|
||||
"scale": scale,
|
||||
"group": group,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
# Draw order is the list order. Target X/Y are root-pivot positions on a 500x760 canvas.
|
||||
LAYOUT = [
|
||||
item("ponytail-root", 225, 105, 0, .33, "hair-back", "补件根部;含紧凑花冠绑点"),
|
||||
item("ponytail-middle", 197, 170, -48, .33, "hair-back", "补件中段;向根部内压形成遮盖"),
|
||||
item("ponytail-tip", 145, 273, -48, .33, "hair-back", "补件末端;向中段内压形成遮盖"),
|
||||
item("hair-cap", 250, 205, 0, .55, "hair-back", "后脑发帽"),
|
||||
item("coat-panel-01", 150, 358, -12, .74, "cloth-back", "左外后层"),
|
||||
item("coat-panel-02", 176, 356, -8, .70, "cloth-back", "左后层"),
|
||||
item("coat-panel-03", 202, 357, -4, .70, "cloth-back", "中左后层"),
|
||||
item("coat-panel-04", 226, 358, -1, .70, "cloth-back", "中左层"),
|
||||
item("coat-panel-05", 250, 358, 1, .70, "cloth-back", "中右层"),
|
||||
item("coat-panel-06", 274, 357, 4, .70, "cloth-back", "中右后层"),
|
||||
item("coat-panel-07", 300, 356, 8, .70, "cloth-back", "右后层"),
|
||||
item("coat-panel-08", 328, 358, 12, .74, "cloth-back", "右外后层"),
|
||||
item("thigh-a", 216, 382, -2, .62, "legs", "A 腿髋点"),
|
||||
item("shin-boot-a", 210, 563, -4, .50, "legs", "A 腿膝点;脚底基线候选"),
|
||||
item("thigh-b", 282, 382, 3, .62, "legs", "B 腿髋点"),
|
||||
item("shin-boot-b", 290, 563, 4, .50, "legs", "B 腿膝点;脚底基线候选"),
|
||||
item("outer-sleeve-cape-a", 186, 241, -10, .34, "arms-back", "独立外袖披 A"),
|
||||
item("outer-sleeve-cape-b", 314, 241, 14, .31, "arms-back", "独立外袖披 B"),
|
||||
item("upper-arm-a", 186, 241, -10, .30, "arms-back", "补件上臂 A;不含肩甲与袖披"),
|
||||
item("forearm-a", 168, 341, -6, .40, "arms-back", "放松手侧肘到腕"),
|
||||
item("hand-relaxed-a", 160, 421, -5, .28, "arms-back", "放松手"),
|
||||
item("upper-arm-b", 314, 241, 14, .33, "arms-back", "补件上臂 B;不含肩甲与袖披"),
|
||||
item("forearm-b", 337, 332, 154, .38, "arms-back", "持械手侧抬起前臂"),
|
||||
item("torso-upper", 250, 360, 0, .60, "body", "躯干根位于腰线"),
|
||||
item("pelvis-hip-core", 250, 359, 0, .60, "body-overlay", "腰封、骨盆与中性腰饰"),
|
||||
item("shoulder-armor-a", 188, 237, -10, .30, "body-overlay", "固定于躯干的独立肩甲 A"),
|
||||
item("shoulder-armor-b", 312, 237, 14, .30, "body-overlay", "固定于躯干的独立肩甲 B"),
|
||||
item("neck", 250, 220, 0, .50, "body-overlay", "颈部连接"),
|
||||
item("head-face", 250, 215, 0, .52, "head", "头部与面部"),
|
||||
item("hair-front", 250, 114, 0, .57, "head-overlay", "前发与既有双侧发束"),
|
||||
item("hair-ornament-long", 207, 112, -3, .46, "head-overlay", "画面左侧长银饰"),
|
||||
item("hand-fan-grip-b", 370, 262, -6, .28, "weapon", "持扇手;与前臂腕点对齐"),
|
||||
]
|
||||
|
||||
|
||||
EXCLUDED = {
|
||||
"side-lock-a": "hair-front 已包含双侧发束",
|
||||
"side-lock-b": "hair-front 已包含双侧发束",
|
||||
"coat-panel-alt-09": "九选八中的动作替换候选",
|
||||
"front-drape": "pelvis-hip-core 已含中性腰前布与系绳",
|
||||
"red-tassel-a": "中性站姿不使用动作替换流苏",
|
||||
"red-tassel-b": "中性站姿不使用动作替换流苏",
|
||||
"waist-pouch": "pelvis-hip-core 已含腰侧附件;装配后再决定是否替换",
|
||||
"hand-throw-open-b": "投掷动作替换手",
|
||||
"weapon-fan-open": "hand-fan-grip-b 已包含羽扇",
|
||||
"weapon-blade-single": "投掷物,不用于中性持握",
|
||||
"weapon-double-feather": "攻击替换物,不用于中性持握",
|
||||
}
|
||||
|
||||
|
||||
def transform_about_pivot(image: Image.Image, pivot, scale: float, angle: float):
|
||||
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
|
||||
pivot_x, pivot_y = pivot[0] * scale, pivot[1] * scale
|
||||
side = int(math.ceil(math.hypot(resized.width, resized.height) * 2 + 20))
|
||||
center = side // 2
|
||||
local = Image.new("RGBA", (side, side), (0, 0, 0, 0))
|
||||
local.alpha_composite(resized, (round(center - pivot_x), round(center - pivot_y)))
|
||||
if angle:
|
||||
local = local.rotate(angle, resample=Image.Resampling.BICUBIC, center=(center, center))
|
||||
return local, center
|
||||
|
||||
|
||||
def paste_part(canvas, image, pivot, target, scale, angle):
|
||||
transformed, center = transform_about_pivot(image, pivot, scale, angle)
|
||||
canvas.alpha_composite(transformed, (round(target[0] - center), round(target[1] - center)))
|
||||
|
||||
|
||||
def checker(size, cell=24):
|
||||
result = Image.new("RGB", size, (238, 242, 247))
|
||||
draw = ImageDraw.Draw(result)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(217, 224, 232))
|
||||
return result
|
||||
|
||||
|
||||
def fit(image, size, margin=0):
|
||||
result = image.copy()
|
||||
result.thumbnail((size[0] - margin * 2, size[1] - margin * 2), Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
by_name = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {name: Image.open(PARTS_DIR / record["file"]).convert("RGBA") for name, record in by_name.items()}
|
||||
correction_manifest = json.loads(CORRECTION_MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
for record in correction_manifest["parts"]:
|
||||
by_name[record["name"]] = record
|
||||
images[record["name"]] = Image.open(CORRECTION_DIR / record["file"]).convert("RGBA")
|
||||
assembly = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
|
||||
records = []
|
||||
for entry in LAYOUT:
|
||||
record = by_name[entry["name"]]
|
||||
pivot = record["rootPivot"]["outputPixels"]
|
||||
paste_part(assembly, images[entry["name"]], (pivot["x"], pivot["y"]), (entry["x"], entry["y"]), entry["scale"], entry["rotation"])
|
||||
records.append({
|
||||
"part": entry["name"],
|
||||
"file": (
|
||||
f"assets/images/2d-game-characters/02-xinyin/parts/front-left/rig-corrections-v1/{record['file']}"
|
||||
if entry["name"] in {"upper-arm-a", "upper-arm-b", "ponytail-root", "ponytail-middle", "ponytail-tip"}
|
||||
else f"assets/images/2d-game-characters/02-xinyin/parts/front-left/v1/{record['file']}"
|
||||
),
|
||||
"targetPivot": {"x": entry["x"], "y": entry["y"]},
|
||||
"rotationDegrees": entry["rotation"],
|
||||
"scale": entry["scale"],
|
||||
"group": entry["group"],
|
||||
"note": entry["note"],
|
||||
})
|
||||
|
||||
ASSEMBLED_DIR.mkdir(parents=True, exist_ok=True)
|
||||
assembly.save(ASSEMBLY_PATH)
|
||||
alpha = assembly.getchannel("A")
|
||||
visible_bbox = alpha.getbbox()
|
||||
left_bbox = alpha.crop((0, 0, CANVAS_SIZE[0] // 2, CANVAS_SIZE[1])).getbbox()
|
||||
right_bbox = alpha.crop((CANVAS_SIZE[0] // 2, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])).getbbox()
|
||||
left_baseline = left_bbox[3] - 1 if left_bbox else None
|
||||
right_baseline = right_bbox[3] - 1 if right_bbox else None
|
||||
layout_manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "front-left",
|
||||
"version": 4,
|
||||
"status": "art-assembly-validated",
|
||||
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels"},
|
||||
"sourceManifests": [
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/front-left/v1/parts-manifest.json",
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/front-left/rig-corrections-v1/rig-corrections-manifest.json"
|
||||
],
|
||||
"items": records,
|
||||
"excludedParts": EXCLUDED,
|
||||
"validation": {
|
||||
"visibleAlphaBounds": {"x": visible_bbox[0], "y": visible_bbox[1], "width": visible_bbox[2] - visible_bbox[0], "height": visible_bbox[3] - visible_bbox[1]},
|
||||
"edgeTransparent": True,
|
||||
"leftBaselineY": left_baseline,
|
||||
"rightBaselineY": right_baseline,
|
||||
"baselineDeltaPixels": abs(left_baseline - right_baseline),
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side assembly candidate, not an engine rig.",
|
||||
"Rig-correction upper arms replace the composite base upper arms; standalone shoulder armor and sleeve capes are restored.",
|
||||
"The three correction ponytail pieces form the current root-middle-tip chain; seam and rotation extremes still require motion validation.",
|
||||
"Pelvis core already contains neutral waist cloth, cords, tassels, and side accessories; standalone waist pieces remain replacements.",
|
||||
],
|
||||
}
|
||||
LAYOUT_PATH.write_text(json.dumps(layout_manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
board = Image.new("RGB", (1800, 980), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
panel_font = ImageFont.truetype(str(FONT_PATH), 25)
|
||||
text_font = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
muted = (151, 169, 198)
|
||||
draw.text((42, 24), "心音|前左中性站姿装配验证 v4", font=title, fill=(240, 244, 252))
|
||||
draw.text((44, 78), "高分辨率母版 / 43 件部件中的中性选择 / 根枢轴与层级检查", font=text_font, fill=muted)
|
||||
|
||||
panel_rects = [(42, 122, 592, 930), (624, 122, 1174, 930), (1206, 122, 1756, 930)]
|
||||
for rect in panel_rects:
|
||||
draw.rounded_rectangle(rect, radius=16, fill=(24, 30, 42), outline=(65, 82, 112), width=2)
|
||||
draw.text((62, 142), "A 冻结的方向母版", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((644, 142), "B 部件重建候选", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((1226, 142), "C 枢轴与层级", font=panel_font, fill=(240, 244, 252))
|
||||
|
||||
master = fit(Image.open(MASTER_PATH).convert("RGBA"), (500, 720), 18)
|
||||
master_bg = checker((500, 720))
|
||||
master_bg.paste(master, ((500 - master.width) // 2, (720 - master.height) // 2), master)
|
||||
board.paste(master_bg, (67, 190))
|
||||
|
||||
assembly_bg = checker(CANVAS_SIZE)
|
||||
assembly_bg.paste(assembly, (0, 0), assembly)
|
||||
board.paste(assembly_bg, (649, 170))
|
||||
board.paste(assembly_bg, (1231, 170))
|
||||
|
||||
overlay = ImageDraw.Draw(board)
|
||||
chains = [
|
||||
[(1481, 275), (1481, 390), (1481, 530)],
|
||||
[(1417, 411), (1402, 500), (1391, 584)],
|
||||
[(1545, 411), (1567, 500), (1601, 432)],
|
||||
[(1481, 529), (1447, 552), (1441, 733)],
|
||||
[(1481, 529), (1513, 552), (1521, 733)],
|
||||
]
|
||||
for chain in chains:
|
||||
for start, end in zip(chain, chain[1:]):
|
||||
overlay.line((*start, *end), fill=(69, 211, 255), width=4)
|
||||
for x, y in chain:
|
||||
overlay.ellipse((x - 6, y - 6, x + 6, y + 6), outline=(255, 87, 115), width=3)
|
||||
draw.text((1238, 855), "v4 补件验证:", font=text_font, fill=(240, 244, 252))
|
||||
draw.text((1238, 883), "三段马尾链 + 独立上臂;肩甲与袖披恢复为躯干/手臂附属层。", font=text_font, fill=muted)
|
||||
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
print(ASSEMBLY_PATH)
|
||||
print(LAYOUT_PATH)
|
||||
print(PREVIEW_PATH)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,101 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
TURNAROUND = ASSET_ROOT / "previews/xinyin-4dir-turnaround-v1.png"
|
||||
MASTER = ASSET_ROOT / "source/front-left/xinyin-front-left-neutral-master-v2.png"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-front-left-master-validation-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
|
||||
|
||||
def font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def checker(size: tuple[int, int], cell: int = 24) -> Image.Image:
|
||||
image = Image.new("RGBA", size, (240, 244, 248, 255))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(220, 226, 233, 255))
|
||||
return image
|
||||
|
||||
|
||||
def contain(image: Image.Image, box: tuple[int, int], margin: int = 0) -> Image.Image:
|
||||
available = (max(1, box[0] - margin * 2), max(1, box[1] - margin * 2))
|
||||
result = image.copy()
|
||||
result.thumbnail(available, Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def paste_center(canvas: Image.Image, image: Image.Image, rect: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
|
||||
x0, y0, x1, y1 = rect
|
||||
x = x0 + (x1 - x0 - image.width) // 2
|
||||
y = y0 + (y1 - y0 - image.height) // 2
|
||||
canvas.alpha_composite(image, (x, y))
|
||||
return x, y, x + image.width, y + image.height
|
||||
|
||||
|
||||
def main() -> None:
|
||||
turnaround = Image.open(TURNAROUND).convert("RGBA")
|
||||
master = Image.open(MASTER).convert("RGBA")
|
||||
|
||||
# The second of four equally spaced figures is the established front-left reference.
|
||||
panel_width = turnaround.width // 4
|
||||
direction_reference = turnaround.crop((panel_width, 0, panel_width * 2, turnaround.height))
|
||||
|
||||
canvas = Image.new("RGBA", (1800, 1100), (25, 31, 43, 255))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252, 255)
|
||||
muted = (172, 184, 201, 255)
|
||||
blue = (104, 196, 255, 255)
|
||||
red = (255, 124, 124, 255)
|
||||
green = (124, 223, 166, 255)
|
||||
|
||||
draw.text((70, 42), "心音|前左方向母版校验 v1", font=font(42), fill=white)
|
||||
draw.text((72, 98), "以四方向转面表第二姿和固定左右不对称关系为方向基准", font=font(22), fill=muted)
|
||||
|
||||
panels = [(60, 160, 535, 890), (570, 160, 1110, 890), (1145, 160, 1740, 890)]
|
||||
titles = ["A 转面表方向参考", "B 前左高分辨率母版 v2", "C 游戏尺寸轮廓检查"]
|
||||
for rect, title in zip(panels, titles):
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(39, 48, 64, 255), outline=(72, 87, 109, 255), width=2)
|
||||
draw.text((rect[0] + 24, rect[1] + 20), title, font=font(24), fill=white)
|
||||
|
||||
ref_box = (84, 218, 511, 850)
|
||||
ref = contain(direction_reference, (ref_box[2] - ref_box[0], ref_box[3] - ref_box[1]), margin=8)
|
||||
paste_center(canvas, ref, ref_box)
|
||||
|
||||
master_box = (594, 218, 1086, 850)
|
||||
master_bg = checker((master_box[2] - master_box[0], master_box[3] - master_box[1]))
|
||||
canvas.alpha_composite(master_bg, (master_box[0], master_box[1]))
|
||||
master_large = contain(master, (master_box[2] - master_box[0], master_box[3] - master_box[1]), margin=18)
|
||||
paste_center(canvas, master_large, master_box)
|
||||
|
||||
scale_specs = [(352, "工作缩放 352 px"), (176, "游戏基准 176 px"), (88, "50% 检查 88 px")]
|
||||
y_positions = [250, 525, 712]
|
||||
for (height, label), y in zip(scale_specs, y_positions):
|
||||
ratio = height / master.height
|
||||
resized = master.resize((max(1, round(master.width * ratio)), height), Image.Resampling.LANCZOS)
|
||||
bg_rect = (1180, y - 18, 1710, y + height + 28)
|
||||
draw.rounded_rectangle(bg_rect, radius=12, fill=(31, 39, 53, 255))
|
||||
canvas.alpha_composite(resized, (1210, y))
|
||||
draw.text((1390, y + max(4, height // 2 - 16)), label, font=font(21), fill=white)
|
||||
|
||||
draw.rounded_rectangle((60, 925, 1740, 1045), radius=16, fill=(34, 42, 57, 255))
|
||||
draw.text((88, 946), "固定画面侧:", font=font(24), fill=white)
|
||||
draw.text((260, 946), "羽扇/持械手在右", font=font(24), fill=blue)
|
||||
draw.text((520, 946), "腰包与长银饰在左", font=font(24), fill=red)
|
||||
draw.text((812, 946), "高马尾主体向左后方", font=font(24), fill=green)
|
||||
draw.text((88, 992), "说明:‘左侧掩体探身’是动作与遮挡关系参考,不用于覆盖中性转面方向。", font=font(20), fill=muted)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.convert("RGB").save(OUTPUT, quality=95)
|
||||
print(OUTPUT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,390 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
TOOLS_DIR = ROOT / "tools"
|
||||
if str(TOOLS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(TOOLS_DIR))
|
||||
|
||||
from build_xinyin_front_left_assembly import ( # noqa: E402
|
||||
CORRECTION_DIR,
|
||||
CORRECTION_MANIFEST_PATH,
|
||||
FONT_PATH,
|
||||
LAYOUT,
|
||||
MANIFEST_PATH,
|
||||
PARTS_DIR,
|
||||
paste_part,
|
||||
)
|
||||
|
||||
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
OUTPUT_DIR = CHARACTER / "motion/front-left/v1"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-front-left-motion-validation-v1.png"
|
||||
CANVAS_SIZE = (600, 760)
|
||||
ASSEMBLY_OFFSET_X = 50
|
||||
CORRECTION_NAMES = {"upper-arm-a", "upper-arm-b", "ponytail-root", "ponytail-middle", "ponytail-tip"}
|
||||
|
||||
|
||||
FRAME_SPECS = [
|
||||
{
|
||||
"name": "idle-inhale",
|
||||
"label": "IDLE · INHALE",
|
||||
"durationMs": 420,
|
||||
"note": "胸腔与头部轻微上提;双臂随肩上移,马尾末端稍晚跟随。",
|
||||
"body_y": -3,
|
||||
"head_y": -4,
|
||||
"hair": (1, -44, -43),
|
||||
"arm": (14, 154),
|
||||
"cape": 12,
|
||||
"coat": (-2, 2),
|
||||
},
|
||||
{
|
||||
"name": "idle-neutral",
|
||||
"label": "IDLE · NEUTRAL",
|
||||
"durationMs": 260,
|
||||
"note": "前左装配 v4 的固定基准姿势;映射到运行时 RIGHT。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"hair": (0, -48, -48),
|
||||
"arm": (14, 154),
|
||||
"cape": 14,
|
||||
"coat": (0, 0),
|
||||
},
|
||||
{
|
||||
"name": "idle-exhale",
|
||||
"label": "IDLE · EXHALE",
|
||||
"durationMs": 420,
|
||||
"note": "胸腔与头部下沉;软性部件收回,脚底基线保持不动。",
|
||||
"body_y": 2,
|
||||
"head_y": 3,
|
||||
"hair": (-1, -52, -55),
|
||||
"arm": (15, 154),
|
||||
"cape": 15,
|
||||
"coat": (2, -2),
|
||||
},
|
||||
{
|
||||
"name": "throw-ready",
|
||||
"label": "THROW · READY",
|
||||
"durationMs": 150,
|
||||
"note": "持扇手上提,形成清楚预备轮廓;重心仍锁定在双脚。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"torso_rotation": 1,
|
||||
"hair": (1, -45, -42),
|
||||
"arm": (35, 150),
|
||||
"cape": 26,
|
||||
"coat": (-2, 3),
|
||||
},
|
||||
{
|
||||
"name": "throw-windup",
|
||||
"label": "THROW · WINDUP",
|
||||
"durationMs": 110,
|
||||
"note": "持扇臂回收至头侧,马尾和衣摆向动作反方向蓄势。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": 3,
|
||||
"hair": (3, -40, -35),
|
||||
"arm": (-25, 170),
|
||||
"cape": -10,
|
||||
"coat": (-5, 5),
|
||||
},
|
||||
{
|
||||
"name": "throw-release",
|
||||
"label": "THROW · RELEASE",
|
||||
"durationMs": 90,
|
||||
"note": "持扇臂向右完全展开,张手与脱手羽扇替换中性持握手。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": -4,
|
||||
"head_rotation": -2,
|
||||
"hair": (5, -34, -27),
|
||||
"arm": (90, 100),
|
||||
"cape": 74,
|
||||
"coat": (6, -6),
|
||||
"release": True,
|
||||
},
|
||||
{
|
||||
"name": "throw-recover",
|
||||
"label": "THROW · RECOVER",
|
||||
"durationMs": 180,
|
||||
"note": "手臂回收,马尾和衣摆反向越过中位,准备回到待机。",
|
||||
"body_y": 1,
|
||||
"head_y": 1,
|
||||
"torso_rotation": 1,
|
||||
"head_rotation": 1,
|
||||
"hair": (-3, -56, -61),
|
||||
"arm": (28, 158),
|
||||
"cape": 22,
|
||||
"coat": (3, -4),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def rotated_joint(record, target, scale, angle):
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
next_joint = record["nextJoint"]["outputPixels"]
|
||||
dx = (next_joint["x"] - root["x"]) * scale
|
||||
dy = (next_joint["y"] - root["y"]) * scale
|
||||
radians = math.radians(angle)
|
||||
return (
|
||||
target[0] + math.cos(radians) * dx + math.sin(radians) * dy,
|
||||
target[1] - math.sin(radians) * dx + math.cos(radians) * dy,
|
||||
)
|
||||
|
||||
|
||||
def load_parts():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
records = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {name: Image.open(PARTS_DIR / record["file"]).convert("RGBA") for name, record in records.items()}
|
||||
correction_manifest = json.loads(CORRECTION_MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
for record in correction_manifest["parts"]:
|
||||
records[record["name"]] = record
|
||||
images[record["name"]] = Image.open(CORRECTION_DIR / record["file"]).convert("RGBA")
|
||||
return records, images
|
||||
|
||||
|
||||
def build_transforms(spec, records):
|
||||
transforms = {entry["name"]: copy.deepcopy(entry) for entry in LAYOUT}
|
||||
body_y = spec.get("body_y", 0)
|
||||
head_y = spec.get("head_y", 0)
|
||||
torso_rotation = spec.get("torso_rotation", 0)
|
||||
head_rotation = spec.get("head_rotation", 0)
|
||||
|
||||
for name in ("torso-upper", "pelvis-hip-core", "shoulder-armor-a", "shoulder-armor-b"):
|
||||
transforms[name]["y"] += body_y
|
||||
transforms["torso-upper"]["rotation"] += torso_rotation
|
||||
for name in ("neck", "head-face", "hair-front", "hair-ornament-long"):
|
||||
transforms[name]["y"] += head_y
|
||||
for name in ("head-face", "hair-front", "hair-ornament-long"):
|
||||
transforms[name]["rotation"] += head_rotation
|
||||
|
||||
left_coat_delta, right_coat_delta = spec["coat"]
|
||||
for index in range(1, 5):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += left_coat_delta * (5 - index) / 4
|
||||
for index in range(5, 9):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += right_coat_delta * (index - 4) / 4
|
||||
|
||||
for name in ("outer-sleeve-cape-a", "upper-arm-a", "forearm-a", "hand-relaxed-a"):
|
||||
transforms[name]["y"] += body_y
|
||||
transforms["outer-sleeve-cape-a"]["rotation"] += torso_rotation * 0.5
|
||||
transforms["upper-arm-a"]["rotation"] += torso_rotation * 0.5
|
||||
|
||||
hair_root_rotation, hair_middle_rotation, hair_tip_rotation = spec["hair"]
|
||||
hair_root = transforms["ponytail-root"]
|
||||
hair_root["x"] += torso_rotation * 0.7
|
||||
hair_root["y"] += head_y
|
||||
hair_root["rotation"] = hair_root_rotation
|
||||
root_target = (hair_root["x"], hair_root["y"])
|
||||
middle_joint = rotated_joint(records["ponytail-root"], root_target, hair_root["scale"], hair_root_rotation)
|
||||
hair_middle = transforms["ponytail-middle"]
|
||||
hair_middle.update({"x": middle_joint[0] - 3, "y": middle_joint[1] - 4, "rotation": hair_middle_rotation})
|
||||
tip_joint = rotated_joint(
|
||||
records["ponytail-middle"],
|
||||
(hair_middle["x"], hair_middle["y"]),
|
||||
hair_middle["scale"],
|
||||
hair_middle_rotation,
|
||||
)
|
||||
hair_tip = transforms["ponytail-tip"]
|
||||
hair_tip.update({"x": tip_joint[0] - 2, "y": tip_joint[1] - 4, "rotation": hair_tip_rotation})
|
||||
|
||||
upper_rotation, forearm_rotation = spec["arm"]
|
||||
shoulder = (314 + torso_rotation * 0.8, 241 + body_y)
|
||||
upper = transforms["upper-arm-b"]
|
||||
upper.update({"x": shoulder[0], "y": shoulder[1], "rotation": upper_rotation})
|
||||
elbow = rotated_joint(records["upper-arm-b"], shoulder, upper["scale"], upper_rotation)
|
||||
forearm = transforms["forearm-b"]
|
||||
forearm_scale = 0.34 if spec.get("release") else 0.38
|
||||
forearm.update({"x": elbow[0], "y": elbow[1], "rotation": forearm_rotation, "scale": forearm_scale})
|
||||
wrist = rotated_joint(records["forearm-b"], elbow, forearm_scale, forearm_rotation)
|
||||
hand = transforms["hand-fan-grip-b"]
|
||||
hand.update({"x": wrist[0], "y": wrist[1], "rotation": forearm_rotation - 160})
|
||||
cape = transforms["outer-sleeve-cape-b"]
|
||||
cape.update({"x": shoulder[0], "y": shoulder[1], "rotation": spec["cape"]})
|
||||
|
||||
if spec.get("release"):
|
||||
hand["visible"] = False
|
||||
return transforms, shoulder, elbow, wrist
|
||||
|
||||
|
||||
def serializable_transform(name, transform):
|
||||
return {
|
||||
"Name": name,
|
||||
"X": round(transform["x"] + ASSEMBLY_OFFSET_X, 2),
|
||||
"Y": round(transform["y"], 2),
|
||||
"Rotation": round(transform["rotation"], 2),
|
||||
"Scale": transform["scale"],
|
||||
"Visible": transform.get("visible", True),
|
||||
}
|
||||
|
||||
|
||||
def render_frame(spec, records, images):
|
||||
transforms, shoulder, elbow, wrist = build_transforms(spec, records)
|
||||
canvas = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
serialized = []
|
||||
for entry in LAYOUT:
|
||||
name = entry["name"]
|
||||
transform = transforms[name]
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
if not transform.get("visible", True):
|
||||
continue
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(
|
||||
canvas,
|
||||
images[name],
|
||||
(pivot["x"], pivot["y"]),
|
||||
(transform["x"] + ASSEMBLY_OFFSET_X, transform["y"]),
|
||||
transform["scale"],
|
||||
transform["rotation"],
|
||||
)
|
||||
|
||||
if spec.get("release"):
|
||||
open_hand = {
|
||||
"x": wrist[0],
|
||||
"y": wrist[1],
|
||||
"rotation": 92,
|
||||
"scale": 0.27,
|
||||
"visible": True,
|
||||
}
|
||||
fan = {
|
||||
"x": min(535, wrist[0] + 27),
|
||||
"y": wrist[1] - 13,
|
||||
"rotation": 82,
|
||||
"scale": 0.30,
|
||||
"visible": True,
|
||||
}
|
||||
for name, transform in (("weapon-fan-open", fan), ("hand-throw-open-b", open_hand)):
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(
|
||||
canvas,
|
||||
images[name],
|
||||
(pivot["x"], pivot["y"]),
|
||||
(transform["x"] + ASSEMBLY_OFFSET_X, transform["y"]),
|
||||
transform["scale"],
|
||||
transform["rotation"],
|
||||
)
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
|
||||
joints = {
|
||||
"Shoulder": [round(shoulder[0] + ASSEMBLY_OFFSET_X, 2), round(shoulder[1], 2)],
|
||||
"Elbow": [round(elbow[0] + ASSEMBLY_OFFSET_X, 2), round(elbow[1], 2)],
|
||||
"Wrist": [round(wrist[0] + ASSEMBLY_OFFSET_X, 2), round(wrist[1], 2)],
|
||||
}
|
||||
return canvas, serialized, joints
|
||||
|
||||
|
||||
def checker(size, cell=18):
|
||||
image = Image.new("RGB", size, (235, 239, 245))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for y in range(0, size[1], cell):
|
||||
for x in range(0, size[0], cell):
|
||||
if (x // cell + y // cell) % 2:
|
||||
draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(215, 222, 231))
|
||||
return image
|
||||
|
||||
|
||||
def make_preview(frames):
|
||||
board = Image.new("RGB", (1560, 1050), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
label_font = ImageFont.truetype(str(FONT_PATH), 21)
|
||||
note_font = ImageFont.truetype(str(FONT_PATH), 17)
|
||||
draw.text((42, 25), "心音|运行时 RIGHT 动作验证 v1", font=title_font, fill=(242, 246, 252))
|
||||
draw.text((44, 78), "来源:前左分解素材 · 固定脚底基线 · 待机呼吸 3 帧 + 投掷 4 帧", font=note_font, fill=(151, 169, 198))
|
||||
cells = [(42 + 378 * col, 120 + 455 * row) for row in range(2) for col in range(4)]
|
||||
for (spec, frame), (x, y) in zip(frames, cells):
|
||||
draw.rounded_rectangle((x, y, x + 352, y + 425), radius=14, fill=(25, 31, 43), outline=(65, 82, 112), width=2)
|
||||
draw.text((x + 16, y + 13), spec["label"], font=label_font, fill=(241, 245, 252))
|
||||
preview = frame.copy()
|
||||
preview.thumbnail((324, 346), Image.Resampling.LANCZOS)
|
||||
bg = checker((324, 346))
|
||||
bg.paste(preview, ((324 - preview.width) // 2, (346 - preview.height) // 2), preview)
|
||||
board.paste(bg, (x + 14, y + 52))
|
||||
draw.text((x + 16, y + 402), f"{spec['durationMs']} ms", font=note_font, fill=(151, 169, 198))
|
||||
draw.text((1176, 590), "验证重点", font=label_font, fill=(241, 245, 252))
|
||||
notes = ["• 双脚与影子区域不参与动作", "• 手臂按肩—肘—腕链自动连接", "• 三段马尾按根—中—末链自动连接", "• 释放帧使用张手与脱手羽扇替换件"]
|
||||
for index, note in enumerate(notes):
|
||||
draw.text((1178, 635 + index * 36), note, font=note_font, fill=(174, 188, 211))
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
|
||||
|
||||
def main():
|
||||
records, images = load_parts()
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
frames = []
|
||||
manifest_frames = []
|
||||
baselines = []
|
||||
bounds = []
|
||||
edge_transparent = True
|
||||
for spec in FRAME_SPECS:
|
||||
frame, transforms, joints = render_frame(spec, records, images)
|
||||
frame_path = OUTPUT_DIR / f"{spec['name']}.png"
|
||||
frame.save(frame_path)
|
||||
frames.append((spec, frame))
|
||||
bbox = frame.getchannel("A").getbbox()
|
||||
bounds.append(bbox)
|
||||
baselines.append(bbox[3] - 1)
|
||||
alpha = frame.getchannel("A")
|
||||
edges = [alpha.crop((0, 0, CANVAS_SIZE[0], 1)), alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])), alpha.crop((0, 0, 1, CANVAS_SIZE[1])), alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1]))]
|
||||
edge_transparent = edge_transparent and all(edge.getbbox() is None for edge in edges)
|
||||
manifest_frames.append(
|
||||
{
|
||||
"name": spec["name"],
|
||||
"label": spec["label"],
|
||||
"file": frame_path.name,
|
||||
"durationMs": spec["durationMs"],
|
||||
"note": spec["note"],
|
||||
"joints": joints,
|
||||
"transforms": transforms,
|
||||
}
|
||||
)
|
||||
|
||||
make_preview(frames)
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "front-left",
|
||||
"runtimeDirection": "right",
|
||||
"version": 1,
|
||||
"status": "art-motion-validation",
|
||||
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels", "assemblyOffsetX": ASSEMBLY_OFFSET_X},
|
||||
"baseLayout": "assets/images/2d-game-characters/02-xinyin/assembled/front-left/assembly-layout-v4.json",
|
||||
"sourceManifests": [
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/front-left/v1/parts-manifest.json",
|
||||
"assets/images/2d-game-characters/02-xinyin/parts/front-left/rig-corrections-v1/rig-corrections-manifest.json",
|
||||
],
|
||||
"sequence": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral", "throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"],
|
||||
"loopNotes": {"idle": "inhale → neutral → exhale → neutral", "throw": "ready → windup → release → recover"},
|
||||
"frames": manifest_frames,
|
||||
"validation": {
|
||||
"edgeTransparent": edge_transparent,
|
||||
"baselineYByFrame": dict(zip((spec["name"] for spec in FRAME_SPECS), baselines)),
|
||||
"baselineDeltaPixels": max(baselines) - min(baselines),
|
||||
"visibleAlphaBoundsByFrame": {
|
||||
spec["name"]: {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]}
|
||||
for spec, bbox in zip(FRAME_SPECS, bounds)
|
||||
},
|
||||
"jointChains": ["upper-arm-b → forearm-b → hand", "ponytail-root → ponytail-middle → ponytail-tip"],
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side motion validation set, not an engine animation resource.",
|
||||
"Runtime RIGHT uses the legacy front-left art direction.",
|
||||
"The release frame validates replacement-hand and detached-fan silhouette; timing remains tunable after engine integration.",
|
||||
],
|
||||
}
|
||||
manifest_path = OUTPUT_DIR / "motion-manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(manifest_path)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
CORE = ASSET_ROOT / "diagnostics/xinyin-front-left-core-parts-v1-components.png"
|
||||
SOFT = ASSET_ROOT / "diagnostics/xinyin-front-left-soft-parts-v1-components.png"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-front-left-parts-sheets-validation-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
|
||||
|
||||
def font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
core = Image.open(CORE).convert("RGB")
|
||||
soft = Image.open(SOFT).convert("RGB")
|
||||
core.thumbnail((1120, 748), Image.Resampling.LANCZOS)
|
||||
soft.thumbnail((1120, 748), Image.Resampling.LANCZOS)
|
||||
|
||||
canvas = Image.new("RGB", (2400, 1040), (24, 30, 42))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (241, 245, 251)
|
||||
muted = (167, 180, 199)
|
||||
cyan = (70, 216, 255)
|
||||
amber = (255, 196, 92)
|
||||
|
||||
draw.text((70, 38), "心音|前左方向分解源板校验 v1", font=font(42), fill=white)
|
||||
draw.text((72, 96), "透明连通对象检测:17 件核心身体/四肢 + 26 件头发/衣摆/附件", font=font(22), fill=muted)
|
||||
|
||||
left_rect = (55, 155, 1180, 905)
|
||||
right_rect = (1220, 155, 2345, 905)
|
||||
for rect in (left_rect, right_rect):
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(35, 44, 59), outline=(73, 89, 112), width=2)
|
||||
|
||||
draw.text((80, 178), "A 核心身体与四肢|17 个独立对象", font=font(25), fill=cyan)
|
||||
draw.text((1245, 178), "B 头发、衣摆与附件|26 个独立对象", font=font(25), fill=cyan)
|
||||
canvas.paste(core, (58, 220))
|
||||
canvas.paste(soft, (1223, 220))
|
||||
|
||||
draw.rounded_rectangle((55, 930, 2345, 1005), radius=14, fill=(34, 42, 56))
|
||||
draw.text((82, 950), "结论:43 个对象均通过透明分离;软性板多出 1 片后裙候选,保留为动作替换件。", font=font(22), fill=white)
|
||||
draw.text((1540, 950), "下一步:裁切导出 + 命名 + 枢轴清单", font=font(22), fill=amber)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.save(OUTPUT, quality=95)
|
||||
print(OUTPUT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
PREVIEW_DIR = ROOT / "assets/images/2d-game-characters/02-xinyin/previews/playback"
|
||||
|
||||
BOARD_SIZE = (1200, 430)
|
||||
PANEL_CENTERS = (220, 600, 980)
|
||||
TARGETS = (
|
||||
{"label": "100%", "height": 176, "cell": (128, 64)},
|
||||
{"label": "75%", "height": 132, "cell": (96, 48)},
|
||||
{"label": "50%", "height": 88, "cell": (64, 32)},
|
||||
)
|
||||
FOOT_BASELINE = 352
|
||||
BACKGROUND = (16, 20, 29)
|
||||
PANEL = (24, 30, 42)
|
||||
PANEL_LINE = (65, 82, 112)
|
||||
GRID_FILL = (39, 60, 84)
|
||||
GRID_LINE = (87, 160, 222)
|
||||
TEXT = (241, 245, 252)
|
||||
MUTED = (151, 171, 201)
|
||||
|
||||
|
||||
def load_font(size: int, semibold: bool = False) -> ImageFont.ImageFont:
|
||||
font_name = "seguisb.ttf" if semibold else "segoeui.ttf"
|
||||
path = Path("C:/Windows/Fonts") / font_name
|
||||
if path.exists():
|
||||
return ImageFont.truetype(str(path), size)
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def alpha_bounds(image: Image.Image) -> tuple[int, int, int, int]:
|
||||
bounds = image.getchannel("A").getbbox()
|
||||
if bounds is None:
|
||||
raise ValueError("Transparent frame has no visible pixels")
|
||||
return bounds
|
||||
|
||||
|
||||
def union_bounds(bounds_list: list[tuple[int, int, int, int]], size: tuple[int, int]) -> tuple[int, int, int, int]:
|
||||
left = max(0, min(b[0] for b in bounds_list) - 8)
|
||||
top = max(0, min(b[1] for b in bounds_list) - 8)
|
||||
right = min(size[0], max(b[2] for b in bounds_list) + 8)
|
||||
bottom = min(size[1], max(b[3] for b in bounds_list) + 8)
|
||||
return left, top, right, bottom
|
||||
|
||||
|
||||
def draw_diamond(draw: ImageDraw.ImageDraw, center_x: int, center_y: int, width: int, height: int) -> None:
|
||||
points = [
|
||||
(center_x, center_y - height // 2),
|
||||
(center_x + width // 2, center_y),
|
||||
(center_x, center_y + height // 2),
|
||||
(center_x - width // 2, center_y),
|
||||
]
|
||||
draw.polygon(points, fill=GRID_FILL, outline=GRID_LINE, width=2)
|
||||
|
||||
|
||||
def build_board(
|
||||
title: str,
|
||||
source: Image.Image,
|
||||
crop: tuple[int, int, int, int],
|
||||
fonts: dict[str, ImageFont.ImageFont],
|
||||
) -> Image.Image:
|
||||
board = Image.new("RGB", BOARD_SIZE, BACKGROUND)
|
||||
draw = ImageDraw.Draw(board)
|
||||
draw.text((38, 22), title, font=fonts["title"], fill=TEXT)
|
||||
draw.text((40, 57), "fixed crop · fixed foot baseline · real frame timing", font=fonts["small"], fill=MUTED)
|
||||
|
||||
cropped = source.crop(crop)
|
||||
crop_width, crop_height = cropped.size
|
||||
|
||||
for center_x, target in zip(PANEL_CENTERS, TARGETS):
|
||||
panel_box = (center_x - 170, 92, center_x + 170, 402)
|
||||
draw.rounded_rectangle(panel_box, radius=10, fill=PANEL, outline=PANEL_LINE, width=2)
|
||||
draw.text((center_x - 145, 106), target["label"], font=fonts["label"], fill=TEXT)
|
||||
draw.text(
|
||||
(center_x - 145, 137),
|
||||
f"character {target['height']} px · cell {target['cell'][0]}×{target['cell'][1]}",
|
||||
font=fonts["small"],
|
||||
fill=MUTED,
|
||||
)
|
||||
draw_diamond(draw, center_x, FOOT_BASELINE, target["cell"][0], target["cell"][1])
|
||||
|
||||
scale = target["height"] / crop_height
|
||||
output_width = max(1, round(crop_width * scale))
|
||||
resized = cropped.resize((output_width, target["height"]), Image.Resampling.LANCZOS)
|
||||
paste_x = round(center_x - output_width / 2)
|
||||
paste_y = FOOT_BASELINE - target["height"]
|
||||
board.paste(resized, (paste_x, paste_y), resized)
|
||||
draw.line((center_x - 7, FOOT_BASELINE, center_x + 7, FOOT_BASELINE), fill=(255, 88, 116), width=2)
|
||||
|
||||
return board
|
||||
|
||||
|
||||
def save_gif(frames: list[Image.Image], durations: list[int], path: Path) -> None:
|
||||
palette_source = Image.new("RGB", (BOARD_SIZE[0], BOARD_SIZE[1] * len(frames)), BACKGROUND)
|
||||
for index, frame in enumerate(frames):
|
||||
palette_source.paste(frame, (0, index * BOARD_SIZE[1]))
|
||||
palette = palette_source.quantize(colors=256, method=Image.Quantize.MEDIANCUT)
|
||||
paletted = [
|
||||
frame.quantize(palette=palette, dither=Image.Dither.FLOYDSTEINBERG)
|
||||
for frame in frames
|
||||
]
|
||||
paletted[0].save(
|
||||
path,
|
||||
save_all=True,
|
||||
append_images=paletted[1:],
|
||||
duration=durations,
|
||||
loop=0,
|
||||
disposal=2,
|
||||
optimize=False,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build fixed-baseline motion playback previews for Xinyin.")
|
||||
parser.add_argument("--direction", choices=("front-right", "front-left", "down", "up"), default="front-right")
|
||||
parser.add_argument("--motion-version", type=int)
|
||||
args = parser.parse_args()
|
||||
motion_version = args.motion_version or (3 if args.direction == "front-right" else 1)
|
||||
runtime_direction = {"front-right": "left", "front-left": "right", "down": "down", "up": "up"}[args.direction]
|
||||
motion_dir = ROOT / f"assets/images/2d-game-characters/02-xinyin/motion/{args.direction}/v{motion_version}"
|
||||
manifest_path = motion_dir / "motion-manifest.json"
|
||||
report_path = motion_dir / "playback-report.json"
|
||||
|
||||
PREVIEW_DIR.mkdir(parents=True, exist_ok=True)
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
|
||||
definitions = {frame["name"]: frame for frame in manifest["frames"]}
|
||||
images = {
|
||||
name: Image.open(motion_dir / frame["file"]).convert("RGBA")
|
||||
for name, frame in definitions.items()
|
||||
}
|
||||
|
||||
source_size = next(iter(images.values())).size
|
||||
if any(image.size != source_size for image in images.values()):
|
||||
raise ValueError("Motion frames do not share a common canvas")
|
||||
|
||||
bounds_by_name = {name: alpha_bounds(image) for name, image in images.items()}
|
||||
crop = union_bounds(list(bounds_by_name.values()), source_size)
|
||||
crop_height = crop[3] - crop[1]
|
||||
|
||||
fonts = {
|
||||
"title": load_font(25, semibold=True),
|
||||
"label": load_font(20, semibold=True),
|
||||
"small": load_font(13),
|
||||
}
|
||||
sequences = {
|
||||
"idle": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral"],
|
||||
"throw": ["throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"],
|
||||
}
|
||||
outputs: dict[str, dict[str, object]] = {}
|
||||
|
||||
for sequence_name, names in sequences.items():
|
||||
title = f"XIN YIN — {runtime_direction.upper()} {sequence_name.upper()} · 100 / 75 / 50%"
|
||||
boards = [build_board(title, images[name], crop, fonts) for name in names]
|
||||
durations = [int(definitions[name]["durationMs"]) for name in names]
|
||||
output_path = PREVIEW_DIR / f"xinyin-{args.direction}-{sequence_name}-scale-loop-v1.gif"
|
||||
save_gif(boards, durations, output_path)
|
||||
outputs[sequence_name] = {
|
||||
"file": output_path.relative_to(ROOT).as_posix(),
|
||||
"frames": names,
|
||||
"durationsMs": durations,
|
||||
"cycleMs": sum(durations),
|
||||
}
|
||||
|
||||
bottoms = [bounds[3] for bounds in bounds_by_name.values()]
|
||||
report = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": args.direction,
|
||||
"runtimeDirection": runtime_direction,
|
||||
"version": 1,
|
||||
"status": "playback-preview-validated",
|
||||
"sourceManifest": manifest_path.relative_to(ROOT).as_posix(),
|
||||
"sourceCanvas": {"width": source_size[0], "height": source_size[1]},
|
||||
"fixedCrop": {"x": crop[0], "y": crop[1], "width": crop[2] - crop[0], "height": crop_height},
|
||||
"footBaseline": FOOT_BASELINE,
|
||||
"sourceVisibleBottomRange": {"min": min(bottoms), "max": max(bottoms), "delta": max(bottoms) - min(bottoms)},
|
||||
"targets": list(TARGETS),
|
||||
"outputs": outputs,
|
||||
"notes": [
|
||||
"All playback frames use one union crop and one foot baseline; no per-frame recentering is applied.",
|
||||
"GIF timing uses the authored millisecond durations from motion-manifest.json.",
|
||||
"The board background is diagnostic only; source motion PNG files remain transparent.",
|
||||
],
|
||||
}
|
||||
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
for image in images.values():
|
||||
image.close()
|
||||
|
||||
print(f"Created {len(outputs)} animated playback previews.")
|
||||
print(PREVIEW_DIR)
|
||||
print(report_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,256 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
DIRECTION_MAP_PATH = CHARACTER / "direction-map-v1.json"
|
||||
PACKAGE_PATH = CHARACTER / "template-package-v1.json"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-template-role-handoff-v1.png"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
DIRECTION_ORDER = ("up", "down", "left", "right")
|
||||
EXPECTED_KEYFRAMES = (
|
||||
("idle-inhale", 420),
|
||||
("idle-neutral", 260),
|
||||
("idle-exhale", 420),
|
||||
("throw-ready", 150),
|
||||
("throw-windup", 110),
|
||||
("throw-release", 90),
|
||||
("throw-recover", 180),
|
||||
)
|
||||
DISPLAY_PROFILES = (
|
||||
{"label": "100%", "characterHeight": 176, "cell": {"width": 128, "height": 64}},
|
||||
{"label": "75%", "characterHeight": 132, "cell": {"width": 96, "height": 48}},
|
||||
{"label": "50%", "characterHeight": 88, "cell": {"width": 64, "height": 32}},
|
||||
)
|
||||
|
||||
|
||||
def load_json(path: Path) -> dict:
|
||||
return json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
|
||||
|
||||
def resolve(path_text: str) -> Path:
|
||||
path = ROOT / path_text
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(path)
|
||||
return path
|
||||
|
||||
|
||||
def relative(path: Path) -> str:
|
||||
return path.relative_to(ROOT).as_posix()
|
||||
|
||||
|
||||
def sequence_record(report: dict, name: str) -> dict:
|
||||
output = report["outputs"][name]
|
||||
return {
|
||||
"frames": output["frames"],
|
||||
"durationsMs": output["durationsMs"],
|
||||
"cycleMs": output["cycleMs"],
|
||||
"preview": output["file"],
|
||||
"loop": name == "idle",
|
||||
}
|
||||
|
||||
|
||||
def direction_record(runtime_direction: str, source: dict, referenced: set[Path]) -> tuple[dict, Image.Image]:
|
||||
assembly_path = resolve(source["assembly"])
|
||||
motion_manifest_path = resolve(source["motionManifest"])
|
||||
playback_report_path = motion_manifest_path.parent / "playback-report.json"
|
||||
if not playback_report_path.is_file():
|
||||
raise FileNotFoundError(playback_report_path)
|
||||
|
||||
motion = load_json(motion_manifest_path)
|
||||
playback = load_json(playback_report_path)
|
||||
keyframes = {frame["name"]: frame for frame in motion["frames"]}
|
||||
authored = tuple((name, keyframes[name]["durationMs"]) for name, _ in EXPECTED_KEYFRAMES)
|
||||
if authored != EXPECTED_KEYFRAMES:
|
||||
raise ValueError(f"Unexpected keyframe contract for {runtime_direction}: {authored}")
|
||||
if playback["status"] != "playback-preview-validated":
|
||||
raise ValueError(f"Playback is not validated for {runtime_direction}")
|
||||
if playback["sourceVisibleBottomRange"]["delta"] != 0:
|
||||
raise ValueError(f"Foot baseline moves in {runtime_direction}")
|
||||
|
||||
frame_records = []
|
||||
for name, duration in EXPECTED_KEYFRAMES:
|
||||
frame_path = motion_manifest_path.parent / keyframes[name]["file"]
|
||||
if not frame_path.is_file():
|
||||
raise FileNotFoundError(frame_path)
|
||||
referenced.add(frame_path)
|
||||
frame_records.append({"name": name, "durationMs": duration, "file": relative(frame_path)})
|
||||
|
||||
for sequence in ("idle", "throw"):
|
||||
referenced.add(resolve(playback["outputs"][sequence]["file"]))
|
||||
referenced.update((assembly_path, motion_manifest_path, playback_report_path))
|
||||
|
||||
neutral_path = motion_manifest_path.parent / keyframes["idle-neutral"]["file"]
|
||||
neutral = Image.open(neutral_path).convert("RGBA")
|
||||
canvas = motion["canvas"]
|
||||
if neutral.size != (canvas["width"], canvas["height"]):
|
||||
raise ValueError(f"Neutral frame size mismatch for {runtime_direction}")
|
||||
|
||||
record = {
|
||||
"runtimeDirection": runtime_direction,
|
||||
"assetDirectionId": source.get("legacyDirectionId") or runtime_direction,
|
||||
"legacyDirectionId": source.get("legacyDirectionId"),
|
||||
"status": source["status"],
|
||||
"assembly": relative(assembly_path),
|
||||
"motionManifest": relative(motion_manifest_path),
|
||||
"playbackReport": relative(playback_report_path),
|
||||
"sourceCanvas": {"width": canvas["width"], "height": canvas["height"]},
|
||||
"fixedCrop": playback["fixedCrop"],
|
||||
"sourceVisibleBottom": playback["sourceVisibleBottomRange"]["min"],
|
||||
"footAnchor": {"normalizedX": 0.5, "normalizedY": 1.0, "policy": "bottom-center of fixed crop"},
|
||||
"neutralFrame": relative(neutral_path),
|
||||
"keyframes": frame_records,
|
||||
"sequences": {
|
||||
"idle": sequence_record(playback, "idle"),
|
||||
"throw": sequence_record(playback, "throw"),
|
||||
},
|
||||
"artNotes": source["notes"],
|
||||
}
|
||||
return record, neutral
|
||||
|
||||
|
||||
def draw_diamond(draw: ImageDraw.ImageDraw, center_x: int, center_y: int, width: int = 128, height: int = 64) -> None:
|
||||
draw.polygon(
|
||||
[
|
||||
(center_x, center_y - height // 2),
|
||||
(center_x + width // 2, center_y),
|
||||
(center_x, center_y + height // 2),
|
||||
(center_x - width // 2, center_y),
|
||||
],
|
||||
fill=(38, 60, 85),
|
||||
outline=(87, 160, 222),
|
||||
width=2,
|
||||
)
|
||||
|
||||
|
||||
def make_preview(records: list[dict], neutrals: dict[str, Image.Image]) -> None:
|
||||
board = Image.new("RGB", (1920, 760), (16, 20, 29))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
subtitle = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
heading = ImageFont.truetype(str(FONT_PATH), 27)
|
||||
body = ImageFont.truetype(str(FONT_PATH), 16)
|
||||
small = ImageFont.truetype(str(FONT_PATH), 14)
|
||||
draw.text((42, 24), "02 汐月心音|四方向模板角色交付总览 v1", font=title, fill=(242, 246, 252))
|
||||
draw.text((44, 78), "统一 176 px 显示高度 · 128×64 菱形格 · 固定裁切与脚底中心原点 · 待机/投掷节奏一致", font=subtitle, fill=(151, 171, 201))
|
||||
|
||||
labels = {"up": "UP 背面", "down": "DOWN 正面", "left": "LEFT 画面左", "right": "RIGHT 画面右"}
|
||||
arrows = {"up": "↑", "down": "↓", "left": "←", "right": "→"}
|
||||
for index, record in enumerate(records):
|
||||
direction = record["runtimeDirection"]
|
||||
x0 = 40 + index * 470
|
||||
y0 = 118
|
||||
draw.rounded_rectangle((x0, y0, x0 + 430, 650), radius=14, fill=(24, 30, 42), outline=(65, 82, 112), width=2)
|
||||
draw.text((x0 + 20, y0 + 18), f"{arrows[direction]} {labels[direction]}", font=heading, fill=(242, 246, 252))
|
||||
asset_id = record["assetDirectionId"]
|
||||
alias = f"运行时 {direction} ← 历史 {asset_id}" if record["legacyDirectionId"] else f"运行时与素材目录均为 {direction}"
|
||||
draw.text((x0 + 22, y0 + 58), alias, font=small, fill=(151, 171, 201))
|
||||
|
||||
center_x = x0 + 215
|
||||
foot_y = 500
|
||||
draw_diamond(draw, center_x, foot_y)
|
||||
crop_data = record["fixedCrop"]
|
||||
crop = (
|
||||
crop_data["x"],
|
||||
crop_data["y"],
|
||||
crop_data["x"] + crop_data["width"],
|
||||
crop_data["y"] + crop_data["height"],
|
||||
)
|
||||
cropped = neutrals[direction].crop(crop)
|
||||
output_height = 176
|
||||
output_width = max(1, round(cropped.width * output_height / cropped.height))
|
||||
resized = cropped.resize((output_width, output_height), Image.Resampling.LANCZOS)
|
||||
board.paste(resized, (center_x - output_width // 2, foot_y - output_height), resized)
|
||||
draw.line((center_x - 8, foot_y, center_x + 8, foot_y), fill=(255, 88, 116), width=3)
|
||||
|
||||
draw.rounded_rectangle((x0 + 20, 530, x0 + 410, 575), radius=8, fill=(31, 48, 56), outline=(66, 156, 121), width=1)
|
||||
draw.text((x0 + 34, 542), "ART TEMPLATE READY", font=body, fill=(132, 232, 184))
|
||||
draw.text((x0 + 20, 590), "idle 420 / 260 / 420 / 260 ms", font=small, fill=(200, 211, 229))
|
||||
draw.text((x0 + 20, 616), "throw 150 / 110 / 90 / 180 / 260 ms", font=small, fill=(200, 211, 229))
|
||||
|
||||
draw.rounded_rectangle((40, 674, 1880, 730), radius=10, fill=(22, 27, 38), outline=(52, 68, 94), width=1)
|
||||
draw.text((60, 690), "当前交付:PNG 帧动画优先接入;分解件与枢轴清单保留给后续 Skeleton2D。尚未完成 Godot 导入、纹理设置、碰撞/选择框及引擎内性能验证。", font=body, fill=(177, 190, 212))
|
||||
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
direction_map = load_json(DIRECTION_MAP_PATH)
|
||||
referenced: set[Path] = {DIRECTION_MAP_PATH}
|
||||
records = []
|
||||
neutrals = {}
|
||||
for direction in DIRECTION_ORDER:
|
||||
record, neutral = direction_record(direction, direction_map["directions"][direction], referenced)
|
||||
records.append(record)
|
||||
neutrals[direction] = neutral
|
||||
|
||||
canvas_sizes = {(record["sourceCanvas"]["width"], record["sourceCanvas"]["height"]) for record in records}
|
||||
if canvas_sizes != {(600, 760)}:
|
||||
raise ValueError(f"Runtime motion canvases are not normalized: {canvas_sizes}")
|
||||
|
||||
package = {
|
||||
"characterId": "02-xinyin",
|
||||
"characterNameZh": "汐月心音",
|
||||
"version": 1,
|
||||
"status": "art-template-ready",
|
||||
"engineIntegrationStatus": "not-started-no-godot-project",
|
||||
"recommendedIntegration": {
|
||||
"primary": "frame-animation",
|
||||
"description": "Import the validated full-frame PNG keyframes first; use decomposed parts and pivots for a later Skeleton2D implementation.",
|
||||
"spriteOrigin": "bottom-center",
|
||||
"textureFilter": "linear at 176/132 px; compare linear and nearest at 88 px in-engine",
|
||||
},
|
||||
"directionModel": {
|
||||
"type": direction_map["runtimeDirectionModel"],
|
||||
"directions": list(DIRECTION_ORDER),
|
||||
"selectionRule": direction_map["selectionRule"],
|
||||
"aimingRule": direction_map["aimingRule"],
|
||||
},
|
||||
"displayProfiles": list(DISPLAY_PROFILES),
|
||||
"animationContract": {
|
||||
"keyframes": [{"name": name, "durationMs": duration} for name, duration in EXPECTED_KEYFRAMES],
|
||||
"idle": {"frames": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral"], "cycleMs": 1360, "loop": True},
|
||||
"throw": {"frames": ["throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"], "cycleMs": 790, "loop": False},
|
||||
},
|
||||
"directions": records,
|
||||
"rebuildTools": [
|
||||
"tools/build_xinyin_motion_playback.py",
|
||||
"tools/build_xinyin_down_assembly.py",
|
||||
"tools/build_xinyin_down_motion.py",
|
||||
"tools/build_xinyin_up_assembly.py",
|
||||
"tools/build_xinyin_up_motion.py",
|
||||
"tools/build_xinyin_template_package.py",
|
||||
],
|
||||
"validation": {
|
||||
"directionCount": len(records),
|
||||
"allDirectionsMotionValidated": all(record["status"] == "motion-art-validated" for record in records),
|
||||
"commonMotionCanvas": {"width": 600, "height": 760},
|
||||
"allPlaybackBaselinesFixed": True,
|
||||
"referencedFileCount": len(referenced),
|
||||
"missingReferencedFiles": [],
|
||||
},
|
||||
"limitations": [
|
||||
"No Godot project exists yet, so import settings, AnimationPlayer/SpriteFrames resources, and engine-side playback remain unverified.",
|
||||
"Collision, selection, navigation, shadow, sorting, and VFX sockets are not part of this art-only package.",
|
||||
"LEFT and RIGHT retain legacy front-right/front-left directories; consume this package instead of guessing folder names.",
|
||||
"Body facing is four-cardinal while projectile and VFX aim are free-angle.",
|
||||
],
|
||||
}
|
||||
PACKAGE_PATH.write_text(json.dumps(package, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
make_preview(records, neutrals)
|
||||
for image in neutrals.values():
|
||||
image.close()
|
||||
|
||||
print(PACKAGE_PATH)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(package["validation"], ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,224 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from build_xinyin_down_assembly import checker, fit, item, paste_part, render_single
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
PARTS_DIR = CHARACTER / "parts/up/v1"
|
||||
MANIFEST_PATH = PARTS_DIR / "parts-manifest.json"
|
||||
MASTER_PATH = CHARACTER / "source/up/xinyin-up-neutral-master-v1.png"
|
||||
ASSEMBLED_DIR = CHARACTER / "assembled/up"
|
||||
ASSEMBLY_PATH = ASSEMBLED_DIR / "xinyin-up-neutral-assembly-v1.png"
|
||||
LAYOUT_PATH = ASSEMBLED_DIR / "assembly-layout-v1.json"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-up-assembly-validation-v1.png"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
CANVAS_SIZE = (600, 760)
|
||||
|
||||
|
||||
# Draw order is list order. X/Y are root-pivot positions on a 600x760 canvas.
|
||||
# UP side ownership is frozen: A = screen-right fan side, B = screen-left relaxed/pouch side.
|
||||
LAYOUT = [
|
||||
item("ponytail-root", 275, 95, -5, .55, "hair-back", "三段马尾根;位于后脑之后并向画面左侧展开"),
|
||||
item("ponytail-middle", 245, 190, -20, .55, "hair-back", "根枢轴贴合上一段远端关节并向画面左侧延伸"),
|
||||
item("ponytail-tip", 202, 287, -12, .55, "hair-back", "末端与中段内压重叠并继续向左下收束"),
|
||||
item("hair-cap", 300, 205, 0, .55, "hair-back", "后脑发帽;遮盖马尾根接缝"),
|
||||
|
||||
item("coat-panel-01", 215, 358, -5, .85, "cloth-back", "画面左外后层"),
|
||||
item("coat-panel-02", 238, 356, -4, .85, "cloth-back", "画面左后层"),
|
||||
item("coat-panel-03", 262, 357, -2, .85, "cloth-back", "中左后层"),
|
||||
item("coat-panel-04", 283, 358, -1, .85, "cloth-back", "中左层"),
|
||||
item("coat-panel-05", 317, 358, 1, .85, "cloth-back", "中右层"),
|
||||
item("coat-panel-06", 338, 357, 2, .85, "cloth-back", "中右后层"),
|
||||
item("coat-panel-07", 362, 356, 4, .85, "cloth-back", "画面右后层"),
|
||||
item("coat-panel-08", 385, 358, 5, .85, "cloth-back", "画面右外后层"),
|
||||
|
||||
item("thigh-b", 266, 382, -2, .62, "legs", "B 腿髋点;画面左"),
|
||||
item("shin-boot-b", 260, 564, -3, .50, "legs", "B 腿膝点;脚底基线候选"),
|
||||
item("thigh-a", 334, 382, 2, .62, "legs", "A 腿髋点;画面右"),
|
||||
item("shin-boot-a", 340, 564, 3, .50, "legs", "A 腿膝点;脚底基线候选"),
|
||||
|
||||
item("outer-sleeve-cape-b", 226, 241, -8, .65, "arms-back", "画面左放松手侧独立外袖披"),
|
||||
item("outer-sleeve-cape-a", 374, 241, 8, .65, "arms-back", "画面右持扇手侧独立外袖披"),
|
||||
item("upper-arm-b", 226, 241, -10, .33, "arms-back", "B 上臂;肩到肘"),
|
||||
item("forearm-b", 219, 289, -6, .38, "arms-back", "B 前臂;肘点与上臂末端内压重叠"),
|
||||
item("hand-relaxed-b", 210, 372, -5, .28, "arms-back", "B 放松手;腕点与前臂末端内压重叠"),
|
||||
item("upper-arm-a", 374, 241, 10, .33, "arms-back", "A 上臂;肩到肘"),
|
||||
item("forearm-a", 381, 289, 154, .38, "arms-back", "A 前臂向上回折;肘点内压重叠"),
|
||||
item("hand-fan-grip-a", 418, 214, 7, .28, "weapon", "A 持扇手;腕点与前臂末端内压重叠"),
|
||||
|
||||
item("torso-upper", 300, 360, 0, .60, "body", "背面躯干根位于腰线"),
|
||||
item("pelvis-hip-core", 300, 359, 0, .60, "body-overlay", "腰封、骨盆与中性后腰饰"),
|
||||
item("shoulder-armor-b", 228, 237, -10, .30, "body-overlay", "画面左放松手侧肩甲"),
|
||||
item("shoulder-armor-a", 372, 237, 10, .30, "body-overlay", "画面右持扇侧肩甲"),
|
||||
item("neck", 300, 220, 0, .50, "body-overlay", "背面颈部连接"),
|
||||
item("head-back", 300, 215, 0, .52, "head", "严格背面头部基底"),
|
||||
item("hair-nape-overlay", 300, 112, 0, .57, "head-overlay", "后脑与后颈发丝覆盖层"),
|
||||
item("hair-ornament-long", 252, 112, -3, .46, "head-overlay", "母版画面左侧长银花发饰"),
|
||||
]
|
||||
|
||||
|
||||
EXCLUDED = {
|
||||
"coat-panel-alt-09": "九选八中的动作替换候选",
|
||||
"rear-drape": "pelvis-hip-core 已含中性腰后布与系绳",
|
||||
"waist-pouch": "pelvis-hip-core 已含画面左侧腰包",
|
||||
"red-tassel-a": "中性站姿不重复叠加动作替换流苏",
|
||||
"red-tassel-b": "中性站姿不重复叠加动作替换流苏",
|
||||
"hand-throw-open-a": "投掷动作替换手",
|
||||
"weapon-fan-open": "hand-fan-grip-a 已包含中性持握羽扇",
|
||||
"weapon-blade-single": "投掷物,不用于中性持握",
|
||||
"weapon-double-feather": "攻击替换物,不用于中性持握",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
by_name = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {name: Image.open(PARTS_DIR / record["file"]).convert("RGBA") for name, record in by_name.items()}
|
||||
layout_names = {entry["name"] for entry in LAYOUT}
|
||||
all_names = set(by_name)
|
||||
if layout_names | set(EXCLUDED) != all_names:
|
||||
missing = sorted(all_names - layout_names - set(EXCLUDED))
|
||||
unknown = sorted(layout_names | set(EXCLUDED) - all_names)
|
||||
raise ValueError(f"Part accounting mismatch. missing={missing}, unknown={unknown}")
|
||||
|
||||
assembly = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
records = []
|
||||
entry_by_name = {entry["name"]: entry for entry in LAYOUT}
|
||||
for entry in LAYOUT:
|
||||
record = by_name[entry["name"]]
|
||||
pivot_record = record["rootPivot"]["outputPixels"]
|
||||
pivot = (pivot_record["x"], pivot_record["y"])
|
||||
paste_part(assembly, images[entry["name"]], pivot, (entry["x"], entry["y"]), entry["scale"], entry["rotation"])
|
||||
records.append({
|
||||
"part": entry["name"],
|
||||
"file": f"assets/images/2d-game-characters/02-xinyin/parts/up/v1/{record['file']}",
|
||||
"targetPivot": {"x": entry["x"], "y": entry["y"]},
|
||||
"rotationDegrees": entry["rotation"],
|
||||
"scale": entry["scale"],
|
||||
"group": entry["group"],
|
||||
"note": entry["note"],
|
||||
})
|
||||
|
||||
ASSEMBLED_DIR.mkdir(parents=True, exist_ok=True)
|
||||
assembly.save(ASSEMBLY_PATH)
|
||||
alpha = assembly.getchannel("A")
|
||||
visible_bbox = alpha.getbbox()
|
||||
edge_clear = not any((
|
||||
alpha.crop((0, 0, CANVAS_SIZE[0], 1)).getbbox(),
|
||||
alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])).getbbox(),
|
||||
alpha.crop((0, 0, 1, CANVAS_SIZE[1])).getbbox(),
|
||||
alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])).getbbox(),
|
||||
))
|
||||
|
||||
baselines = {}
|
||||
for name in ("shin-boot-b", "shin-boot-a"):
|
||||
entry = entry_by_name[name]
|
||||
record = by_name[name]
|
||||
pivot_record = record["rootPivot"]["outputPixels"]
|
||||
single = render_single(images[name], (pivot_record["x"], pivot_record["y"]), entry)
|
||||
bbox = single.getchannel("A").getbbox()
|
||||
baselines[name] = bbox[3] - 1 if bbox else None
|
||||
|
||||
layout_manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "up",
|
||||
"version": 1,
|
||||
"status": "art-assembly-validated",
|
||||
"canvas": {
|
||||
"width": CANVAS_SIZE[0],
|
||||
"height": CANVAS_SIZE[1],
|
||||
"origin": "top-left",
|
||||
"units": "pixels",
|
||||
"footOrigin": {"x": CANVAS_SIZE[0] // 2, "y": max(baselines.values())},
|
||||
},
|
||||
"sideConvention": manifest["sideConvention"],
|
||||
"sourceManifests": ["assets/images/2d-game-characters/02-xinyin/parts/up/v1/parts-manifest.json"],
|
||||
"items": records,
|
||||
"excludedParts": EXCLUDED,
|
||||
"validation": {
|
||||
"usedPartCount": len(records),
|
||||
"excludedPartCount": len(EXCLUDED),
|
||||
"allPartsAccountedFor": len(records) + len(EXCLUDED) == manifest["partCount"],
|
||||
"visibleAlphaBounds": {"x": visible_bbox[0], "y": visible_bbox[1], "width": visible_bbox[2] - visible_bbox[0], "height": visible_bbox[3] - visible_bbox[1]},
|
||||
"edgeTransparent": edge_clear,
|
||||
"leftBootBaselineY": baselines["shin-boot-b"],
|
||||
"rightBootBaselineY": baselines["shin-boot-a"],
|
||||
"baselineDeltaPixels": abs(baselines["shin-boot-b"] - baselines["shin-boot-a"]),
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side assembly candidate, not an engine rig.",
|
||||
"A/B ownership is frozen for UP and must not reuse the DOWN screen-side mapping.",
|
||||
"The pelvis core already contains neutral rear cloth, cords, tassels, and the side pouch; standalone waist pieces remain action replacements.",
|
||||
"The three-part ponytail chain is validated for the neutral pose; rotation extremes still require motion validation.",
|
||||
],
|
||||
}
|
||||
LAYOUT_PATH.write_text(json.dumps(layout_manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
board = Image.new("RGB", (1920, 980), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
panel_font = ImageFont.truetype(str(FONT_PATH), 25)
|
||||
text_font = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
muted = (151, 169, 198)
|
||||
draw.text((42, 24), "心音|UP 背面中性站姿装配验证 v1", font=title, fill=(240, 244, 252))
|
||||
draw.text((44, 78), "冻结母版 / 41 件中的 32 件中性选择 / 背面枢轴、层级与双脚基线", font=text_font, fill=muted)
|
||||
|
||||
panel_rects = [(42, 122, 622, 930), (654, 122, 1234, 930), (1266, 122, 1878, 930)]
|
||||
for rect in panel_rects:
|
||||
draw.rounded_rectangle(rect, radius=16, fill=(24, 30, 42), outline=(65, 82, 112), width=2)
|
||||
draw.text((62, 142), "A 冻结的 UP 母版", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((674, 142), "B 32 件部件重建", font=panel_font, fill=(240, 244, 252))
|
||||
draw.text((1286, 142), "C 枢轴、侧别与基线", font=panel_font, fill=(240, 244, 252))
|
||||
|
||||
master = fit(Image.open(MASTER_PATH).convert("RGBA"), (530, 720), 18)
|
||||
master_bg = checker((530, 720))
|
||||
master_bg.paste(master, ((530 - master.width) // 2, (720 - master.height) // 2), master)
|
||||
board.paste(master_bg, (67, 190))
|
||||
|
||||
assembly_bg = checker(CANVAS_SIZE)
|
||||
assembly_bg.paste(assembly, (0, 0), assembly)
|
||||
display = fit(assembly_bg, (540, 740))
|
||||
board.paste(display, (674 + (540 - display.width) // 2, 180))
|
||||
board.paste(display, (1302 + (540 - display.width) // 2, 180))
|
||||
|
||||
ox, oy = 1302, 180
|
||||
sx = display.width / CANVAS_SIZE[0]
|
||||
sy = display.height / CANVAS_SIZE[1]
|
||||
|
||||
def pt(x, y):
|
||||
return (round(ox + x * sx), round(oy + y * sy))
|
||||
|
||||
overlay = ImageDraw.Draw(board)
|
||||
chains = [
|
||||
[pt(300, 90), pt(300, 215), pt(300, 360)],
|
||||
[pt(228, 237), pt(219, 289), pt(210, 372)],
|
||||
[pt(372, 237), pt(381, 289), pt(418, 214)],
|
||||
[pt(300, 359), pt(266, 382), pt(260, 564), pt(260, baselines["shin-boot-b"])],
|
||||
[pt(300, 359), pt(334, 382), pt(340, 564), pt(340, baselines["shin-boot-a"])],
|
||||
]
|
||||
for chain in chains:
|
||||
for start, end in zip(chain, chain[1:]):
|
||||
overlay.line((*start, *end), fill=(69, 211, 255), width=4)
|
||||
for x, y in chain:
|
||||
overlay.ellipse((x - 6, y - 6, x + 6, y + 6), outline=(255, 87, 115), width=3)
|
||||
baseline_y = pt(300, max(baselines.values()))[1]
|
||||
overlay.line((1318, baseline_y, 1826, baseline_y), fill=(255, 204, 75), width=3)
|
||||
draw.text((1286, 853), f"A/B 固定:画面右持扇,画面左放松|脚底差 {abs(baselines['shin-boot-b'] - baselines['shin-boot-a'])} px", font=text_font, fill=(240, 244, 252))
|
||||
draw.text((1286, 883), "腰部替换件不重复叠加;三段马尾与八片衣摆进入动作极限测试。", font=text_font, fill=muted)
|
||||
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
print(ASSEMBLY_PATH)
|
||||
print(LAYOUT_PATH)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(layout_manifest["validation"], ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from build_xinyin_down_master_validation import (
|
||||
alpha_edges_clear,
|
||||
checker,
|
||||
contain,
|
||||
font,
|
||||
paste_center,
|
||||
)
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
GENERATED = ASSET_ROOT / "source/up/xinyin-up-neutral-master-generation-v1.png"
|
||||
MASTER = ASSET_ROOT / "source/up/xinyin-up-neutral-master-v1.png"
|
||||
MANIFEST = ASSET_ROOT / "source/up/master-manifest-v1.json"
|
||||
TURNAROUND = ASSET_ROOT / "previews/xinyin-4dir-turnaround-v1.png"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-up-master-validation-v1.png"
|
||||
MASTER_SIZE = (1152, 1664)
|
||||
MASTER_OFFSET = (64, 64)
|
||||
|
||||
|
||||
GENERATION_PROMPT = """Use case: stylized-concept
|
||||
Asset type: high-resolution 2D game character decomposition master
|
||||
Primary request: Generate one new full-body strict rear-view master illustration of the same female character 汐月心音 shown in the references, for the runtime UP direction.
|
||||
Input images: frozen DOWN identity/proportion reference; detailed front-left construction reference; rough four-way turnaround used only for rear costume relationships.
|
||||
Scene/backdrop: genuinely transparent background with generous transparent safety margin.
|
||||
Subject: the same adult light-chibi combat character, approximately 4.75 heads tall, in a neutral combat-ready strict orthographic back view; no face or profile; feet on one baseline.
|
||||
Fixed asymmetry: character-right fan hand on screen-right; character-left relaxed hand, black waist pouch, and long silver-flower hair ornament on screen-left; high ponytail flows mainly toward screen-left.
|
||||
Rear costume: back collar, shoulder straps, silver feather armor, fitted back bodice, red waist cords, rear knots, layered indigo/white coat panels, red tassels, armored leggings, rear boot armor and heels.
|
||||
Style/medium: polished anime game character illustration matching the approved references; clean high-resolution transparent PNG.
|
||||
Constraints: preserve identity, proportions, palette, costume motifs, weapon count, and asymmetry; strict rear view; no face, body twist, extra limbs, extra weapons, text, watermark, ground, shadow, scenery, or cropping."""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
generated = Image.open(GENERATED).convert("RGBA")
|
||||
if generated.width + MASTER_OFFSET[0] > MASTER_SIZE[0] or generated.height + MASTER_OFFSET[1] > MASTER_SIZE[1]:
|
||||
raise ValueError("Generated UP master does not fit the production canvas with the requested offset")
|
||||
master = Image.new("RGBA", MASTER_SIZE, (0, 0, 0, 0))
|
||||
master.alpha_composite(generated, MASTER_OFFSET)
|
||||
MASTER.parent.mkdir(parents=True, exist_ok=True)
|
||||
master.save(MASTER)
|
||||
|
||||
alpha = master.getchannel("A")
|
||||
bbox = alpha.getbbox()
|
||||
if bbox is None:
|
||||
raise ValueError("UP master is fully transparent")
|
||||
visible = master.crop(bbox)
|
||||
left_bbox = alpha.crop((0, 0, master.width // 2, master.height)).getbbox()
|
||||
right_bbox = alpha.crop((master.width // 2, 0, master.width, master.height)).getbbox()
|
||||
left_baseline = left_bbox[3] - 1 if left_bbox else None
|
||||
right_baseline = right_bbox[3] - 1 if right_bbox else None
|
||||
|
||||
turnaround = Image.open(TURNAROUND).convert("RGBA")
|
||||
old_reference = turnaround.crop((turnaround.width * 3 // 4, 0, turnaround.width, turnaround.height))
|
||||
|
||||
canvas = Image.new("RGBA", (1800, 1100), (25, 31, 43, 255))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252, 255)
|
||||
muted = (172, 184, 201, 255)
|
||||
blue = (104, 196, 255, 255)
|
||||
red = (255, 124, 124, 255)
|
||||
green = (124, 223, 166, 255)
|
||||
|
||||
draw.text((70, 42), "心音|运行时 UP 背面母版校验 v1", font=font(42), fill=white)
|
||||
draw.text((72, 98), "严格背面 · 约 4.75 头身 · 转身后固定侧别 · 透明高分辨率母版", font=font(22), fill=muted)
|
||||
|
||||
panels = [(60, 160, 535, 890), (570, 160, 1110, 890), (1145, 160, 1740, 890)]
|
||||
titles = ["A 旧背向造型参考", "B UP 背面母版 v1", "C 三档游戏轮廓检查"]
|
||||
for rect, title in zip(panels, titles):
|
||||
draw.rounded_rectangle(rect, radius=18, fill=(39, 48, 64, 255), outline=(72, 87, 109, 255), width=2)
|
||||
draw.text((rect[0] + 24, rect[1] + 20), title, font=font(24), fill=white)
|
||||
|
||||
ref = contain(old_reference, (427, 632), margin=8)
|
||||
paste_center(canvas, ref, (84, 218, 511, 850))
|
||||
|
||||
master_box = (594, 218, 1086, 850)
|
||||
canvas.alpha_composite(checker((master_box[2] - master_box[0], master_box[3] - master_box[1])), (master_box[0], master_box[1]))
|
||||
master_large = contain(visible, (master_box[2] - master_box[0], master_box[3] - master_box[1]), margin=18)
|
||||
paste_center(canvas, master_large, master_box)
|
||||
|
||||
scale_specs = [
|
||||
(352, "工作缩放 352 px", 1210, 240, (1180, 222, 1710, 610), (1450, 390)),
|
||||
(176, "游戏基准 176 px", 1210, 650, (1180, 630, 1445, 850), (1190, 610)),
|
||||
(88, "50% 检查 88 px", 1510, 730, (1470, 700, 1710, 850), (1478, 665)),
|
||||
]
|
||||
for height, label, x, y, background, label_pos in scale_specs:
|
||||
width = max(1, round(visible.width * height / visible.height))
|
||||
resized = visible.resize((width, height), Image.Resampling.LANCZOS)
|
||||
draw.rounded_rectangle(background, radius=12, fill=(31, 39, 53, 255))
|
||||
canvas.alpha_composite(resized, (x, y))
|
||||
draw.text(label_pos, label, font=font(21), fill=white)
|
||||
|
||||
draw.rounded_rectangle((60, 925, 1740, 1045), radius=16, fill=(34, 42, 57, 255))
|
||||
draw.text((88, 946), "冻结关系:", font=font(24), fill=white)
|
||||
draw.text((245, 946), "角色右手/画面右侧持扇", font=font(24), fill=blue)
|
||||
draw.text((570, 946), "腰包与放松手在画面左侧", font=font(24), fill=red)
|
||||
draw.text((936, 946), "头胸骨盆严格朝后", font=font(24), fill=green)
|
||||
draw.text((88, 992), "高马尾向画面左后方展开;双脚基线与身体主轴保持稳定,背部服装层级供后续分解使用。", font=font(20), fill=muted)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.convert("RGB").save(OUTPUT, quality=95)
|
||||
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "up",
|
||||
"version": 1,
|
||||
"status": "master-art-validated",
|
||||
"master": MASTER.relative_to(ROOT).as_posix(),
|
||||
"generationSource": GENERATED.relative_to(ROOT).as_posix(),
|
||||
"generationMode": "built-in-imagegen",
|
||||
"generationPrompt": GENERATION_PROMPT,
|
||||
"generationSourceSize": {"width": generated.width, "height": generated.height},
|
||||
"canvas": {"width": master.width, "height": master.height, "origin": "top-left", "units": "pixels"},
|
||||
"visibleAlphaBounds": {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]},
|
||||
"validation": {
|
||||
"edgeTransparent": alpha_edges_clear(alpha),
|
||||
"strictBackFacing": True,
|
||||
"targetHeadRatio": 4.75,
|
||||
"scaleChecks": [352, 176, 88],
|
||||
"weaponSide": "character-right / screen-right",
|
||||
"pouchSide": "character-left / screen-left",
|
||||
"longHairOrnamentSide": "character-left / screen-left",
|
||||
"ponytailFlow": "screen-left / behind-body",
|
||||
"footOrigin": "bottom-center",
|
||||
"leftVisibleBaselineY": left_baseline,
|
||||
"rightVisibleBaselineY": right_baseline,
|
||||
"baselineDeltaPixels": abs(left_baseline - right_baseline),
|
||||
},
|
||||
"referenceRoles": [
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/source/down/xinyin-down-neutral-master-v1.png", "role": "frozen identity, proportion, costume, palette, and front-facing asymmetry reference"},
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-neutral-master-v2.png", "role": "approved construction, material, and rendering reference"},
|
||||
{"file": "assets/images/2d-game-characters/02-xinyin/previews/xinyin-4dir-turnaround-v1.png", "role": "rough rear costume relationship reference only"},
|
||||
],
|
||||
"notes": [
|
||||
"The generation result is preserved separately; the production master adds a 64 px transparent top-left offset inside a 1152 x 1664 canvas.",
|
||||
"UP is a new strict-back direction and is not a mirrored or relabeled diagonal asset.",
|
||||
"This master is ready for source-sheet decomposition, but is not yet a runtime rig or sprite sequence.",
|
||||
],
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(MASTER)
|
||||
print(MANIFEST)
|
||||
print(OUTPUT)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,339 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from build_xinyin_down_motion import checker, serializable_transform
|
||||
from build_xinyin_up_assembly import FONT_PATH, LAYOUT, MANIFEST_PATH, PARTS_DIR, paste_part
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
OUTPUT_DIR = CHARACTER / "motion/up/v1"
|
||||
PREVIEW_PATH = CHARACTER / "previews/xinyin-up-motion-validation-v1.png"
|
||||
CANVAS_SIZE = (600, 760)
|
||||
|
||||
|
||||
FRAME_SPECS = [
|
||||
{
|
||||
"name": "idle-inhale",
|
||||
"label": "IDLE · INHALE",
|
||||
"durationMs": 420,
|
||||
"note": "肩背与头部轻微上提;画面左后方马尾略晚跟随。",
|
||||
"body_y": -3,
|
||||
"head_y": -4,
|
||||
"hair": (-4, -22, -14),
|
||||
"arm": (10, 153),
|
||||
"cape": 7,
|
||||
"coat": (-2, 2),
|
||||
},
|
||||
{
|
||||
"name": "idle-neutral",
|
||||
"label": "IDLE · NEUTRAL",
|
||||
"durationMs": 260,
|
||||
"note": "UP 装配 v1 的固定背面基准姿势。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"hair": (-5, -20, -12),
|
||||
"arm": (10, 154),
|
||||
"cape": 8,
|
||||
"coat": (0, 0),
|
||||
},
|
||||
{
|
||||
"name": "idle-exhale",
|
||||
"label": "IDLE · EXHALE",
|
||||
"durationMs": 420,
|
||||
"note": "肩背与头部下沉;软性部件收回,双脚基线保持不动。",
|
||||
"body_y": 2,
|
||||
"head_y": 3,
|
||||
"hair": (-6, -18, -10),
|
||||
"arm": (11, 155),
|
||||
"cape": 9,
|
||||
"coat": (2, -2),
|
||||
},
|
||||
{
|
||||
"name": "throw-ready",
|
||||
"label": "THROW · READY",
|
||||
"durationMs": 150,
|
||||
"note": "画面右侧持扇手上提,身体主轴仍保持背面。",
|
||||
"body_y": 0,
|
||||
"head_y": 0,
|
||||
"torso_rotation": 1,
|
||||
"hair": (-6, -23, -16),
|
||||
"arm": (22, 151),
|
||||
"cape": 22,
|
||||
"coat": (-2, 3),
|
||||
},
|
||||
{
|
||||
"name": "throw-windup",
|
||||
"label": "THROW · WINDUP",
|
||||
"durationMs": 110,
|
||||
"note": "持扇臂收至头侧蓄势;画面左后方马尾与衣摆反向压缩。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": -3,
|
||||
"head_rotation": -1,
|
||||
"hair": (-8, -28, -24),
|
||||
"arm": (30, -170),
|
||||
"cape": 28,
|
||||
"coat": (-5, 5),
|
||||
},
|
||||
{
|
||||
"name": "throw-release",
|
||||
"label": "THROW · RELEASE",
|
||||
"durationMs": 90,
|
||||
"note": "身体保持背面,持扇臂向画面右侧完全展开;张手和单枚脱手羽刃替换中性持握。",
|
||||
"body_y": 0,
|
||||
"head_y": -1,
|
||||
"torso_rotation": 3,
|
||||
"head_rotation": 1,
|
||||
"hair": (-2, -10, -5),
|
||||
"arm": (90, 90),
|
||||
"cape": 78,
|
||||
"coat": (6, -6),
|
||||
"release": True,
|
||||
},
|
||||
{
|
||||
"name": "throw-recover",
|
||||
"label": "THROW · RECOVER",
|
||||
"durationMs": 180,
|
||||
"note": "手臂回收;马尾与衣摆越过中位后准备回到待机。",
|
||||
"body_y": 1,
|
||||
"head_y": 1,
|
||||
"torso_rotation": 1,
|
||||
"head_rotation": -1,
|
||||
"hair": (-7, -16, -8),
|
||||
"arm": (38, 151),
|
||||
"cape": 34,
|
||||
"coat": (3, -4),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def rotated_joint(record, target, scale, angle):
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
next_joint = record["nextJoint"]["outputPixels"]
|
||||
dx = (next_joint["x"] - root["x"]) * scale
|
||||
dy = (next_joint["y"] - root["y"]) * scale
|
||||
radians = math.radians(angle)
|
||||
return (
|
||||
target[0] + math.cos(radians) * dx + math.sin(radians) * dy,
|
||||
target[1] - math.sin(radians) * dx + math.cos(radians) * dy,
|
||||
)
|
||||
|
||||
|
||||
def load_parts():
|
||||
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
||||
records = {record["name"]: record for record in manifest["parts"]}
|
||||
images = {name: Image.open(PARTS_DIR / record["file"]).convert("RGBA") for name, record in records.items()}
|
||||
return records, images
|
||||
|
||||
|
||||
def build_transforms(spec, records):
|
||||
transforms = {entry["name"]: copy.deepcopy(entry) for entry in LAYOUT}
|
||||
body_y = spec.get("body_y", 0)
|
||||
head_y = spec.get("head_y", 0)
|
||||
torso_rotation = spec.get("torso_rotation", 0)
|
||||
head_rotation = spec.get("head_rotation", 0)
|
||||
|
||||
# Pelvis and legs stay locked to the ground. Breathing only affects the upper body.
|
||||
transforms["torso-upper"]["y"] += body_y
|
||||
transforms["torso-upper"]["rotation"] += torso_rotation
|
||||
for name in ("shoulder-armor-a", "shoulder-armor-b"):
|
||||
transforms[name]["y"] += body_y
|
||||
for name in ("neck", "head-back", "hair-cap", "hair-nape-overlay", "hair-ornament-long"):
|
||||
transforms[name]["y"] += head_y
|
||||
for name in ("head-back", "hair-cap", "hair-nape-overlay", "hair-ornament-long"):
|
||||
transforms[name]["rotation"] += head_rotation
|
||||
|
||||
left_coat_delta, right_coat_delta = spec["coat"]
|
||||
for index in range(1, 5):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += left_coat_delta * (5 - index) / 4
|
||||
for index in range(5, 9):
|
||||
transforms[f"coat-panel-0{index}"]["rotation"] += right_coat_delta * (index - 4) / 4
|
||||
|
||||
# Relaxed B arm follows breathing but never joins the throw.
|
||||
for name in ("outer-sleeve-cape-b", "upper-arm-b", "forearm-b", "hand-relaxed-b"):
|
||||
transforms[name]["y"] += body_y
|
||||
transforms["outer-sleeve-cape-b"]["rotation"] += torso_rotation * 0.5
|
||||
transforms["upper-arm-b"]["rotation"] += torso_rotation * 0.5
|
||||
|
||||
root_angle, middle_angle, tip_angle = spec["hair"]
|
||||
hair_root = transforms["ponytail-root"]
|
||||
hair_root["x"] -= torso_rotation * 0.7
|
||||
hair_root["y"] += head_y
|
||||
hair_root["rotation"] = root_angle
|
||||
hair_middle = transforms["ponytail-middle"]
|
||||
hair_middle["x"] -= torso_rotation * 1.2
|
||||
hair_middle["y"] += head_y * 0.7
|
||||
hair_middle["rotation"] = middle_angle
|
||||
hair_tip = transforms["ponytail-tip"]
|
||||
hair_tip["x"] -= torso_rotation * 2.0
|
||||
hair_tip["y"] += head_y * 0.4
|
||||
hair_tip["rotation"] = tip_angle
|
||||
|
||||
upper_rotation, forearm_rotation = spec["arm"]
|
||||
shoulder = (374 + torso_rotation * 0.8, 241 + body_y)
|
||||
upper = transforms["upper-arm-a"]
|
||||
upper.update({"x": shoulder[0], "y": shoulder[1], "rotation": upper_rotation})
|
||||
elbow_joint = rotated_joint(records["upper-arm-a"], shoulder, upper["scale"], upper_rotation)
|
||||
elbow = (elbow_joint[0] - 2, elbow_joint[1] - 7)
|
||||
forearm = transforms["forearm-a"]
|
||||
forearm_scale = 0.34 if spec.get("release") else 0.38
|
||||
forearm.update({"x": elbow[0], "y": elbow[1], "rotation": forearm_rotation, "scale": forearm_scale})
|
||||
wrist_joint = rotated_joint(records["forearm-a"], elbow, forearm_scale, forearm_rotation)
|
||||
wrist = (wrist_joint[0] + 2, wrist_joint[1] - 4)
|
||||
hand = transforms["hand-fan-grip-a"]
|
||||
hand.update({"x": wrist[0], "y": wrist[1], "rotation": forearm_rotation - 147})
|
||||
cape = transforms["outer-sleeve-cape-a"]
|
||||
cape.update({"x": shoulder[0], "y": shoulder[1], "rotation": spec["cape"]})
|
||||
|
||||
if spec.get("release"):
|
||||
hand["visible"] = False
|
||||
return transforms, shoulder, elbow, wrist
|
||||
|
||||
|
||||
def render_frame(spec, records, images):
|
||||
transforms, shoulder, elbow, wrist = build_transforms(spec, records)
|
||||
canvas = Image.new("RGBA", CANVAS_SIZE, (0, 0, 0, 0))
|
||||
serialized = []
|
||||
for entry in LAYOUT:
|
||||
name = entry["name"]
|
||||
transform = transforms[name]
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
if not transform.get("visible", True):
|
||||
continue
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(canvas, images[name], (pivot["x"], pivot["y"]), (transform["x"], transform["y"]), transform["scale"], transform["rotation"])
|
||||
|
||||
if spec.get("release"):
|
||||
open_hand = {"x": wrist[0], "y": wrist[1], "rotation": 180, "scale": 0.27, "visible": True}
|
||||
blade = {"x": min(CANVAS_SIZE[0] - 24, wrist[0] + 68), "y": wrist[1] - 8, "rotation": 90, "scale": 0.32, "visible": True}
|
||||
for name, transform in (("hand-throw-open-a", open_hand), ("weapon-blade-single", blade)):
|
||||
pivot = records[name]["rootPivot"]["outputPixels"]
|
||||
paste_part(canvas, images[name], (pivot["x"], pivot["y"]), (transform["x"], transform["y"]), transform["scale"], transform["rotation"])
|
||||
serialized.append(serializable_transform(name, transform))
|
||||
|
||||
joints = {
|
||||
"Shoulder": [round(shoulder[0], 2), round(shoulder[1], 2)],
|
||||
"Elbow": [round(elbow[0], 2), round(elbow[1], 2)],
|
||||
"Wrist": [round(wrist[0], 2), round(wrist[1], 2)],
|
||||
}
|
||||
return canvas, serialized, joints
|
||||
|
||||
|
||||
def make_preview(frames):
|
||||
board = Image.new("RGB", (1560, 1050), (17, 21, 30))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 38)
|
||||
label_font = ImageFont.truetype(str(FONT_PATH), 21)
|
||||
note_font = ImageFont.truetype(str(FONT_PATH), 17)
|
||||
draw.text((42, 25), "心音|运行时 UP 动作验证 v1", font=title_font, fill=(242, 246, 252))
|
||||
draw.text((44, 78), "严格背面身体 · 固定脚底基线 · 待机呼吸 3 帧 + 向画面右侧投掷 4 帧", font=note_font, fill=(151, 169, 198))
|
||||
cells = [(42 + 378 * col, 120 + 455 * row) for row in range(2) for col in range(4)]
|
||||
for (spec, frame), (x, y) in zip(frames, cells):
|
||||
draw.rounded_rectangle((x, y, x + 352, y + 425), radius=14, fill=(25, 31, 43), outline=(65, 82, 112), width=2)
|
||||
draw.text((x + 16, y + 13), spec["label"], font=label_font, fill=(241, 245, 252))
|
||||
preview = frame.copy()
|
||||
preview.thumbnail((324, 346), Image.Resampling.LANCZOS)
|
||||
bg = checker((324, 346))
|
||||
bg.paste(preview, ((324 - preview.width) // 2, (346 - preview.height) // 2), preview)
|
||||
board.paste(bg, (x + 14, y + 52))
|
||||
draw.text((x + 16, y + 402), f"{spec['durationMs']} ms", font=note_font, fill=(151, 169, 198))
|
||||
draw.text((1176, 590), "验证重点", font=label_font, fill=(241, 245, 252))
|
||||
notes = [
|
||||
"• 身体主轴保持背面,不借侧身强化动作",
|
||||
"• 双脚与地面原点在全部帧中锁定",
|
||||
"• 画面右侧 A 手臂按肩—肘—腕链连接",
|
||||
"• 释放帧使用张手与单枚脱手羽刃替换件",
|
||||
]
|
||||
for index, note in enumerate(notes):
|
||||
draw.text((1178, 635 + index * 36), note, font=note_font, fill=(174, 188, 211))
|
||||
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW_PATH, quality=95)
|
||||
|
||||
|
||||
def main():
|
||||
records, images = load_parts()
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
frames = []
|
||||
manifest_frames = []
|
||||
baselines = []
|
||||
bounds = []
|
||||
edge_transparent = True
|
||||
for spec in FRAME_SPECS:
|
||||
frame, transforms, joints = render_frame(spec, records, images)
|
||||
frame_path = OUTPUT_DIR / f"{spec['name']}.png"
|
||||
frame.save(frame_path)
|
||||
frames.append((spec, frame))
|
||||
bbox = frame.getchannel("A").getbbox()
|
||||
if bbox is None:
|
||||
raise ValueError(f"Frame {spec['name']} is fully transparent")
|
||||
bounds.append(bbox)
|
||||
baselines.append(bbox[3] - 1)
|
||||
alpha = frame.getchannel("A")
|
||||
edges = [
|
||||
alpha.crop((0, 0, CANVAS_SIZE[0], 1)),
|
||||
alpha.crop((0, CANVAS_SIZE[1] - 1, CANVAS_SIZE[0], CANVAS_SIZE[1])),
|
||||
alpha.crop((0, 0, 1, CANVAS_SIZE[1])),
|
||||
alpha.crop((CANVAS_SIZE[0] - 1, 0, CANVAS_SIZE[0], CANVAS_SIZE[1])),
|
||||
]
|
||||
edge_transparent = edge_transparent and all(edge.getbbox() is None for edge in edges)
|
||||
manifest_frames.append({
|
||||
"name": spec["name"],
|
||||
"label": spec["label"],
|
||||
"file": frame_path.name,
|
||||
"durationMs": spec["durationMs"],
|
||||
"note": spec["note"],
|
||||
"joints": joints,
|
||||
"transforms": transforms,
|
||||
})
|
||||
|
||||
make_preview(frames)
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "up",
|
||||
"runtimeDirection": "up",
|
||||
"version": 1,
|
||||
"status": "art-motion-validated",
|
||||
"canvas": {"width": CANVAS_SIZE[0], "height": CANVAS_SIZE[1], "origin": "top-left", "units": "pixels"},
|
||||
"baseLayout": "assets/images/2d-game-characters/02-xinyin/assembled/up/assembly-layout-v1.json",
|
||||
"sourceManifests": ["assets/images/2d-game-characters/02-xinyin/parts/up/v1/parts-manifest.json"],
|
||||
"sequence": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral", "throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"],
|
||||
"loopNotes": {
|
||||
"idle": "inhale → neutral → exhale → neutral",
|
||||
"throw": "ready → windup → release → recover",
|
||||
},
|
||||
"frames": manifest_frames,
|
||||
"validation": {
|
||||
"edgeTransparent": edge_transparent,
|
||||
"baselineYByFrame": dict(zip((spec["name"] for spec in FRAME_SPECS), baselines)),
|
||||
"baselineDeltaPixels": max(baselines) - min(baselines),
|
||||
"visibleAlphaBoundsByFrame": {
|
||||
spec["name"]: {"x": bbox[0], "y": bbox[1], "width": bbox[2] - bbox[0], "height": bbox[3] - bbox[1]}
|
||||
for spec, bbox in zip(FRAME_SPECS, bounds)
|
||||
},
|
||||
"jointChains": [
|
||||
"upper-arm-a → forearm-a → hand",
|
||||
"ponytail-root / ponytail-middle / ponytail-tip with neutral-overlap offsets",
|
||||
],
|
||||
},
|
||||
"warnings": [
|
||||
"This is an art-side motion validation set, not an engine animation resource.",
|
||||
"UP keeps the torso back-facing while the fan-side arm releases toward screen-right for readability.",
|
||||
"Projectile and VFX aim remain free-angle at runtime; the body animation is four-cardinal.",
|
||||
],
|
||||
}
|
||||
manifest_path = OUTPUT_DIR / "motion-manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(manifest_path)
|
||||
print(PREVIEW_PATH)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,168 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
ASSET_ROOT = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE_DIR = ASSET_ROOT / "source/up"
|
||||
MASTER = SOURCE_DIR / "xinyin-up-neutral-master-v1.png"
|
||||
CORE = SOURCE_DIR / "xinyin-up-core-parts-sheet-v2.png"
|
||||
SOFT = SOURCE_DIR / "xinyin-up-soft-parts-sheet-v2.png"
|
||||
CORE_DIAGNOSTIC = ASSET_ROOT / "diagnostics/xinyin-up-core-parts-v2-components.png"
|
||||
CORE_COMPONENTS = ASSET_ROOT / "diagnostics/xinyin-up-core-parts-v2-components.json"
|
||||
SOFT_DIAGNOSTIC = ASSET_ROOT / "diagnostics/xinyin-up-soft-parts-v2-components.png"
|
||||
SOFT_COMPONENTS = ASSET_ROOT / "diagnostics/xinyin-up-soft-parts-v2-components.json"
|
||||
MANIFEST = SOURCE_DIR / "source-sheet-manifest-v1.json"
|
||||
OUTPUT = ASSET_ROOT / "previews/xinyin-up-parts-sheets-validation-v1.png"
|
||||
FONT = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
|
||||
|
||||
def font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT), size)
|
||||
|
||||
|
||||
def contain(image: Image.Image, size: tuple[int, int], margin: int = 0) -> Image.Image:
|
||||
result = image.copy()
|
||||
result.thumbnail((size[0] - margin * 2, size[1] - margin * 2), Image.Resampling.LANCZOS)
|
||||
return result
|
||||
|
||||
|
||||
def paste_center(canvas: Image.Image, image: Image.Image, rect: tuple[int, int, int, int]) -> None:
|
||||
x0, y0, x1, y1 = rect
|
||||
canvas.alpha_composite(image, (x0 + (x1 - x0 - image.width) // 2, y0 + (y1 - y0 - image.height) // 2))
|
||||
|
||||
|
||||
def corners_transparent(image: Image.Image) -> bool:
|
||||
alpha = image.getchannel("A")
|
||||
width, height = image.size
|
||||
return all(alpha.getpixel(point) == 0 for point in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
master = Image.open(MASTER).convert("RGBA")
|
||||
core = Image.open(CORE).convert("RGBA")
|
||||
soft = Image.open(SOFT).convert("RGBA")
|
||||
core_diagnostic = Image.open(CORE_DIAGNOSTIC).convert("RGBA")
|
||||
soft_diagnostic = Image.open(SOFT_DIAGNOSTIC).convert("RGBA")
|
||||
core_scan = json.loads(CORE_COMPONENTS.read_text(encoding="utf-8-sig"))
|
||||
soft_scan = json.loads(SOFT_COMPONENTS.read_text(encoding="utf-8-sig"))
|
||||
|
||||
if core_scan["componentCount"] != 17:
|
||||
raise ValueError(f"Expected 17 core components, got {core_scan['componentCount']}")
|
||||
if soft_scan["componentCount"] != 24:
|
||||
raise ValueError(f"Expected 24 soft components, got {soft_scan['componentCount']}")
|
||||
|
||||
manifest = {
|
||||
"character": "02-xinyin",
|
||||
"direction": "up",
|
||||
"version": 1,
|
||||
"status": "source-sheets-alpha-validated",
|
||||
"generationMode": "built-in-imagegen",
|
||||
"directionReference": "xinyin-up-neutral-master-v1.png",
|
||||
"sideConvention": {
|
||||
"A": "screen-right / character-right / fan-hand side",
|
||||
"B": "screen-left / character-left / relaxed-hand and pouch side",
|
||||
},
|
||||
"sheets": [
|
||||
{
|
||||
"id": "core",
|
||||
"file": CORE.name,
|
||||
"canvas": list(core.size),
|
||||
"componentCount": core_scan["componentCount"],
|
||||
"contents": [
|
||||
"rear-upper-torso", "rear-pelvis-hip-core", "rear-head-base", "shoulder-armor-a",
|
||||
"shoulder-armor-b", "rear-neck-connector", "fan-grip-hand-a", "upper-arm-a",
|
||||
"upper-arm-b", "forearm-a", "forearm-b", "relaxed-hand-b", "throw-open-hand-a",
|
||||
"rear-thigh-a", "rear-thigh-b", "rear-lower-leg-boot-a", "rear-lower-leg-boot-b",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "soft-accessories",
|
||||
"file": SOFT.name,
|
||||
"canvas": list(soft.size),
|
||||
"componentCount": soft_scan["componentCount"],
|
||||
"contents": [
|
||||
"rear-nape-hair-overlay", "rear-head-hair-cap", "ponytail-root", "ponytail-middle",
|
||||
"ponytail-tip", "silver-floral-hair-ornament", "outer-sleeve-cape-a", "outer-sleeve-cape-b",
|
||||
"rear-coat-panel-01", "rear-coat-panel-02", "rear-coat-panel-03", "rear-coat-panel-04",
|
||||
"rear-coat-panel-05", "rear-coat-panel-06", "rear-coat-panel-07", "rear-coat-panel-08",
|
||||
"rear-coat-panel-alt-09", "central-rear-drape", "waist-pouch", "red-tassel-a",
|
||||
"red-tassel-b", "weapon-fan-open", "weapon-blade-single", "weapon-double-feather",
|
||||
],
|
||||
},
|
||||
],
|
||||
"rejectedOrSupersededSheets": [
|
||||
{
|
||||
"file": "xinyin-up-core-parts-sheet-v1.png",
|
||||
"reason": "Upper-arm A/B were composite sleeve-capes rather than compact shoulder-to-elbow rig segments.",
|
||||
},
|
||||
{
|
||||
"file": "xinyin-up-soft-parts-sheet-v1.png",
|
||||
"reason": "Sleeve-capes baked in shoulder armor and several coat panels baked in tassels/chains, preventing clean layer ownership.",
|
||||
},
|
||||
],
|
||||
"generationPromptSet": [
|
||||
"Generate a strict-rear 17-object core sheet in an invisible 6x3 grid from the approved UP master, with A on screen-right fan side and B on screen-left relaxed side.",
|
||||
"Correct only the two core upper arms into compact black shoulder-to-elbow segments while preserving the other 15 objects.",
|
||||
"Generate a strict-rear 24-object soft/accessory sheet in an invisible 6x4 grid: rear hair chain, two sleeve-capes, nine coat panels, rear drape, pouch, tassels, and weapons.",
|
||||
"Remove baked shoulder armor from sleeve-capes and remove baked tassels/chains from all nine coat panels while preserving the other parts.",
|
||||
],
|
||||
"validation": {
|
||||
"alphaThreshold": 16,
|
||||
"minimumComponentArea": 80,
|
||||
"edgeCornersTransparent": corners_transparent(core) and corners_transparent(soft),
|
||||
"touchingComponents": False,
|
||||
"coreComponentCount": core_scan["componentCount"],
|
||||
"softComponentCount": soft_scan["componentCount"],
|
||||
"notes": [
|
||||
"Adopted core v2 has exactly 17 disconnected alpha components and compact independent upper arms.",
|
||||
"Adopted soft v2 has exactly 24 disconnected alpha components in an invisible 6x4 production grid.",
|
||||
"Sleeve-capes do not own shoulder armor; the nine coat panels do not own red tassels or hanging chains.",
|
||||
"Part names, exact component mapping, pivots, and parent links remain provisional until independent extraction.",
|
||||
],
|
||||
},
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
canvas = Image.new("RGBA", (2000, 1240), (24, 30, 42, 255))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
white = (242, 246, 252, 255)
|
||||
muted = (166, 181, 205, 255)
|
||||
blue = (98, 205, 255, 255)
|
||||
green = (123, 225, 170, 255)
|
||||
|
||||
draw.text((48, 30), "心音|UP 背面分解源板验证 v1", font=font(40), fill=white)
|
||||
draw.text((50, 82), "采用核心板 v2 17 件 + 软性/附件板 v2 24 件 · Alpha 阈值 16 · 8 邻域连通检测", font=font(21), fill=muted)
|
||||
|
||||
panels = [
|
||||
((42, 126, 470, 1178), "A UP 背面母版"),
|
||||
((500, 126, 1958, 625), "B 核心身体/四肢板 v2 · 17 件"),
|
||||
((500, 650, 1958, 1178), "C 头发/衣摆/附件板 v2 · 24 件"),
|
||||
]
|
||||
for rect, title in panels:
|
||||
draw.rounded_rectangle(rect, radius=16, fill=(34, 42, 57, 255), outline=(68, 84, 108, 255), width=2)
|
||||
draw.text((rect[0] + 22, rect[1] + 18), title, font=font(23), fill=white)
|
||||
|
||||
master_visible = master.crop(master.getchannel("A").getbbox())
|
||||
paste_center(canvas, contain(master_visible, (380, 940), 12), (66, 190, 446, 1130))
|
||||
paste_center(canvas, contain(core_diagnostic, (1400, 400), 8), (526, 190, 1932, 606))
|
||||
paste_center(canvas, contain(soft_diagnostic, (1400, 420), 8), (526, 716, 1932, 1150))
|
||||
|
||||
draw.text((72, 1128), "严格背面", font=font(20), fill=blue)
|
||||
draw.text((205, 1128), "A 右持扇/B 左放松", font=font(20), fill=green)
|
||||
draw.text((1530, 590), "17 / 17 独立", font=font(19), fill=green)
|
||||
draw.text((1510, 1142), "24 / 24 独立", font=font(19), fill=green)
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.convert("RGB").save(OUTPUT, quality=95)
|
||||
print(MANIFEST)
|
||||
print(OUTPUT)
|
||||
print(json.dumps(manifest["validation"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,245 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE_DIR = CHARACTER / "source/down"
|
||||
DIAGNOSTIC_DIR = CHARACTER / "diagnostics"
|
||||
OUTPUT_DIR = CHARACTER / "parts/down/v1"
|
||||
PREVIEW = CHARACTER / "previews/xinyin-down-extracted-parts-v1.png"
|
||||
MANIFEST = OUTPUT_DIR / "parts-manifest.json"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
PADDING = 10
|
||||
ALPHA_THRESHOLD = 16
|
||||
|
||||
|
||||
SHEETS = {
|
||||
"core": {
|
||||
"source": SOURCE_DIR / "xinyin-down-core-parts-sheet-v1.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-down-core-parts-v1-components.json",
|
||||
"expected": 17,
|
||||
},
|
||||
"soft": {
|
||||
"source": SOURCE_DIR / "xinyin-down-soft-parts-sheet-v2.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-down-soft-parts-v2-components.json",
|
||||
"expected": 24,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def part(sheet, component_id, name, label, category, pivot, next_joint, parent, layer, note):
|
||||
return {
|
||||
"sheet": sheet,
|
||||
"componentId": component_id,
|
||||
"name": name,
|
||||
"labelZh": label,
|
||||
"category": category,
|
||||
"pivot": pivot,
|
||||
"next": next_joint,
|
||||
"parent": parent,
|
||||
"layer": layer,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
# A = screen-left / character-right / fan hand side. B = screen-right / character-left / relaxed hand side.
|
||||
PARTS = [
|
||||
part("core", 1, "torso-upper", "上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "正面主躯干;不含手臂与肩甲"),
|
||||
part("core", 2, "pelvis-hip-core", "骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根候选;双腿和衣摆挂接于此"),
|
||||
part("core", 3, "head-face", "头部与面部", "body", (.50, .91), None, "neck", 30, "严格正面;不含前发"),
|
||||
part("core", 4, "shoulder-armor-a", "肩甲 A/画面左", "armor", (.72, .24), None, "torso-upper", 20, "持扇手侧;固定于躯干"),
|
||||
part("core", 5, "shoulder-armor-b", "肩甲 B/画面右", "armor", (.28, .24), None, "torso-upper", 20, "放松手侧;固定于躯干"),
|
||||
part("core", 6, "neck", "颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接头部"),
|
||||
part("core", 8, "upper-arm-a", "上臂 A/画面左", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "持扇手侧;不含肩甲与袖披"),
|
||||
part("core", 9, "upper-arm-b", "上臂 B/画面右", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "放松手侧;不含肩甲与袖披"),
|
||||
part("core", 10, "forearm-a", "前臂 A/画面左", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "持扇手侧肘到腕"),
|
||||
part("core", 11, "forearm-b", "前臂 B/画面右", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "放松手侧肘到腕"),
|
||||
part("core", 7, "hand-fan-grip-a", "持扇手 A", "hand", (.50, .88), None, "forearm-a", 18, "画面左侧;含三羽持握形态"),
|
||||
part("core", 12, "hand-relaxed-b", "放松手 B", "hand", (.50, .08), None, "forearm-b", 18, "画面右侧;腕点位于上端"),
|
||||
part("core", 13, "hand-throw-open-a", "投掷张手 A", "hand", (.18, .18), None, "forearm-a", 18, "持扇手侧动作替换件"),
|
||||
part("core", 14, "thigh-a", "大腿 A/画面左", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面左髋点到膝点"),
|
||||
part("core", 15, "thigh-b", "大腿 B/画面右", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面右髋点到膝点"),
|
||||
part("core", 16, "shin-boot-a", "小腿与靴 A/画面左", "leg", (.50, .05), None, "thigh-a", -7, "画面左;膝点位于上端"),
|
||||
part("core", 17, "shin-boot-b", "小腿与靴 B/画面右", "leg", (.50, .05), None, "thigh-b", -7, "画面右;膝点位于上端"),
|
||||
part("soft", 5, "hair-front", "前发与双侧鬓", "hair", (.50, .12), None, "head-face", 35, "位于面部之前"),
|
||||
part("soft", 6, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-face", -90, "位于头部之后;马尾根父节点"),
|
||||
part("soft", 1, "ponytail-root", "马尾根部", "hair", (.48, .10), (.46, .88), "hair-cap", -96, "含银花冠;根部到第一连接点"),
|
||||
part("soft", 2, "ponytail-middle", "马尾中段", "hair", (.50, .08), (.50, .90), "ponytail-root", -95, "上下端预留重叠"),
|
||||
part("soft", 4, "ponytail-tip", "马尾末端", "hair", (.50, .08), None, "ponytail-middle", -94, "末端链节"),
|
||||
part("soft", 3, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-face", 42, "画面右侧独立装饰层"),
|
||||
part("soft", 8, "outer-sleeve-cape-a", "外袖披 A/画面左", "cloth", (.50, .08), None, "upper-arm-a", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
||||
part("soft", 7, "outer-sleeve-cape-b", "外袖披 B/画面右", "cloth", (.50, .08), None, "upper-arm-b", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
||||
part("soft", 10, "coat-panel-01", "衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "中性八片之一"),
|
||||
part("soft", 11, "coat-panel-02", "衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "中性八片之一"),
|
||||
part("soft", 9, "coat-panel-03", "衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中性八片之一"),
|
||||
part("soft", 12, "coat-panel-04", "衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中性八片之一"),
|
||||
part("soft", 13, "coat-panel-05", "衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中性八片之一"),
|
||||
part("soft", 16, "coat-panel-06", "衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中性八片之一"),
|
||||
part("soft", 15, "coat-panel-07", "衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "中性八片之一"),
|
||||
part("soft", 17, "coat-panel-08", "衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "中性八片之一"),
|
||||
part("soft", 22, "coat-panel-alt-09", "衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作轮廓替换件"),
|
||||
part("soft", 14, "front-drape", "中央腰前布", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "不含独立替换流苏"),
|
||||
part("soft", 18, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面右侧腰部"),
|
||||
part("soft", 19, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
||||
part("soft", 20, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
||||
part("soft", 21, "weapon-fan-open", "三羽展开扇", "weapon", (.50, .88), None, "hand-fan-grip-a", 50, "无手;与持扇手分层装配"),
|
||||
part("soft", 24, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"),
|
||||
part("soft", 23, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"),
|
||||
]
|
||||
|
||||
|
||||
def load_labels(source_path: Path, diagnostic_path: Path):
|
||||
rgba = np.array(Image.open(source_path).convert("RGBA"))
|
||||
alpha = rgba[:, :, 3]
|
||||
labels_image = Image.fromarray(np.where(alpha >= ALPHA_THRESHOLD, 255, 0).astype(np.uint8), "L").copy()
|
||||
diagnostic = json.loads(diagnostic_path.read_text(encoding="utf-8-sig"))
|
||||
for component in diagnostic["components"]:
|
||||
current = np.array(labels_image)
|
||||
y = component["y"]
|
||||
x0 = component["x"]
|
||||
x1 = x0 + component["width"]
|
||||
candidates = np.flatnonzero(current[y, x0:x1] == 255)
|
||||
if not len(candidates):
|
||||
raise RuntimeError(f"No flood-fill seed for {source_path.name} component {component['id']}")
|
||||
ImageDraw.floodfill(labels_image, (x0 + int(candidates[0]), y), component["id"], thresh=0)
|
||||
labels = np.array(labels_image)
|
||||
for _ in range(8):
|
||||
pending = np.argwhere(labels == 255)
|
||||
if not len(pending):
|
||||
break
|
||||
changed = 0
|
||||
for y, x in pending:
|
||||
neighbours = labels[max(0, y - 1) : min(labels.shape[0], y + 2), max(0, x - 1) : min(labels.shape[1], x + 2)]
|
||||
valid = neighbours[(neighbours > 0) & (neighbours < 255)]
|
||||
if len(valid):
|
||||
values, counts = np.unique(valid, return_counts=True)
|
||||
labels[y, x] = values[np.argmax(counts)]
|
||||
changed += 1
|
||||
if not changed:
|
||||
break
|
||||
return rgba, labels, diagnostic
|
||||
|
||||
|
||||
def joint_record(normalized, width, height):
|
||||
if normalized is None:
|
||||
return None
|
||||
return {
|
||||
"contentNormalized": {"x": normalized[0], "y": normalized[1]},
|
||||
"outputPixels": {
|
||||
"x": round(PADDING + width * normalized[0], 2),
|
||||
"y": round(PADDING + height * normalized[1], 2),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def draw_cross(draw, x, y, color, radius=7, width=3):
|
||||
draw.line((x - radius, y, x + radius, y), fill=color, width=width)
|
||||
draw.line((x, y - radius, x, y + radius), fill=color, width=width)
|
||||
|
||||
|
||||
def main():
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
|
||||
loaded = {key: load_labels(value["source"], value["diagnostic"]) for key, value in SHEETS.items()}
|
||||
for key, (_, labels, diagnostic) in loaded.items():
|
||||
expected = SHEETS[key]["expected"]
|
||||
if len(diagnostic["components"]) != expected:
|
||||
raise RuntimeError(f"Expected {expected} components for {key}")
|
||||
if any(not np.any(labels == component_id) for component_id in range(1, expected + 1)):
|
||||
raise RuntimeError(f"Missing labeled component in {key}")
|
||||
|
||||
manifest_parts = []
|
||||
exported = []
|
||||
for spec in PARTS:
|
||||
rgba, labels, diagnostic = loaded[spec["sheet"]]
|
||||
component = diagnostic["components"][spec["componentId"] - 1]
|
||||
x, y, width, height = (component[k] for k in ("x", "y", "width", "height"))
|
||||
crop = rgba[y : y + height, x : x + width].copy()
|
||||
mask = labels[y : y + height, x : x + width] == spec["componentId"]
|
||||
crop[~mask] = 0
|
||||
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
|
||||
output[PADDING : PADDING + height, PADDING : PADDING + width] = crop
|
||||
image = Image.fromarray(output, "RGBA")
|
||||
prefix = "down-core" if spec["sheet"] == "core" else "down-soft"
|
||||
filename = f"{prefix}-c{spec['componentId']:02d}-{spec['name']}.png"
|
||||
image.save(OUTPUT_DIR / filename)
|
||||
record = {
|
||||
"sourceSheet": spec["sheet"],
|
||||
"componentId": spec["componentId"],
|
||||
"name": spec["name"],
|
||||
"labelZh": spec["labelZh"],
|
||||
"category": spec["category"],
|
||||
"file": filename,
|
||||
"parent": spec["parent"],
|
||||
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
|
||||
"outputSize": {"width": image.width, "height": image.height},
|
||||
"rootPivot": joint_record(spec["pivot"], width, height),
|
||||
"nextJoint": joint_record(spec["next"], width, height),
|
||||
"suggestedLayer": spec["layer"],
|
||||
"notes": spec["note"],
|
||||
}
|
||||
manifest_parts.append(record)
|
||||
exported.append((spec, record, image))
|
||||
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"characterNameZh": "汐月心音",
|
||||
"direction": "down",
|
||||
"version": 1,
|
||||
"status": "extracted-unvalidated",
|
||||
"sources": {
|
||||
"core": "assets/images/2d-game-characters/02-xinyin/source/down/xinyin-down-core-parts-sheet-v1.png",
|
||||
"soft": "assets/images/2d-game-characters/02-xinyin/source/down/xinyin-down-soft-parts-sheet-v2.png",
|
||||
},
|
||||
"padding": PADDING,
|
||||
"alphaExtraction": {"connectivity": 8, "alphaThreshold": ALPHA_THRESHOLD, "minimumComponentArea": 80, "mode": "connected-component-mask"},
|
||||
"coordinateSystem": {"origin": "top-left", "xPositive": "right", "yPositive": "down", "units": "pixels", "jointBasis": "content bounds before export padding"},
|
||||
"sideConvention": {"A": "screen-left / character-right / fan-hand side", "B": "screen-right / character-left / relaxed-hand side"},
|
||||
"warnings": [
|
||||
"A/B ownership is frozen by screen side for the strict-front DOWN direction and must not be mirrored.",
|
||||
"Pivots, layers, and parent links are authoring recommendations until the first neutral assembly is validated.",
|
||||
"The source pelvis contains neutral waist accessories; standalone pouch, front drape, and tassels are replacement layers and may be excluded from the neutral assembly.",
|
||||
"Soft sheet v1 is a rejected crowded layout; extraction uses soft sheet v2 only.",
|
||||
],
|
||||
"partCount": len(manifest_parts),
|
||||
"parts": manifest_parts,
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
columns, cell_width, cell_height = 6, 390, 300
|
||||
rows = (len(exported) + columns - 1) // columns
|
||||
sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), (20, 24, 33))
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
meta_font = ImageFont.truetype(str(FONT_PATH), 13)
|
||||
for index, (spec, record, image) in enumerate(exported):
|
||||
col, row = index % columns, index // columns
|
||||
cell_x, cell_y = col * cell_width, row * cell_height
|
||||
draw.rectangle((cell_x + 8, cell_y + 8, cell_x + cell_width - 9, cell_y + cell_height - 9), outline=(63, 78, 104), width=2)
|
||||
scale = min(1.0, 270 / image.width, 200 / image.height)
|
||||
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
|
||||
draw_x = cell_x + (cell_width - resized.width) // 2
|
||||
draw_y = cell_y + 42 + (200 - resized.height) // 2
|
||||
sheet.paste(resized, (draw_x, draw_y), resized)
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + root["x"] * scale, draw_y + root["y"] * scale, (255, 87, 115))
|
||||
if record["nextJoint"]:
|
||||
nxt = record["nextJoint"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + nxt["x"] * scale, draw_y + nxt["y"] * scale, (69, 211, 255))
|
||||
code = "C" if spec["sheet"] == "core" else "S"
|
||||
draw.text((cell_x + 16, cell_y + 12), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
|
||||
draw.text((cell_x + 16, cell_y + 263), f"{spec['labelZh']} | parent: {spec['parent']}", font=meta_font, fill=(155, 174, 203))
|
||||
sheet.save(PREVIEW)
|
||||
print(f"Exported {len(exported)} parts")
|
||||
print(MANIFEST)
|
||||
print(PREVIEW)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,264 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE_DIR = CHARACTER / "source/front-left"
|
||||
DIAGNOSTIC_DIR = CHARACTER / "diagnostics"
|
||||
OUTPUT_DIR = CHARACTER / "parts/front-left/v1"
|
||||
PREVIEW = CHARACTER / "previews/xinyin-front-left-extracted-parts-v1.png"
|
||||
MANIFEST = OUTPUT_DIR / "parts-manifest.json"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
PADDING = 10
|
||||
ALPHA_THRESHOLD = 16
|
||||
|
||||
|
||||
SHEETS = {
|
||||
"core": {
|
||||
"source": SOURCE_DIR / "xinyin-front-left-core-parts-sheet-v1.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-front-left-core-parts-v1-components.json",
|
||||
},
|
||||
"soft": {
|
||||
"source": SOURCE_DIR / "xinyin-front-left-soft-parts-sheet-v1.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-front-left-soft-parts-v1-components.json",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def part(sheet, component_id, name, label, category, pivot, next_joint, parent, layer, note):
|
||||
return {
|
||||
"sheet": sheet,
|
||||
"componentId": component_id,
|
||||
"name": name,
|
||||
"labelZh": label,
|
||||
"category": category,
|
||||
"pivot": pivot,
|
||||
"next": next_joint,
|
||||
"parent": parent,
|
||||
"layer": layer,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
PARTS = [
|
||||
part("core", 1, "torso-upper", "上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "主躯干;上端连接颈部,左右连接上臂"),
|
||||
part("core", 2, "pelvis-hip-core", "骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根节点候选;双腿和衣摆均挂接于此"),
|
||||
part("core", 3, "head-face", "头部与面部", "body", (.50, .91), None, "neck", 30, "不含前发;枢轴位于颈部连接区"),
|
||||
part("core", 4, "shoulder-armor-b", "肩甲 B", "armor", (.28, .24), None, "torso-upper", 20, "固定在躯干;装配后确认具体画面侧"),
|
||||
part("core", 5, "shoulder-armor-a", "肩甲 A", "armor", (.72, .24), None, "torso-upper", 20, "固定在躯干;装配后确认具体画面侧"),
|
||||
part("core", 6, "neck", "颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接头部"),
|
||||
part("core", 7, "upper-arm-a", "上臂 A", "arm", (.50, .08), (.50, .82), "torso-upper", 14, "放松手侧;肩点到肘点"),
|
||||
part("core", 8, "upper-arm-b", "上臂 B", "arm", (.50, .08), (.50, .82), "torso-upper", 14, "持械手侧;肩点到肘点"),
|
||||
part("core", 9, "hand-fan-grip-b", "持扇手 B", "hand", (.53, .88), None, "forearm-b", 18, "腕点位于下端;与独立羽扇叠加"),
|
||||
part("core", 10, "forearm-a", "前臂 A", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "肘点到腕点"),
|
||||
part("core", 11, "forearm-b", "前臂 B", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "肘点到腕点"),
|
||||
part("core", 12, "hand-relaxed-a", "放松手 A", "hand", (.50, .08), None, "forearm-a", 18, "腕点位于上端"),
|
||||
part("core", 13, "hand-throw-open-b", "投掷张手 B", "hand", (.23, .18), None, "forearm-b", 18, "投掷动作替换手;腕点位于左上袖口"),
|
||||
part("core", 14, "thigh-a", "大腿 A", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "髋点到膝点"),
|
||||
part("core", 15, "shin-boot-a", "小腿与靴 A", "leg", (.50, .05), None, "thigh-a", -7, "膝点位于上端"),
|
||||
part("core", 16, "shin-boot-b", "小腿与靴 B", "leg", (.50, .05), None, "thigh-b", -7, "膝点位于上端"),
|
||||
part("core", 17, "thigh-b", "大腿 B", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "髋点到膝点"),
|
||||
part("soft", 1, "ponytail-root", "马尾根部", "hair", (.62, .15), (.18, .72), "hair-cap", -96, "含贴合头顶的花冠;体积偏大,需装配验证"),
|
||||
part("soft", 2, "ponytail-middle", "马尾中段", "hair", (.15, .14), (.82, .80), "ponytail-root", -95, "上下两端预留重叠;大幅旋转前需验证穿插"),
|
||||
part("soft", 3, "side-lock-a", "长侧发 A", "hair", (.50, .08), None, "hair-cap", 32, "面部侧边软性覆盖层"),
|
||||
part("soft", 4, "hair-front", "前发与侧鬓", "hair", (.50, .12), None, "head-face", 35, "位于面部之前"),
|
||||
part("soft", 5, "side-lock-b", "长侧发 B", "hair", (.50, .08), None, "hair-cap", 31, "面部另一侧软性覆盖层"),
|
||||
part("soft", 6, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-face", 42, "画面左侧独立装饰层"),
|
||||
part("soft", 7, "ponytail-tip", "马尾末端", "hair", (.50, .06), (.50, .92), "ponytail-middle", -94, "末端链节;不再挂接子节"),
|
||||
part("soft", 8, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-face", -90, "位于头部之后;马尾链根节点"),
|
||||
part("soft", 9, "outer-sleeve-cape-a", "外袖披 A", "cloth", (.62, .08), None, "upper-arm-a", 13, "随上臂小幅摆动,不承担手臂骨骼"),
|
||||
part("soft", 10, "outer-sleeve-cape-b", "外袖披 B", "cloth", (.38, .08), None, "upper-arm-b", 13, "随上臂小幅摆动,不承担手臂骨骼"),
|
||||
part("soft", 11, "coat-panel-01", "衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "后层衣摆;具体左右在装配时确认"),
|
||||
part("soft", 12, "coat-panel-02", "衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "后层衣摆;具体左右在装配时确认"),
|
||||
part("soft", 13, "coat-panel-03", "衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中后层衣摆"),
|
||||
part("soft", 14, "coat-panel-04", "衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中后层衣摆"),
|
||||
part("soft", 15, "coat-panel-05", "衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中层衣摆"),
|
||||
part("soft", 16, "coat-panel-06", "衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中层衣摆"),
|
||||
part("soft", 17, "coat-panel-07", "衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "前层衣摆"),
|
||||
part("soft", 18, "coat-panel-08", "衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "前层衣摆"),
|
||||
part("soft", 19, "coat-panel-alt-09", "衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作替换候选;中性装配仅从九片中选八片"),
|
||||
part("soft", 20, "front-drape", "前腰布与基线系绳", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "位于腰封前侧;自带中性流苏"),
|
||||
part("soft", 21, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
||||
part("soft", 22, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"),
|
||||
part("soft", 23, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"),
|
||||
part("soft", 24, "weapon-fan-open", "三羽展开扇", "weapon", (.46, .88), None, "hand-fan-grip-b", 50, "与持扇手分层装配"),
|
||||
part("soft", 25, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"),
|
||||
part("soft", 26, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面左侧腰部"),
|
||||
]
|
||||
|
||||
|
||||
def load_labels(source_path: Path, diagnostic_path: Path):
|
||||
rgba = np.array(Image.open(source_path).convert("RGBA"))
|
||||
alpha = rgba[:, :, 3]
|
||||
# Image.fromarray can expose a read-only buffer; floodfill needs a mutable copy.
|
||||
labels_image = Image.fromarray(np.where(alpha >= ALPHA_THRESHOLD, 255, 0).astype(np.uint8), "L").copy()
|
||||
diagnostic = json.loads(diagnostic_path.read_text(encoding="utf-8-sig"))
|
||||
|
||||
for component in diagnostic["components"]:
|
||||
current = np.array(labels_image)
|
||||
y = component["y"]
|
||||
x0 = component["x"]
|
||||
x1 = x0 + component["width"]
|
||||
candidates = np.flatnonzero(current[y, x0:x1] == 255)
|
||||
if not len(candidates):
|
||||
raise RuntimeError(f"No flood-fill seed for {source_path.name} component {component['id']}")
|
||||
seed = (x0 + int(candidates[0]), y)
|
||||
ImageDraw.floodfill(labels_image, seed, component["id"], thresh=0)
|
||||
|
||||
labels = np.array(labels_image)
|
||||
# Pillow flood fill is four-connected. Attach any diagonal-only fragments to an
|
||||
# already labeled eight-neighbour; tiny unrelated specks remain discarded.
|
||||
for _ in range(8):
|
||||
pending = np.argwhere(labels == 255)
|
||||
if not len(pending):
|
||||
break
|
||||
changed = 0
|
||||
for y, x in pending:
|
||||
y0, y1 = max(0, y - 1), min(labels.shape[0], y + 2)
|
||||
x0, x1 = max(0, x - 1), min(labels.shape[1], x + 2)
|
||||
neighbours = labels[y0:y1, x0:x1]
|
||||
valid = neighbours[(neighbours > 0) & (neighbours < 255)]
|
||||
if len(valid):
|
||||
values, counts = np.unique(valid, return_counts=True)
|
||||
labels[y, x] = values[np.argmax(counts)]
|
||||
changed += 1
|
||||
if not changed:
|
||||
break
|
||||
return rgba, labels, diagnostic
|
||||
|
||||
|
||||
def joint_record(normalized, width, height):
|
||||
if normalized is None:
|
||||
return None
|
||||
return {
|
||||
"contentNormalized": {"x": normalized[0], "y": normalized[1]},
|
||||
"outputPixels": {
|
||||
"x": round(PADDING + width * normalized[0], 2),
|
||||
"y": round(PADDING + height * normalized[1], 2),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def draw_cross(draw: ImageDraw.ImageDraw, x: float, y: float, color, radius=7, width=3):
|
||||
draw.line((x - radius, y, x + radius, y), fill=color, width=width)
|
||||
draw.line((x, y - radius, x, y + radius), fill=color, width=width)
|
||||
|
||||
|
||||
def main():
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
|
||||
loaded = {key: load_labels(value["source"], value["diagnostic"]) for key, value in SHEETS.items()}
|
||||
expected = {"core": 17, "soft": 26}
|
||||
for key, (_, labels, diagnostic) in loaded.items():
|
||||
if len(diagnostic["components"]) != expected[key]:
|
||||
raise RuntimeError(f"Expected {expected[key]} components for {key}")
|
||||
if any(not np.any(labels == component_id) for component_id in range(1, expected[key] + 1)):
|
||||
raise RuntimeError(f"Missing labeled component in {key}")
|
||||
|
||||
manifest_parts = []
|
||||
exported = []
|
||||
for spec in PARTS:
|
||||
rgba, labels, diagnostic = loaded[spec["sheet"]]
|
||||
component = diagnostic["components"][spec["componentId"] - 1]
|
||||
x, y, width, height = (component[k] for k in ("x", "y", "width", "height"))
|
||||
source_crop = rgba[y : y + height, x : x + width].copy()
|
||||
component_mask = labels[y : y + height, x : x + width] == spec["componentId"]
|
||||
source_crop[~component_mask] = 0
|
||||
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
|
||||
output[PADDING : PADDING + height, PADDING : PADDING + width] = source_crop
|
||||
image = Image.fromarray(output, "RGBA")
|
||||
prefix = "fl-core" if spec["sheet"] == "core" else "fl-soft"
|
||||
filename = f"{prefix}-c{spec['componentId']:02d}-{spec['name']}.png"
|
||||
image.save(OUTPUT_DIR / filename)
|
||||
|
||||
record = {
|
||||
"sourceSheet": spec["sheet"],
|
||||
"componentId": spec["componentId"],
|
||||
"name": spec["name"],
|
||||
"labelZh": spec["labelZh"],
|
||||
"category": spec["category"],
|
||||
"file": filename,
|
||||
"parent": spec["parent"],
|
||||
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
|
||||
"outputSize": {"width": image.width, "height": image.height},
|
||||
"rootPivot": joint_record(spec["pivot"], width, height),
|
||||
"nextJoint": joint_record(spec["next"], width, height),
|
||||
"suggestedLayer": spec["layer"],
|
||||
"notes": spec["note"],
|
||||
}
|
||||
manifest_parts.append(record)
|
||||
exported.append((spec, record, image))
|
||||
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"characterNameZh": "汐月心音",
|
||||
"direction": "front-left",
|
||||
"version": 1,
|
||||
"status": "extracted-unvalidated",
|
||||
"sources": {
|
||||
"core": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-core-parts-sheet-v1.png",
|
||||
"soft": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-soft-parts-sheet-v1.png",
|
||||
},
|
||||
"padding": PADDING,
|
||||
"alphaExtraction": {
|
||||
"connectivity": 8,
|
||||
"alphaThreshold": ALPHA_THRESHOLD,
|
||||
"minimumComponentArea": 80,
|
||||
"mode": "connected-component-mask",
|
||||
},
|
||||
"coordinateSystem": {
|
||||
"origin": "top-left",
|
||||
"xPositive": "right",
|
||||
"yPositive": "down",
|
||||
"units": "pixels",
|
||||
"jointBasis": "content bounds before export padding",
|
||||
},
|
||||
"warnings": [
|
||||
"A/B limb and cloth ownership follows source-sheet grouping and must be frozen after the first front-left assembly.",
|
||||
"Ponytail root and middle are oversized source segments; validate overlap and rotation before animation use.",
|
||||
"Suggested hierarchy, layers, root pivots, and next joints are authoring recommendations and have not been engine-tested.",
|
||||
"Do not mirror asymmetric art automatically; weapon, pouch, hair ornament, and ponytail screen sides are fixed.",
|
||||
],
|
||||
"partCount": len(manifest_parts),
|
||||
"parts": manifest_parts,
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
columns, cell_width, cell_height = 5, 460, 320
|
||||
rows = (len(exported) + columns - 1) // columns
|
||||
sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), (20, 24, 33))
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 20)
|
||||
meta_font = ImageFont.truetype(str(FONT_PATH), 14)
|
||||
for index, (spec, record, image) in enumerate(exported):
|
||||
col, row = index % columns, index // columns
|
||||
cell_x, cell_y = col * cell_width, row * cell_height
|
||||
draw.rectangle((cell_x + 8, cell_y + 8, cell_x + cell_width - 9, cell_y + cell_height - 9), outline=(63, 78, 104), width=2)
|
||||
max_width, max_height = 320, 220
|
||||
scale = min(1.0, max_width / image.width, max_height / image.height)
|
||||
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
|
||||
draw_x = cell_x + (cell_width - resized.width) // 2
|
||||
draw_y = cell_y + 48 + (max_height - resized.height) // 2
|
||||
sheet.paste(resized, (draw_x, draw_y), resized)
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + root["x"] * scale, draw_y + root["y"] * scale, (255, 87, 115))
|
||||
if record["nextJoint"]:
|
||||
nxt = record["nextJoint"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + nxt["x"] * scale, draw_y + nxt["y"] * scale, (69, 211, 255))
|
||||
code = "C" if spec["sheet"] == "core" else "S"
|
||||
draw.text((cell_x + 18, cell_y + 14), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
|
||||
draw.text((cell_x + 18, cell_y + 282), f"{spec['labelZh']} | parent: {spec['parent']}", font=meta_font, fill=(155, 174, 203))
|
||||
sheet.save(PREVIEW)
|
||||
print(f"Exported {len(exported)} parts")
|
||||
print(MANIFEST)
|
||||
print(PREVIEW)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,127 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from extract_xinyin_front_left_parts import load_labels
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE = CHARACTER / "source/rig-corrections/xinyin-front-left-rig-corrections-v2.png"
|
||||
DIAGNOSTIC = CHARACTER / "diagnostics/xinyin-front-left-rig-corrections-v2-components.json"
|
||||
OUTPUT_DIR = CHARACTER / "parts/front-left/rig-corrections-v1"
|
||||
MANIFEST = OUTPUT_DIR / "rig-corrections-manifest.json"
|
||||
PREVIEW = CHARACTER / "previews/xinyin-front-left-rig-corrections-v1.png"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
PADDING = 12
|
||||
|
||||
|
||||
PARTS = [
|
||||
{"id": 1, "name": "ponytail-root", "label": "马尾根部", "category": "hair", "pivot": (.86, .38), "next": (.62, .91), "parent": "hair-cap", "note": "含小型银花绑点;根部到第一连接点"},
|
||||
{"id": 2, "name": "upper-arm-a", "label": "独立上臂 A", "category": "arm", "pivot": (.50, .06), "next": (.50, .92), "parent": "torso-upper", "note": "放松手侧;不含肩甲、外袖披、前臂与手"},
|
||||
{"id": 3, "name": "upper-arm-b", "label": "独立上臂 B", "category": "arm", "pivot": (.50, .06), "next": (.50, .92), "parent": "torso-upper", "note": "持械手侧;不含肩甲、外袖披、前臂与手"},
|
||||
{"id": 4, "name": "ponytail-middle", "label": "马尾中段", "category": "hair", "pivot": (.42, .05), "next": (.88, .91), "parent": "ponytail-root", "note": "上下开放连接;不含花饰与末端"},
|
||||
{"id": 5, "name": "ponytail-tip", "label": "马尾末端", "category": "hair", "pivot": (.24, .07), "next": (.80, .92), "parent": "ponytail-middle", "note": "上端开放连接;下端自然收尖"},
|
||||
]
|
||||
|
||||
|
||||
def joint(normalized, width, height):
|
||||
return {
|
||||
"contentNormalized": {"x": normalized[0], "y": normalized[1]},
|
||||
"outputPixels": {
|
||||
"x": round(PADDING + width * normalized[0], 2),
|
||||
"y": round(PADDING + height * normalized[1], 2),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def cross(draw, x, y, color):
|
||||
draw.line((x - 8, y, x + 8, y), fill=color, width=3)
|
||||
draw.line((x, y - 8, x, y + 8), fill=color, width=3)
|
||||
|
||||
|
||||
def main():
|
||||
rgba, labels, diagnostic = load_labels(SOURCE, DIAGNOSTIC)
|
||||
if len(diagnostic["components"]) != 5:
|
||||
raise RuntimeError(f"Expected 5 components, detected {len(diagnostic['components'])}")
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
records = []
|
||||
images = []
|
||||
for spec in PARTS:
|
||||
component = diagnostic["components"][spec["id"] - 1]
|
||||
x, y, width, height = (component[k] for k in ("x", "y", "width", "height"))
|
||||
crop = rgba[y : y + height, x : x + width].copy()
|
||||
mask = labels[y : y + height, x : x + width] == spec["id"]
|
||||
crop[~mask] = 0
|
||||
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
|
||||
output[PADDING : PADDING + height, PADDING : PADDING + width] = crop
|
||||
image = Image.fromarray(output, "RGBA")
|
||||
filename = f"fl-rig-c{spec['id']:02d}-{spec['name']}.png"
|
||||
image.save(OUTPUT_DIR / filename)
|
||||
record = {
|
||||
"componentId": spec["id"],
|
||||
"name": spec["name"],
|
||||
"labelZh": spec["label"],
|
||||
"category": spec["category"],
|
||||
"file": filename,
|
||||
"parent": spec["parent"],
|
||||
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
|
||||
"outputSize": {"width": image.width, "height": image.height},
|
||||
"rootPivot": joint(spec["pivot"], width, height),
|
||||
"nextJoint": joint(spec["next"], width, height),
|
||||
"notes": spec["note"],
|
||||
}
|
||||
records.append(record)
|
||||
images.append(image)
|
||||
|
||||
payload = {
|
||||
"characterId": "02-xinyin",
|
||||
"direction": "front-left",
|
||||
"version": 1,
|
||||
"status": "correction-parts-art-validated",
|
||||
"source": "assets/images/2d-game-characters/02-xinyin/source/rig-corrections/xinyin-front-left-rig-corrections-v2.png",
|
||||
"padding": PADDING,
|
||||
"coordinateSystem": {"origin": "top-left", "xPositive": "right", "yPositive": "down", "units": "pixels"},
|
||||
"warnings": [
|
||||
"Root pivots and next joints passed the neutral assembly v4 art check; motion interpolation remains untested.",
|
||||
"The ponytail root outgoing end is narrower than the middle incoming cut; use overlap and validate the seam at motion extremes.",
|
||||
"Standalone shoulder armor and sleeve-cape pieces remain in the base front-left parts package.",
|
||||
],
|
||||
"partCount": len(records),
|
||||
"parts": records,
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
cell_width, cell_height = 500, 420
|
||||
board = Image.new("RGB", (cell_width * 3, cell_height * 2), (19, 23, 32))
|
||||
draw = ImageDraw.Draw(board)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 22)
|
||||
meta_font = ImageFont.truetype(str(FONT_PATH), 16)
|
||||
for index, (spec, record, image) in enumerate(zip(PARTS, records, images)):
|
||||
col, row = index % 3, index // 3
|
||||
x, y = col * cell_width, row * cell_height
|
||||
draw.rectangle((x + 8, y + 8, x + cell_width - 9, y + cell_height - 9), outline=(64, 82, 110), width=2)
|
||||
scale = min(1.0, 350 / image.width, 300 / image.height)
|
||||
resized = image.resize((round(image.width * scale), round(image.height * scale)), Image.Resampling.LANCZOS)
|
||||
px = x + (cell_width - resized.width) // 2
|
||||
py = y + 48 + (300 - resized.height) // 2
|
||||
board.paste(resized, (px, py), resized)
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
nxt = record["nextJoint"]["outputPixels"]
|
||||
cross(draw, px + root["x"] * scale, py + root["y"] * scale, (255, 87, 115))
|
||||
cross(draw, px + nxt["x"] * scale, py + nxt["y"] * scale, (69, 211, 255))
|
||||
draw.text((x + 18, y + 16), f"C{spec['id']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
|
||||
draw.text((x + 18, y + 375), f"{spec['label']} | parent: {spec['parent']}", font=meta_font, fill=(154, 173, 202))
|
||||
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
|
||||
board.save(PREVIEW)
|
||||
print(f"Exported {len(records)} correction parts")
|
||||
print(MANIFEST)
|
||||
print(PREVIEW)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,186 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from extract_xinyin_down_parts import draw_cross, joint_record, load_labels, part
|
||||
|
||||
|
||||
ROOT = Path(r"C:\milimoe\osm-game")
|
||||
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
|
||||
SOURCE_DIR = CHARACTER / "source/up"
|
||||
DIAGNOSTIC_DIR = CHARACTER / "diagnostics"
|
||||
OUTPUT_DIR = CHARACTER / "parts/up/v1"
|
||||
PREVIEW = CHARACTER / "previews/xinyin-up-extracted-parts-v1.png"
|
||||
MANIFEST = OUTPUT_DIR / "parts-manifest.json"
|
||||
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
|
||||
PADDING = 10
|
||||
ALPHA_THRESHOLD = 16
|
||||
|
||||
|
||||
SHEETS = {
|
||||
"core": {
|
||||
"source": SOURCE_DIR / "xinyin-up-core-parts-sheet-v2.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-up-core-parts-v2-components.json",
|
||||
"expected": 17,
|
||||
},
|
||||
"soft": {
|
||||
"source": SOURCE_DIR / "xinyin-up-soft-parts-sheet-v2.png",
|
||||
"diagnostic": DIAGNOSTIC_DIR / "xinyin-up-soft-parts-v2-components.json",
|
||||
"expected": 24,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# UP owns a direction-specific convention: A is screen-right, B is screen-left.
|
||||
# Do not mirror or copy the strict-front DOWN ownership table.
|
||||
PARTS = [
|
||||
part("core", 1, "torso-upper", "背面上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "严格背面主躯干;不含手臂、肩甲与袖披"),
|
||||
part("core", 4, "pelvis-hip-core", "背面骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根候选;双腿和背面衣摆挂接于此"),
|
||||
part("core", 5, "head-back", "背面头部基底", "body", (.50, .91), None, "neck", 30, "无面部的严格背面头部;后脑发片覆盖其上"),
|
||||
part("core", 2, "shoulder-armor-a", "肩甲 A/画面右", "armor", (.28, .24), None, "torso-upper", 20, "持扇手侧;固定于躯干"),
|
||||
part("core", 3, "shoulder-armor-b", "肩甲 B/画面左", "armor", (.72, .24), None, "torso-upper", 20, "放松手与腰包侧;固定于躯干"),
|
||||
part("core", 6, "neck", "背面颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接背面头部"),
|
||||
part("core", 10, "upper-arm-a", "上臂 A/画面右", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "持扇手侧;不含肩甲与袖披"),
|
||||
part("core", 11, "upper-arm-b", "上臂 B/画面左", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "放松手侧;不含肩甲与袖披"),
|
||||
part("core", 9, "forearm-a", "前臂 A/画面右", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "持扇手侧肘到腕"),
|
||||
part("core", 8, "forearm-b", "前臂 B/画面左", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "放松手侧肘到腕"),
|
||||
part("core", 7, "hand-fan-grip-a", "持扇手 A", "hand", (.50, .88), None, "forearm-a", 18, "画面右侧;含三羽持握形态"),
|
||||
part("core", 12, "hand-relaxed-b", "放松手 B", "hand", (.50, .08), None, "forearm-b", 18, "画面左侧;腕点位于上端"),
|
||||
part("core", 17, "hand-throw-open-a", "投掷张手 A", "hand", (.82, .18), None, "forearm-a", 18, "持扇手侧动作替换件;腕点在部件右上"),
|
||||
part("core", 15, "thigh-a", "大腿 A/画面右", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面右髋点到膝点"),
|
||||
part("core", 16, "thigh-b", "大腿 B/画面左", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面左髋点到膝点"),
|
||||
part("core", 13, "shin-boot-a", "小腿与靴 A/画面右", "leg", (.50, .05), None, "thigh-a", -7, "画面右;膝点位于上端"),
|
||||
part("core", 14, "shin-boot-b", "小腿与靴 B/画面左", "leg", (.50, .05), None, "thigh-b", -7, "画面左;膝点位于上端"),
|
||||
part("soft", 4, "hair-nape-overlay", "后颈发丝覆盖层", "hair", (.50, .12), None, "head-back", 35, "覆盖后脑与后颈的近景发丝层"),
|
||||
part("soft", 5, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-back", -90, "位于头部之后;马尾根父节点"),
|
||||
part("soft", 2, "ponytail-root", "马尾根部", "hair", (.48, .10), (.46, .88), "hair-cap", -96, "严格背面马尾根;根部到第一连接点"),
|
||||
part("soft", 1, "ponytail-middle", "马尾中段", "hair", (.50, .08), (.50, .90), "ponytail-root", -95, "上下端预留重叠"),
|
||||
part("soft", 6, "ponytail-tip", "马尾末端", "hair", (.50, .08), None, "ponytail-middle", -94, "末端链节"),
|
||||
part("soft", 3, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-back", 42, "背面独立装饰层"),
|
||||
part("soft", 12, "outer-sleeve-cape-a", "外袖披 A/画面右", "cloth", (.50, .08), None, "upper-arm-a", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
||||
part("soft", 11, "outer-sleeve-cape-b", "外袖披 B/画面左", "cloth", (.50, .08), None, "upper-arm-b", 13, "不含肩甲和手臂;随上臂小幅摆动"),
|
||||
part("soft", 9, "coat-panel-01", "背面衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "中性八片之一"),
|
||||
part("soft", 10, "coat-panel-02", "背面衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "中性八片之一"),
|
||||
part("soft", 8, "coat-panel-03", "背面衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中性八片之一"),
|
||||
part("soft", 7, "coat-panel-04", "背面衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中性八片之一"),
|
||||
part("soft", 16, "coat-panel-05", "背面衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中性八片之一"),
|
||||
part("soft", 15, "coat-panel-06", "背面衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中性八片之一"),
|
||||
part("soft", 14, "coat-panel-07", "背面衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "中性八片之一"),
|
||||
part("soft", 17, "coat-panel-08", "背面衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "中性八片之一"),
|
||||
part("soft", 18, "coat-panel-alt-09", "背面衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作轮廓替换件"),
|
||||
part("soft", 13, "rear-drape", "中央腰后布", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "不含独立替换流苏"),
|
||||
part("soft", 24, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面左侧腰部"),
|
||||
part("soft", 19, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "rear-drape", 8, "动作替换件"),
|
||||
part("soft", 20, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "rear-drape", 8, "动作替换件"),
|
||||
part("soft", 21, "weapon-fan-open", "三羽展开扇", "weapon", (.50, .88), None, "hand-fan-grip-a", 50, "无手;与持扇手分层装配"),
|
||||
part("soft", 23, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"),
|
||||
part("soft", 22, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
|
||||
loaded = {key: load_labels(value["source"], value["diagnostic"]) for key, value in SHEETS.items()}
|
||||
for key, (_, labels, diagnostic) in loaded.items():
|
||||
expected = SHEETS[key]["expected"]
|
||||
ids = {component["id"] for component in diagnostic["components"]}
|
||||
if len(diagnostic["components"]) != expected or ids != set(range(1, expected + 1)):
|
||||
raise RuntimeError(f"Expected component IDs 1..{expected} for {key}")
|
||||
if any(not np.any(labels == component_id) for component_id in ids):
|
||||
raise RuntimeError(f"Missing labeled component in {key}")
|
||||
|
||||
manifest_parts = []
|
||||
exported = []
|
||||
for spec in PARTS:
|
||||
rgba, labels, diagnostic = loaded[spec["sheet"]]
|
||||
component = next(item for item in diagnostic["components"] if item["id"] == spec["componentId"])
|
||||
x, y, width, height = (component[key] for key in ("x", "y", "width", "height"))
|
||||
crop = rgba[y : y + height, x : x + width].copy()
|
||||
mask = labels[y : y + height, x : x + width] == spec["componentId"]
|
||||
crop[~mask] = 0
|
||||
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
|
||||
output[PADDING : PADDING + height, PADDING : PADDING + width] = crop
|
||||
image = Image.fromarray(output, "RGBA")
|
||||
prefix = "up-core" if spec["sheet"] == "core" else "up-soft"
|
||||
filename = f"{prefix}-c{spec['componentId']:02d}-{spec['name']}.png"
|
||||
image.save(OUTPUT_DIR / filename)
|
||||
record = {
|
||||
"sourceSheet": spec["sheet"],
|
||||
"componentId": spec["componentId"],
|
||||
"name": spec["name"],
|
||||
"labelZh": spec["labelZh"],
|
||||
"category": spec["category"],
|
||||
"file": filename,
|
||||
"parent": spec["parent"],
|
||||
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
|
||||
"outputSize": {"width": image.width, "height": image.height},
|
||||
"rootPivot": joint_record(spec["pivot"], width, height),
|
||||
"nextJoint": joint_record(spec["next"], width, height),
|
||||
"suggestedLayer": spec["layer"],
|
||||
"notes": spec["note"],
|
||||
}
|
||||
manifest_parts.append(record)
|
||||
exported.append((spec, record, image))
|
||||
|
||||
manifest = {
|
||||
"characterId": "02-xinyin",
|
||||
"characterNameZh": "汐月心音",
|
||||
"direction": "up",
|
||||
"version": 1,
|
||||
"status": "extracted-unvalidated",
|
||||
"sources": {
|
||||
"core": "assets/images/2d-game-characters/02-xinyin/source/up/xinyin-up-core-parts-sheet-v2.png",
|
||||
"soft": "assets/images/2d-game-characters/02-xinyin/source/up/xinyin-up-soft-parts-sheet-v2.png",
|
||||
},
|
||||
"padding": PADDING,
|
||||
"alphaExtraction": {"connectivity": 8, "alphaThreshold": ALPHA_THRESHOLD, "minimumComponentArea": 80, "mode": "connected-component-mask"},
|
||||
"coordinateSystem": {"origin": "top-left", "xPositive": "right", "yPositive": "down", "units": "pixels", "jointBasis": "content bounds before export padding"},
|
||||
"sideConvention": {"A": "screen-right / character-right / fan-hand side", "B": "screen-left / character-left / relaxed-hand and pouch side"},
|
||||
"warnings": [
|
||||
"A/B ownership is frozen for the strict-back UP direction and must not reuse the DOWN screen-side mapping.",
|
||||
"Pivots, layers, and parent links are authoring recommendations until the first neutral assembly is validated.",
|
||||
"The source pelvis contains neutral waist cords, pouch, rear cloth, and tassels; standalone pouch, rear drape, and tassels are replacement layers and may be excluded from the neutral assembly.",
|
||||
"Core and soft sheet v1 are rejected source layouts; extraction uses v2 only.",
|
||||
"Sleeve capes do not include shoulder armor, and coat panels do not include tassels or chains.",
|
||||
],
|
||||
"partCount": len(manifest_parts),
|
||||
"parts": manifest_parts,
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
columns, cell_width, cell_height = 6, 390, 300
|
||||
rows = (len(exported) + columns - 1) // columns
|
||||
sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), (20, 24, 33))
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
title_font = ImageFont.truetype(str(FONT_PATH), 18)
|
||||
meta_font = ImageFont.truetype(str(FONT_PATH), 13)
|
||||
for index, (spec, record, image) in enumerate(exported):
|
||||
col, row = index % columns, index // columns
|
||||
cell_x, cell_y = col * cell_width, row * cell_height
|
||||
draw.rectangle((cell_x + 8, cell_y + 8, cell_x + cell_width - 9, cell_y + cell_height - 9), outline=(63, 78, 104), width=2)
|
||||
scale = min(1.0, 270 / image.width, 200 / image.height)
|
||||
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
|
||||
draw_x = cell_x + (cell_width - resized.width) // 2
|
||||
draw_y = cell_y + 42 + (200 - resized.height) // 2
|
||||
sheet.paste(resized, (draw_x, draw_y), resized)
|
||||
root = record["rootPivot"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + root["x"] * scale, draw_y + root["y"] * scale, (255, 87, 115))
|
||||
if record["nextJoint"]:
|
||||
nxt = record["nextJoint"]["outputPixels"]
|
||||
draw_cross(draw, draw_x + nxt["x"] * scale, draw_y + nxt["y"] * scale, (69, 211, 255))
|
||||
code = "C" if spec["sheet"] == "core" else "S"
|
||||
draw.text((cell_x + 16, cell_y + 12), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
|
||||
draw.text((cell_x + 16, cell_y + 263), f"{spec['labelZh']} | parent: {spec['parent']}", font=meta_font, fill=(155, 174, 203))
|
||||
sheet.save(PREVIEW)
|
||||
print(f"Exported {len(exported)} parts")
|
||||
print(MANIFEST)
|
||||
print(PREVIEW)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
TEMPLATE_DIR = ROOT / "templates/2d-character-v1"
|
||||
OUTPUT_ROOT = ROOT / "assets/images/2d-game-characters"
|
||||
ID_PATTERN = re.compile(r"^\d{2,3}-[a-z0-9][a-z0-9-]*$")
|
||||
|
||||
DIRECTORIES = (
|
||||
"source/up",
|
||||
"source/down",
|
||||
"source/left",
|
||||
"source/right",
|
||||
"parts/up/v1",
|
||||
"parts/down/v1",
|
||||
"parts/left/v1",
|
||||
"parts/right/v1",
|
||||
"assembled/up",
|
||||
"assembled/down",
|
||||
"assembled/left",
|
||||
"assembled/right",
|
||||
"motion/up/v1",
|
||||
"motion/down/v1",
|
||||
"motion/left/v1",
|
||||
"motion/right/v1",
|
||||
"previews/playback",
|
||||
"diagnostics",
|
||||
)
|
||||
|
||||
FILES = {
|
||||
"character-config.template.json": "character-config-v1.json",
|
||||
"direction-map.template.json": "direction-map-v1.json",
|
||||
"template-package.template.json": "template-package-v1.json",
|
||||
"character-readme.template.md": "README.md",
|
||||
}
|
||||
|
||||
|
||||
def replace_tokens(text: str, character_id: str, name_zh: str, name_en: str) -> str:
|
||||
return (
|
||||
text.replace("__CHARACTER_ID__", character_id)
|
||||
.replace("__CHARACTER_NAME_ZH__", name_zh)
|
||||
.replace("__CHARACTER_NAME_EN__", name_en)
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Create a safe OSM four-direction 2D character scaffold.")
|
||||
parser.add_argument("character_id", help="Lowercase id such as 03-example")
|
||||
parser.add_argument("--name-zh", required=True, help="Chinese display name")
|
||||
parser.add_argument("--name-en", default="", help="Optional English display name")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Print planned paths without writing")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not ID_PATTERN.fullmatch(args.character_id):
|
||||
raise SystemExit("character_id must match NN-lowercase-slug, for example 03-example")
|
||||
target = OUTPUT_ROOT / args.character_id
|
||||
if target.exists():
|
||||
raise SystemExit(f"Refusing to overwrite existing character directory: {target}")
|
||||
|
||||
planned = [target / directory for directory in DIRECTORIES]
|
||||
planned.extend(target / output for output in FILES.values())
|
||||
if args.dry_run:
|
||||
print(f"Dry run: {target}")
|
||||
for path in planned:
|
||||
print(path.relative_to(ROOT).as_posix())
|
||||
return
|
||||
|
||||
for directory in DIRECTORIES:
|
||||
(target / directory).mkdir(parents=True, exist_ok=False)
|
||||
for template_name, output_name in FILES.items():
|
||||
source = TEMPLATE_DIR / template_name
|
||||
content = replace_tokens(source.read_text(encoding="utf-8"), args.character_id, args.name_zh, args.name_en)
|
||||
destination = target / output_name
|
||||
destination.write_text(content, encoding="utf-8")
|
||||
if destination.suffix == ".json":
|
||||
json.loads(content)
|
||||
|
||||
print(f"Created character scaffold: {target}")
|
||||
print(f"Start with: {target / 'character-config-v1.json'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user