feat: sync Shanhe 2.2 source and add remote package verification
Shanhe source and offline package checks / verify (pull_request) Failing after 5s
Shanhe source and offline package checks / verify (pull_request) Failing after 5s
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict'),{createHash}=require('node:crypto'),decomp=require('poly-decomp');
|
||||
const index=JSON.parse(fs.readFileSync('research/county-map-index.json','utf8')),context={window:{}};vm.runInNewContext(fs.readFileSync('dist/county-index.js','utf8'),context);const catalog=context.window.COUNTY_INDEX;
|
||||
assert.equal(index.levels.length,329);assert.equal(catalog.levels.length,329);assert.equal(index.unavailable.length,4);assert.deepEqual(Array.from(catalog.unavailable,l=>l.id).sort(),['441900','442000','460400','620200']);
|
||||
const parents=JSON.parse(fs.readFileSync('research/prefecture-map-index.json','utf8')).levels.flatMap(p=>p.regions.filter(r=>r.unitType==='prefecture').map(r=>({...r,province:p.id})));
|
||||
assert.deepEqual(index.levels.concat(index.unavailable).map(l=>l.id).sort(),parents.map(l=>l.id).sort());for(const entry of index.levels.concat(index.unavailable)){const parent=parents.find(p=>p.id===entry.id);assert.equal(entry.name,parent.name);assert.equal(entry.province,parent.province);}
|
||||
const packages=new Map();for(const meta of catalog.levels){assert.ok(/^\.\/county\/\d{6}\.js$/.test(meta.path));if(!packages.has(meta.path))packages.set(meta.path,[]);packages.get(meta.path).push(meta);}
|
||||
assert.deepEqual(fs.readdirSync('dist/county').sort(),Array.from(packages.keys(),p=>p.split('/').pop()).sort());const packedLevels=new Map();for(const [path,metas] of packages){assert.ok(metas.length>=1&&metas.length<=2);assert.equal(new Set(metas.map(m=>m.province)).size,1);metas.sort((a,b)=>a.id.localeCompare(b.id));assert.equal(path,'./county/'+metas[0].id+'.js');const text=fs.readFileSync('dist/'+path.slice(2),'utf8');assert.equal(text,metas.map(m=>fs.readFileSync('src/county/'+m.id+'.js','utf8')).join('\n'));const local=[];vm.runInNewContext(text,{window:{PuzzleAtlas:{register:value=>{assert.ok(!packedLevels.has(value.id));packedLevels.set(value.id,value);local.push(value.id);}}}});assert.deepEqual(local,metas.map(m=>m.id));}
|
||||
assert.equal(packedLevels.size,329);let pieces=0,rings=0,holes=0,repairs=0;
|
||||
for(const entry of index.levels){
|
||||
const text=fs.readFileSync('src/county/'+entry.id+'.js','utf8');assert.equal(createHash('sha256').update(text).digest('hex'),entry.assetSha256);
|
||||
const level=packedLevels.get(entry.id),meta=catalog.levels.find(l=>l.id===entry.id);assert.ok(meta);assert.equal(meta.count,entry.regions.length);assert.equal(level.province,entry.province);assert.equal(level.kind,'county');assert.equal(level.regions.length,entry.regions.length);assert.equal(level.id,entry.id);
|
||||
const seen=new Set();for(const r of level.regions){const source=entry.regions.find(v=>v.id===r.id);assert.ok(source);assert.ok(!seen.has(r.id));seen.add(r.id);assert.equal(r.name,source.name);assert.equal(r.rings.length,source.rings);assert.equal((r.holes||[]).length,source.holes);repairs+=source.repairedSourcePolygons;
|
||||
for(const ring of r.rings.concat(r.holes||[])){assert.ok(ring.length>=3);assert.ok(ring.every(p=>p.length===2&&p.every(Number.isFinite)));assert.ok(decomp.isSimple(ring),r.name+' must have a simple boundary');let area=0;for(let i=0;i<ring.length;i++)area+=ring[i][0]*ring[(i+1)%ring.length][1]-ring[(i+1)%ring.length][0]*ring[i][1];assert.ok(Math.abs(area)>1e-10);}
|
||||
if((r.holes&&r.holes.length)||(entry.collisionFallbacks||[]).includes(r.id))assert.ok(r.physics&&r.physics.length);pieces++;rings+=r.rings.length;holes+=(r.holes||[]).length;
|
||||
}
|
||||
// Every county participates in a connected puzzle, including marked island routes.
|
||||
const connected=new Set([0]);for(let i=0;i<level.regions.length;i++)for(const [a,b,type] of level.edges){assert.ok(a>=0&&b>=0&&a<level.regions.length&&b<level.regions.length);assert.ok(type>=0&&type<=2);if(connected.has(a)||connected.has(b)){connected.add(a);connected.add(b);}}assert.equal(connected.size,level.regions.length,level.name+' puzzle must be connected');
|
||||
}
|
||||
assert.equal(pieces,2728);const report={passed:true,stages:329,countyFiles:packages.size,pieces,rings,holes,repairedSourcePolygons:repairs,exceptions:index.unavailable,scope:'Frozen provider coverage, source names/IDs, topology repairs, static collision holes and all local assets; not current authoritative administrative validation.'};fs.writeFileSync('artifacts/county-map-audit.json',JSON.stringify(report,null,2));console.log('县区关卡核对通过:329关、2728块、'+packages.size+'个县区文件,本地文件/来源索引/父级/边界拓扑/内环碰撞/关卡连通性完整。');
|
||||
+22
-1
@@ -1,5 +1,5 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
|
||||
const context={window:{}};vm.runInNewContext(fs.readFileSync('src/maps.js','utf8'),context);const data=context.window.MAP_DATA,level=data.levels[0],source=JSON.parse(fs.readFileSync('research/china.json','utf8'));
|
||||
const context={window:{}};assert.equal(fs.readFileSync('dist/maps.js','utf8'),fs.readFileSync('src/maps.js','utf8'),'地图源素材与构建产物必须一致,请在地图生成完成后重新构建');vm.runInNewContext(fs.readFileSync('dist/maps.js','utf8'),context);const data=context.window.MAP_DATA,level=data.levels[0],source=JSON.parse(fs.readFileSync('research/china.json','utf8'));
|
||||
const expected=['110000','120000','130000','140000','150000','210000','220000','230000','310000','320000','330000','340000','350000','360000','370000','410000','420000','430000','440000','450000','460000','500000','510000','520000','530000','540000','610000','620000','630000','640000','650000','710000','810000','820000'];
|
||||
assert.deepEqual(Array.from(level.regions,r=>r.id).sort(),expected.slice().sort());
|
||||
const regions=level.regions.map(r=>{const f=source.features.find(f=>String(f.properties.adcode)===r.id),raw=f.geometry.type==='MultiPolygon'?f.geometry.coordinates:[f.geometry.coordinates];assert.equal(r.name,f.properties.name);assert.equal(r.rings.length,raw.length,r.name+'不得丢弃独立外环');for(const ring of r.rings){assert.ok(ring.length>=3);assert.ok(ring.every(p=>p.length===2&&p.every(Number.isFinite)));let area=0;for(let i=0;i<ring.length;i++)area+=ring[i][0]*ring[(i+1)%ring.length][1]-ring[(i+1)%ring.length][0]*ring[i][1];assert.ok(Math.abs(area)>1e-10,r.name+'存在退化外环');}return {id:r.id,name:r.name,sourcePolygonCount:raw.length,packagedPolygonCount:r.rings.length};});
|
||||
@@ -7,3 +7,24 @@ const maritime=source.features.find(f=>f.properties.adcode==='100000_JD');assert
|
||||
assert.ok(level.edges.some(e=>e[2]===1&&(level.regions[e[0]].id==='710000'||level.regions[e[1]].id==='710000')));
|
||||
const report={passed:true,provinceCount:34,regions,maritimeSegments:level.decorations.length,taiwanIncluded:true,hongKongIncluded:true,macaoIncluded:true,countyAndPrefectureLimitation:'台湾省地级轮廓接口404;无对应地级关卡。直辖市、港澳不设地级单元关卡。',scope:'验证34项名称/代码及源数据外环未丢失,不等于标准地图审图或所有最新区划/全部岛礁的独立权威核验。',mapContentReference:'https://www.gov.cn/gongbao/content/2023/content_5752310.htm'};
|
||||
fs.writeFileSync('artifacts/map-audit.json',JSON.stringify(report,null,2));console.log('地图核对通过:34省级行政区,含台湾/香港/澳门;全部源外环保留,海域线层'+level.decorations.length+'段。');
|
||||
// A province endpoint lists all immediate children. Audit the frozen source
|
||||
// list, including province-administered county-level peers, not only counts.
|
||||
const provinceIndex=JSON.parse(fs.readFileSync('research/prefecture-map-index.json','utf8'));
|
||||
assert.equal(provinceIndex.levels.length,27);let provinceDirectPieces=0,prefecturePieces=0;
|
||||
for(const entry of provinceIndex.levels){
|
||||
const lv=data.levels.find(l=>l.id===entry.id);assert.ok(lv&&lv.kind==='prefecture');
|
||||
assert.deepEqual(Array.from(lv.regions,r=>r.id).sort(),entry.regions.map(r=>r.id).sort(),entry.name+'不得过滤省直辖地区或遗漏源子区域');
|
||||
assert.equal(new Set(lv.regions.map(r=>r.id)).size,lv.regions.length);
|
||||
for(const r of lv.regions){const expected=entry.regions.find(v=>v.id===r.id);assert.equal(r.name,expected.name);assert.equal(r.unitType,expected.unitType);assert.equal(r.rings.length,expected.rings,r.name+'源外环必须保留');assert.equal((r.holes||[]).length,expected.holes,r.name+'源内环必须保留');if(r.unitType==='province-direct')provinceDirectPieces++;else prefecturePieces++;for(const ring of r.rings.concat(r.holes||[]))assert.ok(ring.length>=3&&ring.every(p=>p.every(Number.isFinite)));if(r.holes&&r.holes.length)assert.ok(r.physics&&r.physics.length);}
|
||||
const direct=entry.regions.filter(r=>r.unitType==='province-direct').length;
|
||||
assert.equal(lv.directRegionCount||0,direct);if(direct){assert.equal(lv.playLabel,'省域拼图');assert.ok(lv.unitCaption.includes('省直辖'));}
|
||||
}
|
||||
assert.equal(prefecturePieces,333);assert.equal(provinceDirectPieces,30);
|
||||
const hainan=data.levels.find(l=>l.id==='460000');assert.ok(hainan.mapInsets&&hainan.mapInsets.length===1);assert.equal(hainan.mapInsets[0].id,'460300');assert.ok(hainan.mapInsets[0].label.includes('缩放移位示意'));assert.ok(hainan.scopeNote.includes('三沙'));
|
||||
report.prefectureLevels=27;report.prefecturePieces=prefecturePieces;report.provinceDirectPieces=provinceDirectPieces;report.provinceChildPieces=prefecturePieces+provinceDirectPieces;
|
||||
console.log('省内完整性核对通过:27关、333个地级单元及30个省直辖地区,全部源子区域/外环/内环保留。');
|
||||
// The detailed-level index records source IDs, names and exterior/hole counts.
|
||||
const detailIndex=JSON.parse(fs.readFileSync('research/detail-map-index.json','utf8'));
|
||||
assert.equal(detailIndex.levels.length,7);let detailPieces=0;
|
||||
for(const entry of detailIndex.levels){const lv=data.levels.find(l=>l.id===entry.id);assert.ok(lv&&lv.kind===entry.kind);assert.equal(lv.regions.length,entry.regions.length);for(const r of lv.regions){const raw=entry.regions.find(v=>v.id===r.id);assert.ok(raw);assert.equal(r.name,raw.name);assert.equal(r.rings.length,raw.rings,r.name+'源外环必须保留');assert.equal((r.holes||[]).length,raw.holes||0,r.name+'源内环必须保留');for(const ring of r.rings.concat(r.holes||[])){assert.ok(ring.length>=3);assert.ok(ring.every(p=>p.every(Number.isFinite)));}if(r.holes&&r.holes.length)assert.ok(r.physics&&r.physics.length);detailPieces++;}}
|
||||
report.detailedLevels=detailIndex.levels.map(l=>({id:l.id,name:l.name,kind:l.kind,pieces:l.regions.length,source:l.source,snapshot:l.snapshot}));report.detailedPieces=detailPieces;report.countyAndPrefectureLimitation='四直辖市县区、香港/澳门分区、台湾县市细分关卡已开放;台湾远海岛屿移位示意,金门/连江不重复列入台湾。';fs.writeFileSync('artifacts/map-audit.json',JSON.stringify(report,null,2));console.log('细分地图核对通过:7个新增关卡、'+detailPieces+'块,源外环/内环及类型标注完整。');
|
||||
|
||||
+11
-3
@@ -1,15 +1,23 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {transform} from 'esbuild';
|
||||
import vm from 'node:vm';
|
||||
import packCountyMaps from './pack-county-maps.cjs';
|
||||
import {transform,build} from 'esbuild';
|
||||
import {execFileSync} from 'node:child_process';
|
||||
fs.rmSync('dist',{force:true,recursive:true});fs.mkdirSync('dist/vendor',{recursive:true});
|
||||
for(const name of ['index.html','style.css','maps.js'])fs.copyFileSync('src/'+name,'dist/'+name);
|
||||
for(const name of ['core.js','game.js','result.js','app.js']){const result=await transform(fs.readFileSync('src/'+name,'utf8'),{target:['chrome61'],minify:true,legalComments:'inline'});fs.writeFileSync('dist/'+name,result.code);}
|
||||
for(const name of ['core.js','atlas.js','game.js','result.js','app.js']){const result=await transform(fs.readFileSync('src/'+name,'utf8'),{target:['chrome61'],minify:true,legalComments:'inline'});fs.writeFileSync('dist/'+name,result.code);}
|
||||
await build({entryPoints:['src/video.js'],outfile:'dist/video.js',bundle:true,format:'iife',target:['es2017','chrome61'],minify:true,legalComments:'inline'});
|
||||
const countyContext={window:{}};vm.runInNewContext(fs.readFileSync('src/county-index.js','utf8'),countyContext);
|
||||
const countyPackage=packCountyMaps(countyContext.window.COUNTY_INDEX,id=>fs.readFileSync('src/county/'+id+'.js','utf8'));
|
||||
fs.writeFileSync('dist/county-index.js','window.COUNTY_INDEX='+JSON.stringify(countyPackage.index)+';\n');
|
||||
fs.mkdirSync('dist/county',{recursive:true});for(const [file,text] of countyPackage.files)fs.writeFileSync('dist/'+file,text);
|
||||
for(const name of ['matter.min.js','decomp.min.js'])fs.copyFileSync('src/vendor/'+name,'dist/vendor/'+name);
|
||||
// Include third-party notices in an allowed local asset, outside game UI.
|
||||
fs.writeFileSync('dist/licenses.json',JSON.stringify({matter:{version:'0.20.0',license:fs.readFileSync('node_modules/matter-js/LICENSE','utf8')},decomp:{version:'0.3.0',license:fs.readFileSync('node_modules/poly-decomp/LICENSE','utf8')},maps:{source:'DataV.GeoAtlas',url:'https://datav.aliyun.com/portal/school/atlas/area_selector',downloaded:'2026-10-16',note:'Public data; geographic outlines simplified for a game. Original provider terms apply.'}},null,2));
|
||||
fs.writeFileSync('dist/licenses.json',JSON.stringify({matter:{version:'0.20.0',license:fs.readFileSync('node_modules/matter-js/LICENSE','utf8')},decomp:{version:'0.3.0',license:fs.readFileSync('node_modules/poly-decomp/LICENSE','utf8')},mp4Muxer:{version:'5.2.2',license:fs.readFileSync('node_modules/mp4-muxer/LICENSE','utf8')},taiwanCounty:{source:'NLSC',snapshot:'COUNTY_MOI_1090820',url:'https://data.gov.tw/dataset/7442',license:'政府資料開放授權條款第1版',licenseURL:'https://data.gov.tw/license',downloaded:'2026-10-17',note:'County/city outlines simplified for gameplay; remote island clusters use a labelled translated inset. Kinmen and Lienchiang belong to Fujian and are not duplicated in the Taiwan level.'},maps:{source:'DataV.GeoAtlas',url:'https://datav.aliyun.com/portal/school/atlas/area_selector',downloaded:'2026-10-16',note:'Public data; geographic outlines simplified for a game. Original provider terms apply.'}},null,2));
|
||||
execFileSync(process.execPath,['scripts/check.mjs'],{stdio:'inherit'});
|
||||
execFileSync(process.execPath,['scripts/audit-maps.cjs'],{stdio:'inherit'});
|
||||
execFileSync(process.execPath,['scripts/audit-county-maps.cjs'],{stdio:'inherit'});
|
||||
fs.mkdirSync('artifacts',{recursive:true});const audit='.codex/skills/minitool-zip-builder/scripts/audit_artifact.py';
|
||||
if(!fs.existsSync(audit))throw Error('缺少用户指定官方 Skill,请先安装 1.8.0。');
|
||||
const dirAudit=execFileSync('python3',[audit,'dist'],{encoding:'utf8'});console.log('官方目录审计:'+dirAudit.trim());
|
||||
|
||||
@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import {parse} from 'acorn
|
||||
const issues=[];const root='dist';
|
||||
function walk(dir){return fs.readdirSync(dir,{withFileTypes:true}).flatMap(d=>d.isDirectory()?walk(path.join(dir,d.name)):[path.join(dir,d.name)]);}
|
||||
const files=walk(root),allowed=new Set(['.html','.css','.js','.json','.png','.jpg','.jpeg','.webp','.gif','.svg','.woff','.woff2']);
|
||||
if(files.length>200)issues.push('ZIP文件数量超过200个上限: '+files.length);
|
||||
for(const f of files){if(!allowed.has(path.extname(f)))issues.push('不允许的文件类型: '+f);if(path.basename(f).startsWith('.'))issues.push('隐藏文件: '+f);const source=fs.readFileSync(f,'utf8');if(f.endsWith('.js')){try{parse(source,{ecmaVersion:2017});}catch(e){issues.push('非 ES2017 语法: '+f+' '+e.message);}const banned=[/\beval\s*\(/,/\bnew\s+Function\s*\(/,/\bfetch\s*\(/,/\bXMLHttpRequest\b/,/\bWebAssembly\b/,/\bnew\s+(?:SharedWorker|Worker|WebSocket|EventSource)\s*\(/,/navigator\.(?:clipboard|geolocation)/,/requestFullscreen\s*\(/,/window\.open\s*\(/];for(const re of banned)if(re.test(source))issues.push('禁用能力 '+re+' '+f);}
|
||||
if(f.endsWith('.html')){for(const m of source.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi))if(m[1].trim())issues.push('内联脚本');if(/\son[a-z]+\s*=/i.test(source))issues.push('行内事件');if(/<meta[^>]+Content-Security-Policy|type=[\"']module[\"']/i.test(source))issues.push('自建CSP或模块脚本');if(/<(?:iframe|object|form)\b|javascript:|\sdownload[\s=>]/i.test(source))issues.push('禁止的 HTML 能力');for(const m of source.matchAll(/(?:src|href)="([^"#]+)"/g)){if(!m[1].startsWith('./'))issues.push('非相对本地资源: '+m[1]);else if(!fs.existsSync(path.join(root,m[1])))issues.push('缺失资源: '+m[1]);}}
|
||||
if(f.endsWith('.css')){for(const m of source.matchAll(/url\(([^)]+)\)/g))if(/https?:|\/\//.test(m[1]))issues.push('外部样式资源');const banned=[/[;{]\s*gap\s*:/,/\bclamp\(/,/\bcolor-mix\(/,/\bdvh\b/,/\baspect-ratio\s*:/];for(const re of banned)if(re.test(source))issues.push('无降级的现代 CSS '+re);}}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Download/audit county GIS inputs without changing the released game maps.
|
||||
|
||||
Raw source geometry, reproducible per-city game coordinates and a provenance
|
||||
manifest live in ignored data/. Four cities without county children retain
|
||||
their whole-city outline instead of fabricated county or township polygons.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import pathlib
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
from map_geometry import make_level, place_labels
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
BASE = "https://geo.datav.aliyun.com/areas_v3/bound/"
|
||||
EXCEPTIONS = {
|
||||
"441900": "https://www.dg.gov.cn/zjdz/dzgk/xzqh/content/post_2824924.html",
|
||||
"442000": "https://www.zs.gov.cn/zjzs/zsgk/content/post_1669002.html",
|
||||
"460400": "https://www.danzhou.gov.cn/danzhou/index.html",
|
||||
"620200": "https://wap.jyg.gov.cn/zjjyg/",
|
||||
}
|
||||
|
||||
|
||||
def read_json(path):
|
||||
return json.loads(path.read_text())
|
||||
|
||||
|
||||
def inspect_features(data, parent, whole=False):
|
||||
if data.get("type") != "FeatureCollection" or not data.get("features"):
|
||||
raise ValueError("Expected a non-empty FeatureCollection")
|
||||
entries, seen = [], set()
|
||||
for feature in data["features"]:
|
||||
prop = feature.get("properties", {})
|
||||
code = str(prop.get("adcode", ""))
|
||||
if not code.isdigit() or code in seen or not prop.get("name"):
|
||||
raise ValueError("Missing/duplicate feature id or name")
|
||||
seen.add(code)
|
||||
if whole:
|
||||
if code != parent:
|
||||
raise ValueError("Whole-city feature does not match city")
|
||||
elif (str(prop.get("parent", {}).get("adcode")) != parent
|
||||
or prop.get("level") != "district"):
|
||||
raise ValueError("County is not an immediate district child")
|
||||
geo = feature.get("geometry", {})
|
||||
if geo.get("type") not in ("Polygon", "MultiPolygon"):
|
||||
raise ValueError("Unexpected non-polygon geometry")
|
||||
polys = geo["coordinates"] if geo["type"] == "MultiPolygon" else [geo["coordinates"]]
|
||||
rings = holes = points = 0
|
||||
for polygon in polys:
|
||||
if not polygon:
|
||||
raise ValueError("Empty polygon")
|
||||
rings += 1
|
||||
holes += len(polygon) - 1
|
||||
for ring in polygon:
|
||||
if len(ring) < 4 or ring[0] != ring[-1]:
|
||||
raise ValueError("Open or degenerate source ring")
|
||||
for point in ring:
|
||||
if (len(point) < 2 or not all(isinstance(v, (int, float))
|
||||
and math.isfinite(v) for v in point[:2])
|
||||
or not -180 <= point[0] <= 180 or not -90 <= point[1] <= 90):
|
||||
raise ValueError("Invalid geographic coordinate")
|
||||
if abs(sum(a[0]*b[1]-b[0]*a[1] for a, b in zip(ring, ring[1:]))) < 1e-15:
|
||||
raise ValueError("Zero-area source ring")
|
||||
points += len(ring)
|
||||
entries.append({"id": code, "name": prop["name"], "rings": rings,
|
||||
"holes": holes, "points": points})
|
||||
return entries
|
||||
|
||||
|
||||
def get_source(code, folder, whole=False):
|
||||
suffix = ".json" if whole else "_full.json"
|
||||
url = BASE + code + suffix
|
||||
path = folder / (code + ".json")
|
||||
if path.exists():
|
||||
raw = path.read_bytes()
|
||||
data = json.loads(raw)
|
||||
regions = inspect_features(data, code, whole)
|
||||
return raw, data, regions, url
|
||||
for attempt in range(3):
|
||||
try:
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "ShanhePuzzle-GIS/1.0"})
|
||||
with urllib.request.urlopen(request, timeout=35) as response:
|
||||
raw = response.read()
|
||||
data = json.loads(raw)
|
||||
regions = inspect_features(data, code, whole)
|
||||
tmp = path.with_suffix(".partial")
|
||||
tmp.write_bytes(raw)
|
||||
tmp.replace(path)
|
||||
return raw, data, regions, url
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404 or attempt == 2:
|
||||
raise
|
||||
except Exception:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(.5 * (attempt + 1))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--snapshot", required=True, help="Local YYYY-MM-DD snapshot label")
|
||||
parser.add_argument("--only", help="Optional comma-separated city ids for a small probe")
|
||||
args = parser.parse_args()
|
||||
datetime.date.fromisoformat(args.snapshot)
|
||||
index = read_json(ROOT / "research/prefecture-map-index.json")
|
||||
cities = [dict(region, province=province["id"], provinceName=province["name"])
|
||||
for province in index["levels"] for region in province["regions"]
|
||||
if region["unitType"] == "prefecture"]
|
||||
if args.only:
|
||||
selected = set(args.only.split(","))
|
||||
cities = [city for city in cities if city["id"] in selected]
|
||||
if len(cities) != len(selected):
|
||||
raise ValueError("Unknown city id in --only")
|
||||
dest = ROOT / "data/city-county-gis" / args.snapshot
|
||||
for name in ["raw", "unsplit", "levels"]:
|
||||
(dest / name).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def fetch(city):
|
||||
code = city["id"]
|
||||
entry = {"id": code, "name": city["name"], "province": city["province"],
|
||||
"provinceName": city["provinceName"]}
|
||||
try:
|
||||
raw, data, regions, url = get_source(code, dest / "raw")
|
||||
entry.update(status="available", path="raw/"+code+".json", source=url,
|
||||
sha256=hashlib.sha256(raw).hexdigest(), bytes=len(raw), regions=regions)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 404 or code not in EXCEPTIONS:
|
||||
entry.update(status="failed", reason=str(error))
|
||||
return entry
|
||||
try:
|
||||
raw, data, regions, url = get_source(code, dest / "unsplit", whole=True)
|
||||
prop = data["features"][0]["properties"]
|
||||
if len(regions) != 1 or prop.get("childrenNum") != 0:
|
||||
raise ValueError("Cannot confirm the no-county-child exception")
|
||||
entry.update(status="no_county_children", path="unsplit/"+code+".json",
|
||||
source=url, unavailableChildSource=BASE+code+"_full.json",
|
||||
sourceChildrenNum=0, reference=EXCEPTIONS[code],
|
||||
sha256=hashlib.sha256(raw).hexdigest(), bytes=len(raw), regions=regions,
|
||||
note="Whole-city outline only; township boundaries are not supplied by this source.")
|
||||
except Exception as fallback_error:
|
||||
entry.update(status="failed", reason=str(fallback_error))
|
||||
except Exception as error:
|
||||
entry.update(status="failed", reason=str(error))
|
||||
return entry
|
||||
|
||||
entries = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
|
||||
futures = [pool.submit(fetch, city) for city in cities]
|
||||
for future in concurrent.futures.as_completed(futures):
|
||||
entries.append(future.result())
|
||||
if len(entries) % 25 == 0 or len(entries) == len(cities):
|
||||
print("GIS fetched:", len(entries), "/", len(cities), flush=True)
|
||||
entries.sort(key=lambda entry: entry["id"])
|
||||
failed = [entry for entry in entries if entry["status"] == "failed"]
|
||||
for entry in entries:
|
||||
if entry["status"] != "available":
|
||||
continue
|
||||
data = read_json(dest / entry["path"])
|
||||
level = make_level(data["features"], int(entry["id"]), entry["name"], int(entry["province"]))
|
||||
if not level:
|
||||
raise ValueError("No playable subdivision for " + entry["id"])
|
||||
level.update(kind="county", parent=entry["province"], playLabel="县区拼图")
|
||||
level.pop("projection", None)
|
||||
place_labels(level)
|
||||
source_by_id = {region["id"]: region for region in entry["regions"]}
|
||||
assert {region["id"] for region in level["regions"]} == set(source_by_id)
|
||||
for region in level["regions"]:
|
||||
expected = source_by_id[region["id"]]
|
||||
assert region["name"] == expected["name"]
|
||||
assert len(region["rings"]) == expected["rings"]
|
||||
assert len(region.get("holes", [])) == expected["holes"]
|
||||
for ring in region["rings"] + region.get("holes", []):
|
||||
assert len(ring) >= 3 and all(all(math.isfinite(v) for v in p) for p in ring)
|
||||
assert abs(sum(ring[i][0]*ring[(i+1)%len(ring)][1]
|
||||
-ring[(i+1)%len(ring)][0]*ring[i][1]
|
||||
for i in range(len(ring)))) > 1e-10
|
||||
encoded = json.dumps(level, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
path = dest / "levels" / (entry["id"] + ".json")
|
||||
path.write_bytes(encoded)
|
||||
entry["preparedPath"] = "levels/" + path.name
|
||||
entry["preparedSha256"] = hashlib.sha256(encoded).hexdigest()
|
||||
available = [entry for entry in entries if entry["status"] == "available"]
|
||||
manifest = {"source": "DataV.GeoAtlas", "snapshotDate": args.snapshot,
|
||||
"scope": "Existing game's prefectural areas; provider snapshot, not a guarantee of current administrative boundaries.",
|
||||
"rawCoordinates": "Source longitude/latitude values preserved; datum not declared by the source, no WGS84/GCJ02 assumption.",
|
||||
"preparedCoordinates": "Simplified game-plane coordinates, longest extent 1000; not geographic GIS coordinates.",
|
||||
"releaseMapsChanged": False, "requested": len(cities), "available": len(available),
|
||||
"countyPieces": sum(len(entry["regions"]) for entry in available),
|
||||
"noCountyChildren": sum(entry["status"] == "no_county_children" for entry in entries),
|
||||
"failed": len(failed), "cities": entries}
|
||||
(dest / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2)+"\n")
|
||||
(dest / "README.md").write_text("# City county GIS material snapshot\n\n"
|
||||
"raw/: original per-city GeoJSON county outlines; longitude/latitude values are preserved.\n"
|
||||
"levels/: simplified per-city game coordinates, with every source outer ring and hole retained.\n"
|
||||
"unsplit/: whole-city outlines for four cities that report no county children.\n"
|
||||
"manifest.json: source URLs, county names/codes, raw/prepared checksums, coverage and exceptions.\n\n"
|
||||
"Prepared files still require collision decomposition, topology/playability and mobile performance validation before game integration. "
|
||||
"They are materials, not an uploadable mini-tool ZIP. No released game map is modified.\n")
|
||||
print(json.dumps({k: manifest[k] for k in ["requested", "available", "countyPieces", "noCountyChildren", "failed"]}), flush=True)
|
||||
if failed:
|
||||
print(json.dumps(failed, ensure_ascii=False), flush=True)
|
||||
raise SystemExit(1)
|
||||
artifact = ROOT / "artifacts" / ("city-county-gis-"+args.snapshot.replace("-", "")+".zip")
|
||||
artifact.parent.mkdir(exist_ok=True)
|
||||
paths = [dest / "manifest.json", dest / "README.md"]
|
||||
for entry in entries:
|
||||
paths.append(dest / entry["path"])
|
||||
if entry.get("preparedPath"):
|
||||
paths.append(dest / entry["preparedPath"])
|
||||
with zipfile.ZipFile(artifact, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
|
||||
for path in sorted(paths):
|
||||
bundle.write(path, path.relative_to(dest).as_posix())
|
||||
print("GIS material ZIP:", artifact, "|", artifact.stat().st_size, "bytes", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Build-time geometry simplification shared by prefecture and detailed maps."""
|
||||
import math
|
||||
def area(r):return abs(sum(r[i][0]*r[(i+1)%len(r)][1]-r[(i+1)%len(r)][0]*r[i][1] for i in range(len(r)))/2)
|
||||
def dist(p,a,b):
|
||||
dx,dy=b[0]-a[0],b[1]-a[1];n=dx*dx+dy*dy
|
||||
t=max(0,min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/n)) if n else 0
|
||||
return (p[0]-a[0]-t*dx)**2+(p[1]-a[1]-t*dy)**2
|
||||
def dp(p,eps):
|
||||
if len(p)<3:return p
|
||||
v,i=max((dist(p[k],p[0],p[-1]),k) for k in range(1,len(p)-1))
|
||||
if v<=eps*eps:return [p[0],p[-1]]
|
||||
return dp(p[:i+1],eps)[:-1]+dp(p[i:],eps)
|
||||
def project(p):return [p[0]*.82,-math.log(math.tan(math.pi/4+math.radians(p[1])/2))*180/math.pi*.82]
|
||||
def make_level(features,code,name,province):
|
||||
fs=[f for f in features if f.get('properties',{}).get('name') and f['properties'].get('adcode')]
|
||||
if len(fs)<2:return None
|
||||
reg=[];boundary=[]
|
||||
for f in fs:
|
||||
prop=f['properties'];g=f['geometry'];polys=g['coordinates'] if g['type']=='MultiPolygon' else [g['coordinates']]
|
||||
rings=[project_ring(p[0]) for p in polys if len(p[0])>=4]
|
||||
holes=[project_ring(hole) for poly in polys for hole in poly[1:] if len(hole)>=4]
|
||||
rings.sort(key=area,reverse=True)
|
||||
if not rings:continue
|
||||
main=rings[0];boundary.append({(round(x,3),round(y,3)) for r in rings+holes for x,y in r})
|
||||
# Keep island geometry, simplify each independently; no invented boundaries.
|
||||
span=max(max(p[0] for p in main)-min(p[0] for p in main),max(p[1] for p in main)-min(p[1] for p in main))
|
||||
simple=[]
|
||||
for r in rings:
|
||||
localspan=max(max(p[0] for p in r)-min(p[0] for p in r),max(p[1] for p in r)-min(p[1] for p in r))
|
||||
eps=max(min(span*.005,localspan*.01),.00000001);q=dp(r,eps)
|
||||
while len(q)>90:eps*=1.4;q=dp(r,eps)
|
||||
if len(q)<4:q=r
|
||||
simple.append(q[:-1] if q[0]==q[-1] else q)
|
||||
cx=sum(x for x,y in main[:-1])/max(1,len(main)-1);cy=sum(y for x,y in main[:-1])/max(1,len(main)-1)
|
||||
entry={'id':str(prop['adcode']),'name':prop['name'],'rings':simple,'center':[cx,cy]}
|
||||
if holes:
|
||||
entry['holes']=[]
|
||||
for hole in holes:
|
||||
eps=span*.001;q=dp(hole,eps)
|
||||
while len(q)>90:eps*=1.4;q=dp(hole,eps)
|
||||
if len(q)<4:q=hole
|
||||
entry['holes'].append(q[:-1] if q[0]==q[-1] else q)
|
||||
reg.append(entry)
|
||||
if len(reg)<2:return None
|
||||
edges=[]
|
||||
for i in range(len(reg)):
|
||||
for j in range(i):
|
||||
if len(boundary[i]&boundary[j])>=2:edges.append([j,i,0])
|
||||
# Join disconnected island components with explicit game-only sea routes.
|
||||
def components():
|
||||
groups=[{i} for i in range(len(reg))]
|
||||
for a,b,_ in edges:
|
||||
ga=next(g for g in groups if a in g);gb=next(g for g in groups if b in g)
|
||||
if ga is not gb:ga.update(gb);groups.remove(gb)
|
||||
return groups
|
||||
while len(components())>1:
|
||||
gs=components();candidates=[]
|
||||
for a in gs[0]:
|
||||
for g in gs[1:]:
|
||||
for b in g:
|
||||
pa,pb=reg[a]['center'],reg[b]['center'];candidates.append(((pa[0]-pb[0])**2+(pa[1]-pb[1])**2,a,b))
|
||||
_,a,b=min(candidates);edges.append([a,b,1])
|
||||
allp=[p for r in reg for ring in r['rings'] for p in ring]
|
||||
minx,miny=min(p[0] for p in allp),min(p[1] for p in allp);maxx,maxy=max(p[0] for p in allp),max(p[1] for p in allp)
|
||||
span=max(maxx-minx,maxy-miny);scale=1000/span
|
||||
for r in reg:
|
||||
r['center']=[round((r['center'][0]-minx)*scale,2),round((r['center'][1]-miny)*scale,2)]
|
||||
r['rings']=[[[round((x-minx)*scale,4),round((y-miny)*scale,4)] for x,y in ring] for ring in r['rings']]
|
||||
if r.get('holes'):r['holes']=[[[round((x-minx)*scale,4),round((y-miny)*scale,4)] for x,y in ring] for ring in r['holes']]
|
||||
return {'id':str(code),'name':name,'province':str(province),'width':round((maxx-minx)*scale,2),'height':round((maxy-miny)*scale,2),'regions':reg,'edges':edges,'projection':[minx,miny,scale]}
|
||||
def project_ring(r):return [project(p) for p in r]
|
||||
|
||||
def inside(p,ring):
|
||||
x,y=p;hit=False
|
||||
for i,a in enumerate(ring):
|
||||
b=ring[(i+1)%len(ring)]
|
||||
if (a[1]>y)!=(b[1]>y) and x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0]:hit=not hit
|
||||
return hit
|
||||
|
||||
def place_labels(lv):
|
||||
for r in lv['regions']:
|
||||
ring=r['rings'][0];minx,maxx=min(p[0] for p in ring),max(p[0] for p in ring);miny,maxy=min(p[1] for p in ring),max(p[1] for p in ring)
|
||||
candidates=[[minx+(maxx-minx)*i/14,miny+(maxy-miny)*j/14] for i in range(1,14) for j in range(1,14)]
|
||||
candidates=[p for p in candidates if inside(p,ring) and not any(inside(p,hole) for hole in r.get('holes',[]))]
|
||||
if candidates:r['label']=max(candidates,key=lambda p:min(dist(p,ring[k],ring[(k+1)%len(ring)]) for k in range(len(ring))))
|
||||
else:r['label']=r['center']
|
||||
r['label']=[round(v,3) for v in r['label']]
|
||||
|
||||
|
||||
def hainan_offshore_inset(lv):
|
||||
"""Gameplay inset: preserve every Sansha ring, uniformly scale and translate.
|
||||
|
||||
The national map and raw coordinates are untouched. Only this provincial
|
||||
puzzle uses a clearly labelled inset so the main island remains playable.
|
||||
"""
|
||||
if lv['id']!='460000':return
|
||||
offshore=next(r for r in lv['regions'] if r['id']=='460300')
|
||||
for r in lv['regions']:
|
||||
r['labelName']=r['name'].split('黎族')[0] if '黎族' in r['name'] else r['name'].removesuffix('市').removesuffix('县')
|
||||
mainland=[p for r in lv['regions'] if r is not offshore for ring in r['rings'] for p in ring]
|
||||
sea=[p for ring in offshore['rings'] for p in ring]
|
||||
minx,maxx=min(p[0] for p in mainland),max(p[0] for p in mainland)
|
||||
miny,maxy=min(p[1] for p in mainland),max(p[1] for p in mainland)
|
||||
sx,sy=min(p[0] for p in sea),min(p[1] for p in sea)
|
||||
sw,sh=max(p[0] for p in sea)-sx,max(p[1] for p in sea)-sy
|
||||
width,height=maxx-minx,maxy-miny
|
||||
factor=min(width*.38/sw,height*.55/sh)
|
||||
tx,ty=maxx+width*.10,maxy-height*.53
|
||||
move=lambda p:[tx+(p[0]-sx)*factor,ty+(p[1]-sy)*factor]
|
||||
offshore['rings']=[[move(p) for p in ring] for ring in offshore['rings']]
|
||||
if offshore.get('holes'):offshore['holes']=[[move(p) for p in ring] for ring in offshore['holes']]
|
||||
offshore['center']=move(offshore['center'])
|
||||
allp=[p for r in lv['regions'] for ring in r['rings'] for p in ring]
|
||||
bx,by=min(p[0] for p in allp),min(p[1] for p in allp)
|
||||
bw,bh=max(p[0] for p in allp)-bx,max(p[1] for p in allp)-by
|
||||
scale=1000/max(bw,bh)
|
||||
normalize=lambda p:[round((p[0]-bx)*scale,4),round((p[1]-by)*scale,4)]
|
||||
for r in lv['regions']:
|
||||
r['rings']=[[normalize(p) for p in ring] for ring in r['rings']]
|
||||
if r.get('holes'):r['holes']=[[normalize(p) for p in ring] for ring in r['holes']]
|
||||
r['center']=normalize(r['center'])
|
||||
lv['width'],lv['height']=round(bw*scale,2),round(bh*scale,2)
|
||||
# Reserve space around the islands, for a visible frame and explanatory label.
|
||||
a,b=normalize([tx-width*.025,ty-height*.025]),normalize([tx+sw*factor+width*.025,ty+sh*factor+height*.025])
|
||||
lv['mapInsets']=[{'id':'460300','label':'三沙诸岛 · 缩放移位示意','x':a[0],'y':a[1],'width':b[0]-a[0],'height':b[1]-a[1]}]
|
||||
lv['scopeNote']='含15个省直辖地区;三沙诸岛缩放移位示意。'
|
||||
lv['unitCaption']='地级及省直辖 · 三沙移位示意'
|
||||
lv['projectionNote']='海南省域游戏关卡使用三沙诸岛缩放移位示意,全国地图与源素材坐标保持原状。'
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
// Keep editable/auditable maps separate in source, but ship at most two
|
||||
// same-province stages per classic script to meet the 200-file ZIP limit.
|
||||
module.exports=function packCountyMaps(index,readStage){
|
||||
const levels=index.levels.map(meta=>({...meta})),provinces=new Map(),files=new Map(),seen=new Set();
|
||||
for(const meta of levels){if(!/^\d{6}$/.test(meta.id)||!/^\d{6}$/.test(meta.province)||seen.has(meta.id))throw Error('Invalid county catalog');seen.add(meta.id);if(!provinces.has(meta.province))provinces.set(meta.province,[]);provinces.get(meta.province).push(meta);}
|
||||
for(const entries of provinces.values()){entries.sort((a,b)=>a.id.localeCompare(b.id));for(let i=0;i<entries.length;i+=2){const group=entries.slice(i,i+2),file='county/'+group[0].id+'.js';for(const meta of group)meta.path='./'+file;files.set(file,group.map(meta=>readStage(meta.id)).join('\n'));}}
|
||||
return {index:{...index,levels},files};
|
||||
};
|
||||
+5
-3
@@ -1,10 +1,12 @@
|
||||
import pathlib,zipfile,json,hashlib
|
||||
root=pathlib.Path('dist');out=pathlib.Path('artifacts/shanhe-puzzle-xhs.zip')
|
||||
files=sorted(p for p in root.rglob('*') if p.is_file())
|
||||
if len(files)>200:raise SystemExit(f'ZIP文件数量超过200个上限: {len(files)}')
|
||||
with zipfile.ZipFile(out,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
|
||||
for p in sorted(root.rglob('*')):
|
||||
if p.is_file():z.write(p,p.relative_to(root).as_posix())
|
||||
for p in files:z.write(p,p.relative_to(root).as_posix())
|
||||
with zipfile.ZipFile(out) as z:
|
||||
assert 'index.html' in z.namelist()
|
||||
assert z.testzip() is None
|
||||
assert len(z.infolist())<=200
|
||||
print('离线 ZIP:',out.resolve(),' | ',round(out.stat().st_size/1024),'KB')
|
||||
pathlib.Path('artifacts/package-report.json').write_text(json.dumps({'file':str(out),'bytes':out.stat().st_size,'sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'archiveIntegrity':'passed','rootEntry':'index.html'},indent=2))
|
||||
pathlib.Path('artifacts/package-report.json').write_text(json.dumps({'file':str(out),'bytes':out.stat().st_size,'fileCount':len(files),'fileLimit':200,'sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'archiveIntegrity':'passed','rootEntry':'index.html'},indent=2))
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Install only the pinned official package auditor inside the remote CI image."""
|
||||
import hashlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
url = 'https://fe-static.xhscdn.com/minitool/20261015161653/minitool-zip-builder-1.8.0.skill'
|
||||
with urllib.request.urlopen(url, timeout=120) as response:
|
||||
archive = zipfile.ZipFile(io.BytesIO(response.read()))
|
||||
matches = [name for name in archive.namelist() if name.endswith('scripts/audit_artifact.py')]
|
||||
if len(matches) != 1:
|
||||
raise SystemExit('Official auditor missing or ambiguous')
|
||||
content = archive.read(matches[0])
|
||||
if hashlib.sha256(content).hexdigest() != '62ff11eae1d5bb566a6f74b0fa102fe2eb3ffe982b87596aca2f93485cc9de21':
|
||||
raise SystemExit('Official auditor changed; review before updating the pinned checksum')
|
||||
target = Path('.codex/skills/minitool-zip-builder/scripts/audit_artifact.py')
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(content)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Prepare independently loaded city/county game assets from a GIS snapshot.
|
||||
|
||||
Requires Shapely only for this preparation step; npm run build uses the saved
|
||||
src/county assets and source index and does not require Python GIS packages.
|
||||
"""
|
||||
import argparse, copy, hashlib, json, math, pathlib
|
||||
from shapely import make_valid
|
||||
from shapely.geometry import Polygon, MultiPolygon
|
||||
from map_geometry import project
|
||||
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
|
||||
def polygons(geometry):
|
||||
if geometry.geom_type=='Polygon':return [geometry]
|
||||
if hasattr(geometry,'geoms'):return [p for item in geometry.geoms for p in polygons(item)]
|
||||
return []
|
||||
|
||||
def rounded_ring(ring,digits):
|
||||
points=[]
|
||||
for p in list(ring.coords)[:-1]:
|
||||
q=[round(p[0],digits),round(p[1],digits)]
|
||||
q=[int(v) if float(v).is_integer() else v for v in q]
|
||||
if not points or q!=points[-1]:points.append(q)
|
||||
if len(points)>1 and points[0]==points[-1]:points.pop()
|
||||
return points
|
||||
|
||||
def compact_polygon(poly):
|
||||
x1,y1,x2,y2=poly.bounds;span=max(x2-x1,y2-y1);eps=span*.003
|
||||
simple=poly.simplify(eps,preserve_topology=True)
|
||||
for _ in range(18):
|
||||
if len(simple.exterior.coords)<=81:break
|
||||
candidate=poly.simplify(eps*1.3,preserve_topology=True)
|
||||
if candidate.area<poly.area*.97 or candidate.area>poly.area*1.03:break
|
||||
simple=candidate;eps*=1.3
|
||||
for digits in [1,2,3,4,6,8]:
|
||||
outer=rounded_ring(simple.exterior,digits);holes=[rounded_ring(h,digits) for h in simple.interiors]
|
||||
if len(outer)<3 or any(len(h)<3 for h in holes):continue
|
||||
candidate=Polygon(outer,holes)
|
||||
if candidate.is_valid and candidate.area>0 and abs(candidate.area-simple.area)/simple.area<=.01:
|
||||
return outer,holes,digits
|
||||
raise ValueError('Cannot quantize a polygon without losing its topology')
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--snapshot',default='2026-10-18');args=parser.parse_args()
|
||||
snapshot=ROOT/'data/city-county-gis'/args.snapshot;manifest=json.loads((snapshot/'manifest.json').read_text())
|
||||
dest=ROOT/'src/county';dest.mkdir(exist_ok=True);index={'source':manifest['source'],'snapshot':args.snapshot,'levels':[],'unavailable':[]};catalog=[];total=0;repairs=0
|
||||
for entry in manifest['cities']:
|
||||
if entry['status']!='available':
|
||||
index['unavailable'].append({'id':entry['id'],'name':entry['name'],'province':entry['province'],'reason':'no_county_children'})
|
||||
continue
|
||||
old=json.loads((snapshot/entry['preparedPath']).read_text());raw=json.loads((snapshot/entry['path']).read_text())
|
||||
all_points=[project(p) for f in raw['features'] for poly in (f['geometry']['coordinates'] if f['geometry']['type']=='MultiPolygon' else [f['geometry']['coordinates']]) for p in poly[0]]
|
||||
minx,miny=min(p[0] for p in all_points),min(p[1] for p in all_points);span=max(max(p[0] for p in all_points)-minx,max(p[1] for p in all_points)-miny);scale=1000/span
|
||||
def local(p):
|
||||
q=project(p);return [(q[0]-minx)*scale,(q[1]-miny)*scale]
|
||||
level={k:copy.deepcopy(old[k]) for k in ['id','name','province','width','height','edges']}
|
||||
level.update(kind='county',parent=entry['province'],provinceName=entry['provinceName'],playLabel='县区拼图',unitCaption='市辖区 · 县 · 县级市',scopeNote='左右调整待落块,松手落下,拼完整片'+entry['name']+'。',regions=[])
|
||||
proof=[]
|
||||
for feature in raw['features']:
|
||||
prop=feature['properties'];source_polys=feature['geometry']['coordinates'] if feature['geometry']['type']=='MultiPolygon' else [feature['geometry']['coordinates']]
|
||||
output=[];fixed=0
|
||||
for source_poly in source_polys:
|
||||
poly=Polygon([local(p) for p in source_poly[0]],[[local(p) for p in h] for h in source_poly[1:]])
|
||||
if not poly.is_valid:poly=make_valid(poly);fixed+=1
|
||||
pieces=polygons(poly)
|
||||
if not pieces:raise ValueError('No polygon after source repair')
|
||||
output.extend(pieces)
|
||||
output.sort(key=lambda p:p.area,reverse=True);region={'id':str(prop['adcode']),'name':prop['name'],'rings':[]};holes=[]
|
||||
for poly in output:
|
||||
outer,inner,digits=compact_polygon(poly);region['rings'].append(outer);holes.extend(inner)
|
||||
if holes:region['holes']=holes
|
||||
center=MultiPolygon(output).centroid;label=output[0].representative_point()
|
||||
region['center']=[round(center.x,1),round(center.y,1)];region['label']=[round(label.x,1),round(label.y,1)]
|
||||
level['regions'].append(region);repairs+=fixed
|
||||
proof.append({'id':region['id'],'name':region['name'],'sourceRings':len(source_polys),'sourceHoles':sum(len(p)-1 for p in source_polys),'rings':len(region['rings']),'holes':len(holes),'repairedSourcePolygons':fixed})
|
||||
assert [r['id'] for r in level['regions']]==[r['id'] for r in old['regions']]
|
||||
payload=json.dumps(level,ensure_ascii=False,separators=(',',':'))
|
||||
(dest/(level['id']+'.js')).write_text('window.PuzzleAtlas.register('+payload+');\n')
|
||||
index['levels'].append({'id':level['id'],'name':level['name'],'province':level['province'],'provinceName':entry['provinceName'],'sha256':entry['sha256'],'regions':proof})
|
||||
catalog.append({'id':level['id'],'name':level['name'],'province':level['province'],'provinceName':entry['provinceName'],'kind':'county','playLabel':'县区拼图','count':len(level['regions']),'path':'./county/'+level['id']+'.js'})
|
||||
total+=len(payload.encode())
|
||||
(ROOT/'src/county-index.js').write_text('window.COUNTY_INDEX='+json.dumps({'levels':catalog,'unavailable':index['unavailable']},ensure_ascii=False,separators=(',',':'))+';\n')
|
||||
(ROOT/'research/county-map-index.json').write_text(json.dumps(index,ensure_ascii=False,separators=(',',':'))+'\n')
|
||||
print('County assets:',len(catalog),'levels;',sum(v['count'] for v in catalog),'pieces;',total,'bytes; source polygon repairs:',repairs)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Add a small, explicitly scoped set of detailed puzzles from local map inputs.
|
||||
|
||||
Run after prepare-maps.py. Raw downloads stay in ignored data/, while the
|
||||
compact source index is required by the build-time geographic audit.
|
||||
"""
|
||||
import copy, hashlib, json, pathlib, subprocess
|
||||
from map_geometry import make_level, place_labels
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
source=ROOT/'src/maps.js'
|
||||
data=json.loads(source.read_text().removeprefix('window.MAP_DATA=').strip().removesuffix(';'))
|
||||
# Preserve the national and 27 provincial levels, including province-administered peers.
|
||||
data['levels']=[lv for lv in data['levels'] if lv.get('kind') not in ('county','partition','county-city')]
|
||||
for lv in data['levels']:
|
||||
lv['kind']='province' if lv['id']=='100000' else 'prefecture'
|
||||
index={'downloadDate':'2026-10-17','levels':[]}
|
||||
expected={'110000':('北京市',16),'120000':('天津市',16),'310000':('上海市',16),'500000':('重庆市',38),'810000':('香港特别行政区',18),'820000':('澳门特别行政区',8)}
|
||||
for code,(name,count) in expected.items():
|
||||
raw=ROOT/'data/provinces-raw'/(code+'.json')
|
||||
features=json.loads(raw.read_text())['features']
|
||||
features=[f for f in features if f['properties'].get('level')=='district']
|
||||
assert len(features)==count,(code,len(features))
|
||||
lv=make_level(features,code,name,code)
|
||||
assert lv and len(lv['regions'])==count
|
||||
lv.pop('projection',None);lv['kind']='partition' if code in ('810000','820000') else 'county'
|
||||
lv['playLabel']='分区拼图' if lv['kind']=='partition' else '县区拼图'
|
||||
lv['unitCaption']='按素材分区 · 堂区及路凼填海区' if code=='820000' else '18个分区' if code=='810000' else '区 · 县 · 自治县' if code=='500000' else '市辖区'
|
||||
lv['source']='DataV.GeoAtlas';place_labels(lv);data['levels'].append(lv)
|
||||
index['levels'].append({'id':code,'name':name,'kind':lv['kind'],'source':'DataV.GeoAtlas','sha256':hashlib.sha256(raw.read_bytes()).hexdigest(),'regions':[{'id':str(f['properties']['adcode']),'name':f['properties']['name'],'rings':len(f['geometry']['coordinates']) if f['geometry']['type']=='MultiPolygon' else 1,'holes':sum(len(poly)-1 for poly in f['geometry']['coordinates']) if f['geometry']['type']=='MultiPolygon' else len(f['geometry']['coordinates'])-1} for f in features]})
|
||||
# An explicitly attributed county/city source is separate from the national map.
|
||||
taiwan=ROOT/'data/taiwan-raw/counties.geojson'
|
||||
if not taiwan.exists():raise SystemExit('缺少台湾县市构建输入,请先运行 scripts/prepare-taiwan.py')
|
||||
features=json.loads(taiwan.read_text())['features']
|
||||
assert len(features)==20
|
||||
play_features=copy.deepcopy(features)
|
||||
# Keep every source exterior ring. Two remote island clusters are translated
|
||||
# into a labelled inset area so one county does not span thousands of km.
|
||||
insets=0
|
||||
for f in play_features:
|
||||
for poly in f['geometry']['coordinates']:
|
||||
ring=poly[0];cx=sum(p[0] for p in ring)/len(ring);cy=sum(p[1] for p in ring)/len(ring)
|
||||
if cy<21 or cx<118:
|
||||
target=(118.95,21.7) if cy<15 else (119.35,21.7)
|
||||
dx,dy=target[0]-cx,target[1]-cy
|
||||
for p in ring:p[0]+=dx;p[1]+=dy
|
||||
insets+=1
|
||||
assert insets>0
|
||||
lv=make_level(play_features,'710000','台湾省','710000');lv.pop('projection',None)
|
||||
lv.update(kind='county-city',playLabel='县市拼图',unitCaption='县市 · 远海岛屿移位示意',source='NLSC',scopeNote='县市关卡包括台湾岛及澎湖;远海岛屿采用移位示意。金门、连江属福建,不重复列入。')
|
||||
place_labels(lv);data['levels'].append(lv)
|
||||
index['levels'].append({'id':'710000','name':'台湾省','kind':'county-city','source':'NLSC','snapshot':'COUNTY_MOI_1090820','translatedOffshoreRings':insets,'sourceURL':'https://data.gov.tw/dataset/7442','license':'政府资料开放授权条款第1版','sha256':hashlib.sha256(taiwan.read_bytes()).hexdigest(),'regions':[{'id':str(f['properties']['adcode']),'name':f['properties']['name'],'rings':len(f['geometry']['coordinates']),'holes':sum(len(poly)-1 for poly in f['geometry']['coordinates'])} for f in features]})
|
||||
assert len(data['levels'])==35
|
||||
source.write_text('window.MAP_DATA='+json.dumps(data,ensure_ascii=False,separators=(',',':'))+';\n')
|
||||
subprocess.run(['node',str(ROOT/'scripts/triangulate-holes.mjs')],check=True,cwd=ROOT)
|
||||
(ROOT/'research/detail-map-index.json').write_text(json.dumps(index,ensure_ascii=False,indent=2)+'\n')
|
||||
print('Detailed levels:',[(lv['name'],lv['playLabel'],len(lv['regions'])) for lv in data['levels'] if lv['kind'] not in ('province','prefecture')])
|
||||
+34
-80
@@ -1,65 +1,7 @@
|
||||
import json, math, pathlib, collections
|
||||
import json, math, pathlib, collections, subprocess, hashlib
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
AREAS=json.load(open(ROOT/'research/areas.json'));LOOKUP={a['adcode']:a for a in AREAS}
|
||||
def area(r):return abs(sum(r[i][0]*r[(i+1)%len(r)][1]-r[(i+1)%len(r)][0]*r[i][1] for i in range(len(r)))/2)
|
||||
def dist(p,a,b):
|
||||
dx,dy=b[0]-a[0],b[1]-a[1];n=dx*dx+dy*dy
|
||||
t=max(0,min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/n)) if n else 0
|
||||
return (p[0]-a[0]-t*dx)**2+(p[1]-a[1]-t*dy)**2
|
||||
def dp(p,eps):
|
||||
if len(p)<3:return p
|
||||
v,i=max((dist(p[k],p[0],p[-1]),k) for k in range(1,len(p)-1))
|
||||
if v<=eps*eps:return [p[0],p[-1]]
|
||||
return dp(p[:i+1],eps)[:-1]+dp(p[i:],eps)
|
||||
def project(p):return [p[0]*.82,-math.log(math.tan(math.pi/4+math.radians(p[1])/2))*180/math.pi*.82]
|
||||
def make_level(features,code,name,province):
|
||||
fs=[f for f in features if f.get('properties',{}).get('name') and f['properties'].get('adcode')]
|
||||
if len(fs)<2:return None
|
||||
reg=[];boundary=[]
|
||||
for f in fs:
|
||||
prop=f['properties'];g=f['geometry'];polys=g['coordinates'] if g['type']=='MultiPolygon' else [g['coordinates']]
|
||||
rings=[project_ring(p[0]) for p in polys if len(p[0])>=4]
|
||||
rings.sort(key=area,reverse=True)
|
||||
if not rings:continue
|
||||
main=rings[0];boundary.append({(round(x,3),round(y,3)) for r in rings for x,y in r})
|
||||
# Keep island geometry, simplify each independently; no invented boundaries.
|
||||
span=max(max(p[0] for p in main)-min(p[0] for p in main),max(p[1] for p in main)-min(p[1] for p in main))
|
||||
simple=[]
|
||||
for r in rings:
|
||||
localspan=max(max(p[0] for p in r)-min(p[0] for p in r),max(p[1] for p in r)-min(p[1] for p in r))
|
||||
eps=max(min(span*.005,localspan*.01),.00000001);q=dp(r,eps)
|
||||
while len(q)>90:eps*=1.4;q=dp(r,eps)
|
||||
if len(q)<4:q=r
|
||||
simple.append(q[:-1] if q[0]==q[-1] else q)
|
||||
cx=sum(x for x,y in main[:-1])/max(1,len(main)-1);cy=sum(y for x,y in main[:-1])/max(1,len(main)-1)
|
||||
reg.append({'id':str(prop['adcode']),'name':prop['name'],'rings':simple,'center':[cx,cy]})
|
||||
if len(reg)<2:return None
|
||||
edges=[]
|
||||
for i in range(len(reg)):
|
||||
for j in range(i):
|
||||
if len(boundary[i]&boundary[j])>=2:edges.append([j,i,0])
|
||||
# Join disconnected island components with explicit game-only sea routes.
|
||||
def components():
|
||||
groups=[{i} for i in range(len(reg))]
|
||||
for a,b,_ in edges:
|
||||
ga=next(g for g in groups if a in g);gb=next(g for g in groups if b in g)
|
||||
if ga is not gb:ga.update(gb);groups.remove(gb)
|
||||
return groups
|
||||
while len(components())>1:
|
||||
gs=components();candidates=[]
|
||||
for a in gs[0]:
|
||||
for g in gs[1:]:
|
||||
for b in g:
|
||||
pa,pb=reg[a]['center'],reg[b]['center'];candidates.append(((pa[0]-pb[0])**2+(pa[1]-pb[1])**2,a,b))
|
||||
_,a,b=min(candidates);edges.append([a,b,1])
|
||||
allp=[p for r in reg for ring in r['rings'] for p in ring]
|
||||
minx,miny=min(p[0] for p in allp),min(p[1] for p in allp);maxx,maxy=max(p[0] for p in allp),max(p[1] for p in allp)
|
||||
span=max(maxx-minx,maxy-miny);scale=1000/span
|
||||
for r in reg:
|
||||
r['center']=[round((r['center'][0]-minx)*scale,2),round((r['center'][1]-miny)*scale,2)]
|
||||
r['rings']=[[[round((x-minx)*scale,4),round((y-miny)*scale,4)] for x,y in ring] for ring in r['rings']]
|
||||
return {'id':str(code),'name':name,'province':str(province),'width':round((maxx-minx)*scale,2),'height':round((maxy-miny)*scale,2),'regions':reg,'edges':edges,'projection':[minx,miny,scale]}
|
||||
def project_ring(r):return [project(p) for p in r]
|
||||
from map_geometry import make_level, project, place_labels, hainan_offshore_inset
|
||||
levels=[]
|
||||
cn=json.load(open(ROOT/'research/china.json'));nation=make_level(cn['features'],100000,'中国 · 省级拼图',100000);levels.append(nation)
|
||||
for p in sorted((ROOT/'data/raw').glob('*.json')):
|
||||
@@ -78,35 +20,45 @@ result={'source':'DataV.GeoAtlas','downloadDate':'2026-10-16','provinces':provin
|
||||
summary={'levels':len(levels),'countyLevels':len(levels)-1,'provincePieces':len(nation['regions']),'countyPieces':sum(len(l['regions']) for l in levels[1:]),'availableProvinces':len({l['province'] for l in levels[1:]}),'seaRoutes':sum(e[2] for l in levels for e in l['edges'])}
|
||||
(ROOT/'data/county-materials/summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2));print(summary)
|
||||
|
||||
# Formal release: only province and prefecture-level units, no county pieces.
|
||||
# Formal release: prefectures plus province-administered peers, so the province has no filtered-out gaps.
|
||||
citylevels=[nation]
|
||||
excluded=[]
|
||||
direct_summary=[]
|
||||
prefecture_index={'downloadDate':'2026-10-16','source':'DataV.GeoAtlas','levels':[]}
|
||||
for p in sorted((ROOT/'data/provinces-raw').glob('*.json')):
|
||||
code=int(p.stem);info=LOOKUP.get(code)
|
||||
if not info:continue
|
||||
fs=json.load(open(p)).get('features',[])
|
||||
cityfs=[f for f in fs if f.get('properties',{}).get('level')=='city' and int(f['properties'].get('adcode',0))%100==0]
|
||||
excluded.extend(f['properties']['name'] for f in fs if f not in cityfs)
|
||||
# These are the province endpoint's immediate children, not every county
|
||||
# nested inside a prefecture. District-only municipalities are added separately.
|
||||
children=[f for f in fs if f.get('properties',{}).get('level') in ('city','district') and f['properties'].get('parent',{}).get('adcode')==code]
|
||||
prefectures=[f for f in children if int(f['properties']['adcode'])%100==0]
|
||||
if not prefectures:continue
|
||||
cityfs=children
|
||||
assert len(cityfs)==len(fs),(code,'unclassified province children')
|
||||
direct=[f for f in cityfs if f not in prefectures]
|
||||
lv=make_level(cityfs,code,info['name'],code)
|
||||
if lv:
|
||||
# Missing county-only zones may disconnect prefectures: these are not land neighbors.
|
||||
lv['kind']='prefecture'
|
||||
direct_ids={str(f['properties']['adcode']) for f in direct}
|
||||
for r in lv['regions']:r['unitType']='province-direct' if r['id'] in direct_ids else 'prefecture'
|
||||
if direct:
|
||||
lv['playLabel']='省域拼图'
|
||||
lv['unitCaption']='地级行政区 · 省直辖地区'
|
||||
lv['scopeNote']='含'+str(len(direct))+'个省直辖县级地区,拼完整片省域。'
|
||||
lv['directRegionCount']=len(direct)
|
||||
direct_summary.append({'province':str(code),'names':[f['properties']['name'] for f in direct]})
|
||||
entries=[]
|
||||
for f in cityfs:
|
||||
prop=f['properties'];geometry=f['geometry'];polys=geometry['coordinates'] if geometry['type']=='MultiPolygon' else [geometry['coordinates']]
|
||||
entries.append({'id':str(prop['adcode']),'name':prop['name'],'unitType':'province-direct' if str(prop['adcode']) in direct_ids else 'prefecture','rings':len(polys),'holes':sum(len(poly)-1 for poly in polys)})
|
||||
prefecture_index['levels'].append({'id':str(code),'name':info['name'],'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'regions':entries})
|
||||
# Disconnected islands retain explicit game-only routes.
|
||||
for edge in lv['edges']:
|
||||
if edge[2]:edge[2]=2
|
||||
citylevels.append(lv)
|
||||
def inside(p,ring):
|
||||
x,y=p;hit=False
|
||||
for i,a in enumerate(ring):
|
||||
b=ring[(i+1)%len(ring)]
|
||||
if (a[1]>y)!=(b[1]>y) and x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0]:hit=not hit
|
||||
return hit
|
||||
for lv in citylevels:
|
||||
for r in lv['regions']:
|
||||
ring=r['rings'][0];minx,maxx=min(p[0] for p in ring),max(p[0] for p in ring);miny,maxy=min(p[1] for p in ring),max(p[1] for p in ring)
|
||||
candidates=[[minx+(maxx-minx)*i/14,miny+(maxy-miny)*j/14] for i in range(1,14) for j in range(1,14)]
|
||||
candidates=[p for p in candidates if inside(p,ring)]
|
||||
if candidates:r['label']=max(candidates,key=lambda p:min(dist(p,ring[k],ring[(k+1)%len(ring)]) for k in range(len(ring))))
|
||||
else:r['label']=r['center']
|
||||
r['label']=[round(v,3) for v in r['label']]
|
||||
hainan_offshore_inset(lv)
|
||||
place_labels(lv)
|
||||
# Preserve the source's unnamed maritime boundary features as a separate layer.
|
||||
minx,miny,scale=nation['projection'];decorations=[]
|
||||
for feature in cn['features']:
|
||||
@@ -117,5 +69,7 @@ nation['decorations']=decorations
|
||||
for lv in citylevels:lv.pop('projection',None)
|
||||
result={'source':'DataV.GeoAtlas','downloadDate':'2026-10-16','provinces':provinces,'levels':citylevels}
|
||||
(ROOT/'src/maps.js').write_text('window.MAP_DATA='+json.dumps(result,ensure_ascii=False,separators=(',',':'))+';\n')
|
||||
summary={'levels':len(citylevels),'prefectureLevels':len(citylevels)-1,'provincePieces':len(nation['regions']),'prefecturePieces':sum(len(l['regions']) for l in citylevels[1:]),'availableProvinces':len(citylevels)-1,'excludedCountyUnits':excluded,'countyMaterials':{'levels':len(levels)-1,'pieces':sum(len(l['regions']) for l in levels[1:]),'path':'data/county-materials/maps.js'}}
|
||||
(ROOT/'data/map-summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2));print('Release:',{k:v for k,v in summary.items() if k!='excludedCountyUnits'})
|
||||
subprocess.run(['node',str(ROOT/'scripts/triangulate-holes.mjs')],check=True,cwd=ROOT)
|
||||
summary={'levels':len(citylevels),'prefectureLevels':len(citylevels)-1,'provincePieces':len(nation['regions']),'prefecturePieces':sum(len(l['regions']) for l in citylevels[1:]),'availableProvinces':len(citylevels)-1,'provinceDirectPieces':sum(len(v['names']) for v in direct_summary),'provinceDirectUnits':direct_summary,'countyMaterials':{'levels':len(levels)-1,'pieces':sum(len(l['regions']) for l in levels[1:]),'path':'data/county-materials/maps.js'}}
|
||||
(ROOT/'research/prefecture-map-index.json').write_text(json.dumps(prefecture_index,ensure_ascii=False,indent=2)+'\n')
|
||||
(ROOT/'data/map-summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2));print('Release:',{k:v for k,v in summary.items() if k!='provinceDirectUnits'})
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Convert the official NLSC county SHP ZIP to a build-only GeoJSON input.
|
||||
|
||||
Download https://maps.nlsc.gov.tw/pro/download.jsp's county EPSG:3824 ZIP
|
||||
into data/taiwan-raw/counties.zip first. Only Python's standard library is used.
|
||||
"""
|
||||
import json, pathlib, struct, zipfile
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
folder=ROOT/'data/taiwan-raw'
|
||||
with zipfile.ZipFile(folder/'counties.zip') as z:
|
||||
names=z.namelist();dbf=z.read(next(n for n in names if n.lower().endswith('.dbf')))
|
||||
shp=z.read(next(n for n in names if n.lower().endswith('.shp')))
|
||||
prj=z.read(next(n for n in names if n.lower().endswith('.prj'))).decode()
|
||||
assert 'GEOGCS' in prj and 'TWD_1997' in prj and 'Degree' in prj
|
||||
count,header,size=struct.unpack_from('<IHH',dbf,4);fields=[];offset=32
|
||||
while dbf[offset]!=13:
|
||||
d=dbf[offset:offset+32];fields.append((d[:11].split(b'\0')[0].decode(),d[16]));offset+=32
|
||||
rows=[]
|
||||
for i in range(count):
|
||||
row=dbf[header+i*size:header+(i+1)*size];assert row[0]==32;pos=1;prop={}
|
||||
for name,length in fields:prop[name]=row[pos:pos+length].decode('utf-8').strip();pos+=length
|
||||
rows.append(prop)
|
||||
assert count==22 and struct.unpack_from('<i',shp,32)[0]==5
|
||||
geometries=[];offset=100
|
||||
while offset<len(shp):
|
||||
_,words=struct.unpack_from('>ii',shp,offset);part=shp[offset+8:offset+8+words*2];offset+=8+words*2
|
||||
assert struct.unpack_from('<i',part)[0]==5
|
||||
parts,points=struct.unpack_from('<ii',part,36);starts=list(struct.unpack_from('<'+'i'*parts,part,44))+[points];base=44+parts*4
|
||||
coords=[list(struct.unpack_from('<dd',part,base+i*16)) for i in range(points)]
|
||||
rings=[coords[starts[i]:starts[i+1]] for i in range(parts)]
|
||||
def signed(r):return sum(a[0]*b[1]-b[0]*a[1] for a,b in zip(r,r[1:]))/2
|
||||
# SHP exterior rings are clockwise. Inner holes are not individual pieces.
|
||||
outers=[r for r in rings if signed(r)<0]
|
||||
assert outers and all(114<x<125 and 9<y<27 for r in outers for x,y in r)
|
||||
def inside(p,r):
|
||||
x,y=p;hit=False
|
||||
for a,b in zip(r,r[1:]):
|
||||
if (a[1]>y)!=(b[1]>y) and x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0]:hit=not hit
|
||||
return hit
|
||||
polys=[[r] for r in outers]
|
||||
for hole in [r for r in rings if signed(r)>0]:
|
||||
owners=[poly for poly in polys if inside(hole[0],poly[0])];assert len(owners)==1;owners[0].append(hole)
|
||||
geometries.append({'type':'MultiPolygon','coordinates':polys})
|
||||
assert len(geometries)==len(rows)
|
||||
trans=str.maketrans({'臺':'台','縣':'县','蘭':'兰','雲':'云','義':'义','園':'园','東':'东','蓮':'莲'})
|
||||
features=[]
|
||||
for prop,g in zip(rows,geometries):
|
||||
# These two counties belong to Fujian, not Taiwan Province.
|
||||
if prop['COUNTYCODE'] in ('09007','09020'):continue
|
||||
features.append({'type':'Feature','properties':{'adcode':'TW-'+prop['COUNTYCODE'],'sourceCode':prop['COUNTYCODE'],'name':prop['COUNTYNAME'].translate(trans),'level':'county-city'},'geometry':g})
|
||||
assert len(features)==20
|
||||
result={'type':'FeatureCollection','source':'NLSC','sourceURL':'https://data.gov.tw/dataset/7442','snapshot':'COUNTY_MOI_1090820','license':'政府資料開放授權條款第1版','features':features}
|
||||
(folder/'counties.geojson').write_text(json.dumps(result,ensure_ascii=False,separators=(',',':')))
|
||||
print('台湾县市输入:',len(features),'块;外环',sum(len(f['geometry']['coordinates']) for f in features))
|
||||
@@ -0,0 +1,15 @@
|
||||
// Deterministic Node diagnostic, not a mobile FPS / native acceptance test.
|
||||
const fs=require('node:fs'),vm=require('node:vm'),path=require('node:path'),Module=require('node:module'),{performance}=require('node:perf_hooks'),M=require('matter-js');
|
||||
const args=process.argv.slice(2),source=args[0]||'src/game.js';
|
||||
const mod=new Module(path.resolve('src/profile-game.cjs'));mod.filename=path.resolve('src/profile-game.cjs');mod.paths=module.paths;mod._compile(fs.readFileSync(source,'utf8'),mod.filename);const {Game}=mod.exports;
|
||||
const box={window:{}};vm.runInNewContext(fs.readFileSync('src/maps.js','utf8'),box);const maps=box.window.MAP_DATA.levels;
|
||||
let county;vm.runInNewContext(fs.readFileSync('src/county/140500.js','utf8'),{window:{PuzzleAtlas:{register(l){county=l;}}}});
|
||||
const methods=['uprightOnce','guardPenetrations','tryMerges','attractNearby','updateSupport','stepGrowth','limitMotion','pose','pocketPlan','snapPlan'];
|
||||
function run(level,upright,shake){let seed=74;const rng=()=>{seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;};const g=new Game(level,440,680,4,()=>{},rng,1,2),cost={},calls={},ticks=[],collisions={count:0},transforms={count:0};let measuring=false;
|
||||
for(const key of methods){const f=g[key];g[key]=function(...args){if(!measuring)return f.apply(this,args);calls[key]=(calls[key]||0)+1;const start=performance.now();try{return f.apply(this,args);}finally{cost[key]=(cost[key]||0)+performance.now()-start;}};}
|
||||
const collide=M.Collision.collides,angle=M.Body.setAngle;M.Collision.collides=function(...args){if(measuring)collisions.count++;return collide.apply(this,args);};M.Body.setAngle=function(...args){if(measuring)transforms.count++;return angle.apply(this,args);};g.start();let awake=0,samples=0;
|
||||
try{for(let i=0;i<2400&&g.status==='playing';i++){if(g.pending&&i%35===0){const serial=g.pending.serial;g.movePending(35+rng()*370,serial);g.holdPending(serial);g.releasePending(serial);}if(i===1200)upright&&g.uprightOnce();if(shake&&i>=1200&&i%40===0)g.swipe({x:220,y:560},{x:i%80?100:-100,y:-30},65);measuring=i>=1800;const start=performance.now();g.tick(1000/60);if(measuring){ticks.push(performance.now()-start);awake+=g.groups.filter(p=>!p.body.isSleeping).length;samples+=g.groups.length;}}}finally{M.Collision.collides=collide;M.Body.setAngle=angle;}
|
||||
ticks.sort((a,b)=>a-b);const result={id:level.id,upright,shake,status:g.status,groups:g.groups.length,dropped:g.dropped,parts:g.groups.reduce((n,p)=>n+p.body.parts.length,0),sampleTicks:ticks.length,meanMs:ticks.reduce((n,t)=>n+t,0)/ticks.length,p95Ms:ticks[Math.floor(ticks.length*.95)],awakeRatio:awake/samples,collisionCalls:collisions.count,angleGeometryTransforms:transforms.count,costMs:cost,calls};g.destroy();return result;
|
||||
}
|
||||
const out=[];for(const level of [maps[0],maps.find(l=>l.id==='420000'),county])for(const shake of [false,true])for(const upright of [false,true])out.push(run(level,upright,shake));
|
||||
const report={scope:'Node physics only; upright means one button press at tick 1200, not a mode; method times are inclusive and instrumentation adds overhead; no rendering/video or native FPS claim',source,cases:out};if(args[1])fs.writeFileSync(args[1],JSON.stringify(report,null,2)+'\n');else console.log(JSON.stringify(report,null,2));
|
||||
@@ -0,0 +1,2 @@
|
||||
# Only needed to regenerate src/county assets; not needed by npm run build.
|
||||
shapely==2.1.2
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
const root=path.resolve(process.env.PREVIEW_DIR||'src');
|
||||
const root=path.resolve(process.env.PREVIEW_DIR||'dist');
|
||||
if(!fs.existsSync(path.join(root,'index.html')))throw Error('请先运行 npm run build,再启动预览。');
|
||||
const mime={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.json':'application/json'};
|
||||
http.createServer((req,res)=>{let p;try{p=decodeURIComponent(new URL(req.url,'http://localhost').pathname);}catch{res.writeHead(400).end();return;}const file=path.resolve(root,'.'+(p==='/'?'/index.html':p));if(!file.startsWith(root+path.sep)){res.writeHead(403).end();return;}fs.readFile(file,(err,b)=>{if(err){res.writeHead(404).end('Not found');return;}res.writeHead(200,{'Content-Type':mime[path.extname(file)]||'application/octet-stream','Cache-Control':'no-store'});res.end(b);});}).listen(4173,'127.0.0.1',()=>console.log('山河拼图预览:http://localhost:4173'));
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Preparation only: static hole-aware convex parts and robust decomposition fallback.
|
||||
import fs from 'node:fs';import earcut from 'earcut';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import M from 'matter-js';import gameModule from '../src/game.js';
|
||||
function inside([x,y],ring){let hit=false;for(let i=0,j=ring.length-1;i<ring.length;j=i++){const a=ring[i],b=ring[j];if((a[1]>y)!==(b[1]>y)&&x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0])hit=!hit;}return hit;}
|
||||
function triangulate(region){region.physics=[];let assigned=0;for(const outer of region.rings){const holes=(region.holes||[]).filter(h=>inside(h[0],outer));assigned+=holes.length;const flat=earcut.flatten([outer,...holes]),indices=earcut(flat.vertices,flat.holes,2);assert.ok(earcut.deviation(flat.vertices,flat.holes,2,indices)<1e-8);for(let i=0;i<indices.length;i+=3)region.physics.push(indices.slice(i,i+3).map(j=>[flat.vertices[j*2],flat.vertices[j*2+1]]));}assert.equal(assigned,(region.holes||[]).length);}
|
||||
let regions=0,parts=0,fallbacks=0;const index=JSON.parse(fs.readFileSync('research/county-map-index.json','utf8'));
|
||||
for(const name of fs.readdirSync('src/county').filter(n=>n.endsWith('.js'))){const path='src/county/'+name,level=JSON.parse(fs.readFileSync(path,'utf8').replace(/^window\.PuzzleAtlas\.register\(/,'').replace(/\);\s*$/,''));
|
||||
for(const region of level.regions)if(region.holes&®ion.holes.length){regions++;triangulate(region);parts+=region.physics.length;}
|
||||
// Exercise the exact game's decomposition at common viewport scales. A valid
|
||||
// but awkward outline must not leave missing physical parts after max-depth.
|
||||
const fallback=new Set();for(const [w,h] of [[320,568],[340,560],[440,680]]){const game=new gameModule.Game(level,w,h,4);for(let id=0;id<level.regions.length;id++){let warned=false;const previous=console.warn;console.warn=(...args)=>{if(String(args[0]).includes('quickDecomp'))warned=true;else previous(...args);};let group;try{group=game.createGroup([id],{tx:0,ty:0,angle:0});}finally{console.warn=previous;}if(warned)fallback.add(id);M.Composite.remove(game.engine.world,group.body);game.groups=[];}game.destroy();}
|
||||
for(const id of fallback){triangulate(level.regions[id]);fallbacks++;}
|
||||
const encoded='window.PuzzleAtlas.register('+JSON.stringify(level)+');\n';fs.writeFileSync(path,encoded);const entry=index.levels.find(l=>l.id===level.id);entry.assetSha256=createHash('sha256').update(encoded).digest('hex');entry.collisionFallbacks=Array.from(fallback,id=>level.regions[id].id);
|
||||
}
|
||||
fs.writeFileSync('research/county-map-index.json',JSON.stringify(index)+'\n');console.log('County physics:',regions,'hole regions,',parts,'hole parts;',fallbacks,'static decomposition fallbacks');
|
||||
@@ -0,0 +1,10 @@
|
||||
// Build-only triangulation: the game consumes static convex polygons, no library.
|
||||
import earcut from 'earcut';import fs from 'node:fs';import assert from 'node:assert/strict';
|
||||
const filename='src/maps.js',data=JSON.parse(fs.readFileSync(filename,'utf8').replace(/^window\.MAP_DATA=/,'').replace(/;\s*$/,''));
|
||||
function inside([x,y],ring){let hit=false;for(let i=0,j=ring.length-1;i<ring.length;j=i++){const a=ring[i],b=ring[j];if((a[1]>y)!==(b[1]>y)&&x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0])hit=!hit;}return hit;}
|
||||
let count=0;
|
||||
for(const lv of data.levels)for(const region of lv.regions){if(!region.holes||!region.holes.length)continue;region.physics=[];let assigned=0;
|
||||
for(const outer of region.rings){const holes=region.holes.filter(h=>inside(h[0],outer));assigned+=holes.length;if(!holes.length){region.physics.push(outer);continue;}const flat=earcut.flatten([outer,...holes]),indices=earcut(flat.vertices,flat.holes,2);assert.ok(earcut.deviation(flat.vertices,flat.holes,2,indices)<1e-8);
|
||||
for(let i=0;i<indices.length;i+=3)region.physics.push(indices.slice(i,i+3).map(j=>[flat.vertices[j*2],flat.vertices[j*2+1]]));
|
||||
}assert.equal(assigned,region.holes.length);count++;}
|
||||
fs.writeFileSync(filename,'window.MAP_DATA='+JSON.stringify(data)+';\n');console.log('保留内嵌县市的环形碰撞区域:'+count+'块');
|
||||
Reference in New Issue
Block a user