export-assets.mjs 15 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Deterministic asset slicing, SVG rasterization and editable effect export.
  2. No repainting or background removal: source artwork remains unchanged. */
  3. import fs from 'node:fs';import path from 'node:path';import vm from 'node:vm';
  4. import {createRequire} from 'node:module';import {fileURLToPath} from 'node:url';
  5. const require=createRequire(import.meta.url),root=path.dirname(fileURLToPath(import.meta.url));
  6. let sharp;try{sharp=require('sharp');}catch{sharp=require(process.env.BUFFALO_SHARP_PATH||'C:/Users/EDY/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/sharp');}
  7. const at=p=>path.join(root,p);const write=(p,v)=>fs.writeFileSync(at(p),typeof v==='string'?v:JSON.stringify(v,null,2));
  8. for(const dir of ['assets/sprites','assets/ui/png','assets/fx','assets/maps'])fs.mkdirSync(at(dir),{recursive:true});
  9. const records=[];
  10. const atlases=[
  11. ['tower-item-atlas',5,2,['tower.archer','tower.pistol','tower.crossbow','tower.rifle','tower.mortar','item.airstrike','item.frost','item.repair','item.gold','brand.buffalo']],
  12. ['enemy-atlas',3,2,['enemy.rabbit','enemy.bison','enemy.wolf','enemy.vulture','enemy.scorpion','enemy.king']],
  13. ['avatar-atlas',4,2,['avatar.bison','avatar.wolf','avatar.eagle','avatar.scorpion','avatar.rabbit','avatar.bear','avatar.horse','avatar.snake']],
  14. ['props-atlas',4,4,['prop.base','prop.portal','prop.build-pad','prop.watchtower','prop.cactus','prop.prickly-pear','prop.grass','prop.shrub','prop.red-rock','prop.tan-rock','prop.skull','prop.ribs','prop.wagon','prop.fence','prop.barrels','prop.windmill']],
  15. ['terrain-atlas',2,2,['terrain.serpentine','terrain.longhorn','terrain.switchback','terrain.chokepoint']]
  16. ];
  17. for(const [name,cols,rows,ids]of atlases){
  18. const src='assets/art/'+name+'.png',meta=await sharp(at(src)).metadata();
  19. for(let i=0;i<ids.length;i++){
  20. const x=Math.round(i%cols*meta.width/cols),y=Math.round(Math.floor(i/cols)*meta.height/rows);
  21. const w=Math.round((i%cols+1)*meta.width/cols)-x,h=Math.round((Math.floor(i/cols)+1)*meta.height/rows)-y;
  22. const file='assets/sprites/'+ids[i]+'.png';await sharp(at(src)).extract({left:x,top:y,width:w,height:h}).png().toFile(at(file));
  23. const {data,info}=await sharp(at(file)).ensureAlpha().raw().toBuffer({resolveWithObject:true});let minX=w,minY=h,maxX=-1,maxY=-1;
  24. for(let py=0;py<h;py++)for(let px=0;px<w;px++)if(data[(py*w+px)*info.channels+3]>8){minX=Math.min(minX,px);maxX=Math.max(maxX,px);minY=Math.min(minY,py);maxY=Math.max(maxY,py);}
  25. records.push({id:ids[i],file,width:w,height:h,transparent:meta.hasAlpha,atlas:src,grid:[cols,rows],cellIndex:i,sourceRect:{x,y,width:w,height:h},uv:[x/meta.width,y/meta.height,w/meta.width,h/meta.height],transparentPadding:[minY,w-1-maxX,h-1-maxY,minX],pivot:[.5,.5],nineSlice:[0,0,0,0]});
  26. }
  27. }
  28. const ui=JSON.parse(fs.readFileSync(at('assets/ui/ui-assets.json'),'utf8'));
  29. const extraUI=[
  30. ['trash',64,64,0,'<path d="M14 20H50M25 20V12H39V20M19 20L22 53H42L45 20M28 28V44M36 28V44" fill="none" stroke="#e9c688" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>'],
  31. ['document',64,64,0,'<path d="M16 8H37L49 20V56H16ZM37 8V20H49M24 32H41M24 42H41" fill="#46303b" stroke="#e9c688" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>'],
  32. ['progress-track',128,24,8,'<rect x="1" y="1" width="126" height="22" rx="6" fill="#261b24" stroke="#a77b3f" stroke-width="2"/><rect x="5" y="5" width="118" height="14" rx="3" fill="#171219" stroke="#664d36"/>'],
  33. ['progress-fill',128,16,5,'<defs><linearGradient id="g" x2="0" y2="1"><stop stop-color="#ffe0a0"/><stop offset="1" stop-color="#c29143"/></linearGradient></defs><rect x="1" y="1" width="126" height="14" rx="4" fill="url(#g)"/>'],
  34. ['tab-normal',128,64,12,'<path d="M10 1H118L127 10V63H1V10Z" fill="#352535" stroke="#94703e" stroke-width="2"/><path d="M9 55H119" stroke="#ae8243"/>'],
  35. ['tab-selected',128,64,12,'<path d="M10 1H118L127 10V63H1V10Z" fill="#765336" stroke="#ecc983" stroke-width="2"/><path d="M8 56H120" stroke="#f3cf85" stroke-width="4"/>'],
  36. ['switch-off',84,44,0,'<rect x="2" y="5" width="80" height="34" rx="17" fill="#271d26" stroke="#906b3c" stroke-width="2"/><circle cx="22" cy="22" r="17" fill="#b59a77" stroke="#f1d8a8" stroke-width="2"/>'],
  37. ['switch-on',84,44,0,'<rect x="2" y="5" width="80" height="34" rx="17" fill="#a47e3f" stroke="#e9c784" stroke-width="2"/><circle cx="62" cy="22" r="17" fill="#f0d7a2" stroke="#fff0c5" stroke-width="2"/>'],
  38. ['badge',48,48,0,'<path d="M24 2L43 10V27Q40 40 24 46Q8 40 5 27V10Z" fill="#644336" stroke="#d5ab63" stroke-width="3"/><path d="M24 10L28 19L38 20L30 27L32 37L24 32L16 37L18 27L10 20L20 19Z" fill="#edc780"/>']
  39. ];
  40. for(const [name,w,h,slice,body]of extraUI){const file=name+'.svg';write('assets/ui/'+file,`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>`);ui.assets.push({id:'ui.'+name,file,width:w,height:h,transparent:true,pivot:[.5,.5],kind:'component',borderSlices:[slice,slice,slice,slice]});}
  41. for(const a of ui.assets){const file='assets/ui/png/'+a.file.replace('.svg','.png');await sharp(at('assets/ui/'+a.file)).png().toFile(at(file));records.push({...a,source:'assets/ui/'+a.file,file,nineSlice:a.borderSlices});}
  42. // Reuse the exact gameplay geometry and deterministic decoration placement for all four maps.
  43. const app=fs.readFileSync(at('app.js'),'utf8');
  44. const maps=vm.runInNewContext(app.match(/const MAP_DEFS = (\[[\s\S]*?\n\]);/)[1]);
  45. function rng(seed){let s=seed>>>0;return()=>{s=(s*1664525+1013904223)>>>0;return s/4294967296;};}
  46. function segment(px,py,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;const t=Math.max(0,Math.min(1,((px-a[0])*dx+(py-a[1])*dy)/l));return Math.hypot(px-a[0]-dx*t,py-a[1]-dy*t);}
  47. function dataImage(file){return 'data:image/png;base64,'+fs.readFileSync(at(file)).toString('base64');}
  48. for(let i=0;i<maps.length;i++){
  49. const m=maps[i],distance=(x,y)=>Math.min(...m.path.slice(1).map((p,j)=>segment(x,y,m.path[j],p))),slots=[];
  50. m.rows.forEach(y=>m.cols.forEach(x=>{if(x>=24&&x<=406&&y>=18&&y<=580&&distance(x,y)>=m.minD&&Math.hypot(x-m.base.x,y-m.base.y)>=80)slots.push({x,y});}));m.slots=slots;m.coordinateSize=[430,600];
  51. const d=m.path.map((p,j)=>(j?'L':'M')+p.join(' ')).join(' '),r=rng(1024+i*87);
  52. let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="750" height="1047" viewBox="0 0 430 600"><image href="${dataImage('assets/sprites/terrain.'+m.key+'.png')}" width="430" height="600" preserveAspectRatio="none"/><rect width="430" height="600" fill="#edc483" opacity=".13"/>`;
  53. for(const [w,c]of [[53,'#714b2a55'],[48,'#a47440'],[41,'#c99859'],[33,'#dcb275']])svg+=`<path d="${d}" fill="none" stroke="${c}" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
  54. svg+=`<path d="${d}" fill="none" stroke="#aa794b77" stroke-width="1.2" stroke-dasharray="3 11" stroke-linejoin="round"/>`;
  55. for(let j=0;j<38;j++){const x=12+r()*406,y=15+r()*565;if(distance(x,y)<41||slots.some(s=>Math.hypot(s.x-x,s.y-y)<38)||Math.hypot(m.base.x-x,m.base.y-y)<68)continue;const idx=4+Math.floor(r()*12),size=idx===15?50:25+r()*24;svg+=`<image href="${dataImage('assets/sprites/'+atlases[3][3][idx]+'.png')}" x="${x-size/2}" y="${y-size*.78}" width="${size}" height="${size}" preserveAspectRatio="none"/>`;}
  56. svg+='<defs><linearGradient id="edge"><stop stop-color="#56351c" stop-opacity=".21"/><stop offset=".12" stop-color="#56351c" stop-opacity="0"/><stop offset=".88" stop-color="#56351c" stop-opacity="0"/><stop offset="1" stop-color="#56351c" stop-opacity=".21"/></linearGradient></defs><rect width="430" height="600" fill="url(#edge)"/></svg>';
  57. const file='assets/maps/'+m.key+'.png';write('assets/maps/'+m.key+'.svg',svg);await sharp(Buffer.from(svg)).png().toFile(at(file));m.background=file;records.push({id:'map.'+m.key,file,width:750,height:1047,transparent:false,source:'assets/maps/'+m.key+'.svg',pivot:[.5,.5],nineSlice:[0,0,0,0]});
  58. }
  59. write('assets/maps/maps.json',{coordinateSize:[430,600],referenceWidth:750,maps});
  60. // Eight-frame transparent VFX sheets are vector-authored and editable.
  61. for(const name of ['impact','frost','repair','muzzle','portal']){
  62. let svg='<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="128" viewBox="0 0 1024 128"><defs><radialGradient id="fire"><stop stop-color="#fff6cb"/><stop offset=".35" stop-color="#ffd485"/><stop offset=".7" stop-color="#db7940" stop-opacity=".8"/><stop offset="1" stop-color="#8e4235" stop-opacity="0"/></radialGradient></defs>';
  63. for(let i=0;i<8;i++){const t=i/7,a=1-t*.9,r=8+t*49,x=i*128+64;svg+=`<g transform="translate(${x} 64)" opacity="${a}">`;
  64. if(name==='impact')svg+=`<circle r="${r}" fill="url(#fire)"/><circle r="${r*.94}" fill="none" stroke="#ffdf9b" stroke-width="${4*(1-t)+1}"/>`;
  65. if(name==='frost'){svg+=`<circle r="${r}" fill="#97dae5" fill-opacity=".13" stroke="#cce9e9" stroke-width="2"/>`;for(let j=0;j<6;j++)svg+=`<path transform="rotate(${j*60+t*20})" d="M0 -${r*.5} L4 -${r*.74} L0 -${r} L-4 -${r*.74} Z" fill="#d5edf0"/>`;}
  66. if(name==='repair')svg+=`<circle r="${r}" fill="none" stroke="#b9d993" stroke-width="2"/><path d="M-5 -20H5V-5H20V5H5V20H-5V5H-20V-5H-5Z" transform="translate(0 ${-t*16}) scale(${.6+t*.45})" fill="#d2e4a7"/>`;
  67. if(name==='muzzle')svg+=`<path d="M-16 -5 L${34-t*18} -${13-t*9} L16 0 L${34-t*18} ${13-t*9} L-16 5Z" fill="#ffdc93"/><ellipse cx="0" rx="15" ry="5" fill="#fff8d9"/>`;
  68. if(name==='portal')svg+=`<ellipse rx="${30+3*Math.sin(t*6.28)}" ry="${48+3*Math.sin(t*6.28)}" fill="#9c74bb" fill-opacity=".1" stroke="#c4a1df" stroke-width="3" transform="rotate(${t*12})"/><ellipse rx="17" ry="35" fill="none" stroke="#a785cf" stroke-width="2" transform="rotate(${-t*24})"/>`;
  69. svg+='</g>';
  70. }
  71. svg+='</svg>';const source='assets/fx/'+name+'.svg',file='assets/fx/'+name+'.png';write(source,svg);await sharp(Buffer.from(svg)).png().toFile(at(file));records.push({id:'fx.'+name,source,file,width:1024,height:128,transparent:true,frames:8,grid:[8,1],fps:name==='portal'?12:16,pivot:[.5,.5],loop:name==='portal',nineSlice:[0,0,0,0]});
  72. }
  73. const backgrounds=['menu-desert','mode-campaign','mode-endless'];
  74. for(const name of backgrounds){const file='assets/art/'+name+'.png',m=await sharp(at(file)).metadata();records.push({id:'illustration.'+name,file,width:m.width,height:m.height,transparent:false,pivot:[.5,.5],nineSlice:[0,0,0,0]});}
  75. write('assets/animation.json',{version:1,notes:'Procedural sprite motion plus transparent VFX frame strips. No directional skeletal animation is implied.',units:'430-wide gameplay coordinates; multiply by 750/430 for reference UI',enemy:{run:{duration:.45,loop:true,positionY:[0,-1.3,0,1.3,0],mirrorX:'movement.x < 0'},fly:{duration:.78,loop:true,positionY:[0,-3,0,3,0]},hit:{duration:.12,brightness:[1.6,1]},death:{duration:.25,opacity:[1,0],scale:[1,.85]}},tower:{recoil:{duration:.12,positionY:[0,2,0]},levelUp:{duration:.55,scale:[1,1.12,1]}},ui:{pressed:{duration:.1,positionY:[0,2],brightness:.9},popup:{duration:.2,positionY:[8,0],scale:[.97,1],opacity:[0,1]}},effects:records.filter(a=>a.id.startsWith('fx.'))});
  76. write('theme.json',{style:'A / Handpainted Western Desert',reference:{width:750,height:1334,matchWidth:1,htmlLogicalWidth:430,htmlToDesign:750/430},colors:ui.palette,fonts:{brand:{family:'Rye',file:'assets/fonts/Rye-Regular.ttf'},heading:{family:'Bree Serif',file:'assets/fonts/BreeSerif-Regular.ttf'},body:{family:'Barlow Semi Condensed',file:'assets/fonts/BarlowSemiCondensed-SemiBold.ttf'},number:{family:'Barlow Semi Condensed',file:'assets/fonts/BarlowSemiCondensed-Bold.ttf'}},typeScaleDesign:{pageTitle:42,section:24,button:24,body:23,meta:19},geometry:{panelBorder:20,cardBorder:18,buttonBorder:16,iconBox:64,light:'upper left',corners:'clipped brass corners; small functional corner radii',shadow:'warm dark plum'},safeArea:'Read the platform safe-area inset; fill the background, inset the interactive root. Fit the entire 430×600 battlefield uniformly between HUD and dock.'});
  77. write('asset-manifest.json',{version:1,status:'awaiting_html_visual_review',style:'A',reference:[750,1334],sliceOrder:['top','right','bottom','left'],spriteSourceOrigin:'top-left; Unity pixel Y = atlasHeight - sourceRect.y - sourceRect.height',textPolicy:'All interface text remains live HTML or TextMeshPro. Art contains no interface labels.',generatedWith:'OpenAI imagegen; prompts and original paths in art-prompts.json',fonts:{license:'SIL Open Font License; license files included',source:'https://github.com/google/fonts/tree/main/ofl',families:['Rye','Bree Serif','Barlow Semi Condensed']},assets:records});
  78. const cards=records.map(a=>`<article><div class="image ${a.frames?'fx':''}" ${a.frames?`style="background-image:url('${a.file}')"`:''}>${a.frames?'':`<img loading="lazy" src="${a.file}" alt="${a.id}">`}</div><b>${a.id}</b><span>${a.width} × ${a.height}${a.transparent?' · Alpha':''}${a.frames?' · 8 frames':''}</span><a href="${a.file}" download>PNG ↓</a>${a.source?` <a href="${a.source}" download>SVG ↓</a>`:''}</article>`).join('');
  79. write('assets.html',`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Buffalo Siege · A 素材一览</title><style>@font-face{font-family:Bree;src:url('assets/fonts/BreeSerif-Regular.ttf')}*{box-sizing:border-box}body{margin:0;background:#201820;color:#dfc7a8;font:14px/1.6 system-ui,sans-serif}header{padding:30px 5vw;border-bottom:1px solid #776044}h1{font:32px Bree,serif;color:#f1d69f;margin:0 0 8px}header a{color:#e8bd72;margin-right:20px}main{padding:24px 5vw;display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:18px}article{background:#352735;border:1px solid #755a3d;padding:12px;min-width:0}article b,article span{display:block;overflow-wrap:anywhere}article b{color:#f1d7ae;font-size:13px;margin-top:9px}article span{font-size:11px;color:#b39e8a}article a{color:#e8bd72;font-size:12px}.image{height:150px;display:grid;place-items:center;background:repeating-conic-gradient(#382c36 0% 25%,#302630 0% 50%) 50% / 20px 20px}.image img{max-width:100%;max-height:145px;object-fit:contain}.image.fx{height:128px;width:128px;margin:auto;background-size:1024px 128px;animation:fx .5s steps(8) infinite}@keyframes fx{to{background-position:-1024px 0}}p{max-width:860px;margin:8px 0}</style><header><h1>Buffalo Siege / Style A</h1><p>统一素材清单 · ${records.length} 项资源。图像保留透明通道,文字独立排版。原始图集、单张切片、可编辑控件、四张地图、特效帧条与字体许可均包含在本地目录。</p><p><a href="index.html">← 返回交互预览</a><a href="asset-manifest.json" download>资源清单 JSON ↓</a><a href="theme.json" download>主题参数 JSON ↓</a><a href="assets/animation.json" download>动画参数 JSON ↓</a></p></header><main>${cards}</main></html>`);
  80. console.log('Exported '+records.length+' asset records, four maps, five effects and gallery.');