Author SHA1 Message Date
que01 7f4ebe8fb7 Improve Cesium preview loading state 2026-07-31 18:11:21 +08:00
que01 0def373c09 Extract Cesium preview assets 2026-07-31 16:56:22 +08:00
que01 41a07a78ef Add scrub edge bushes 2026-07-31 16:53:28 +08:00
que01andClaude Opus 5 eb4a0d9b2a fix: 树发黑的真正原因是反照率没提亮,并加饱和度让远看更绿
emissive 提到 0.8 仍然发黑:它乘的是本来就很暗的反照率,0.8 × 深绿约等于
sRGB [0.22, 0.31, 0.11],还是暗的。要提的是反照率本身。

Cesium 截图定位:草亮黄绿、建筑近白、路面浅灰,只有树暗。这棵树图集的叶片
本来就是深绿(绿色系像素均值 sRGB [0.249, 0.35, 0.12]),按真实反照率渲染
是对的,但场景里其他材质都被手工提亮过——EXPORT_TINTS 草 0.72、带肋墙面
0.86,EXPORT_EMISSION_OVERRIDES 建筑 0.18,全是针对 Cesium 偏白的默认光照
调出来的。新资产没调过,是唯一如实渲染的东西,放旁边就显得发黑。

- FOLIAGE_ALBEDO_GAIN = 2.1,在抠图植被 dilate 那一遍顺带乘上。用增益而非
  tint:其他材质是单一表面,而这是同时装着叶片/树皮/果实的图集,往绿色混会
  把树干染绿。缩放保留色相关系,只把整体抬到和邻居一样的曝光。
- FOLIAGE_SATURATION = 1.75,绕各像素自身 Rec.709 亮度做饱和度拉伸。图集本
  来就偏灰(平均饱和度 0.22),远看时 mip 把叶片、树皮、缝隙混在一起会更往
  中性靠。绕亮度拉伸把叶片推绿而基本不动本来中性的部分,也没有绿色 tint 强
  加给树干的色相偏移。叶片 sRGB → [0.262, 0.529, 0.021],饱和度 0.22 → 0.34,
  过曝到纯白的像素占 0.3%。
- FOLIAGE_EMISSION 回调 0.25,它只负责给背光面兜底。
- 新增 triangulate_mesh():export_tangents 打开后刷了 55 行「切向空间只能只算
  三角/四边形」,MeshBatch 建的 OSM 轮廓都是 n-gon。glTF 只有三角形,导出时
  无论如何都会三角化,提前做不改变任何输出三角形(三角数 51719 前后一致),
  切线 49/102 → 102/102,警告归零。

被数据排除的假设:贴图颜色全链路逐位一致;模拟 mip 链可见像素亮度
0.127→0.124;法线贴图抠图区是干净平面法线;GLB 重新导入 Blender 渲染正常。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 13:23:44 +08:00
que01andClaude Opus 5 afada31469 fix: 树在 Cesium 远看发黑 — 补 emissive 并导出切线
黑色色块修掉后仍存在:近看正常,远看整棵树是暗色块。逐项排除:

- 贴图颜色全链路无偏移,源 4k / 降采样 2k / GLB 内 PNG 的 opaque 均值
  都是 sRGB [0.409, 0.406, 0.362],不是 gamma 问题。
- 模拟 GPU mip 链,可见像素亮度 mip0→mip6 只从 0.127 变到 0.124,
  覆盖率稳定 0.42,不是 mipmap 变暗。
- 法线贴图抠图区域是干净的平面法线 [0.494, 0.512, 0.988],无黑像素。

真实原因是缺 emissive 补偿。预览页 skyBox / skyAtmosphere / sun 全部关闭
且未配置环境贴图,Cesium 只剩很弱的默认球谐环境光,太阳直射不到的面接近
全黑——这正是 EXPORT_EMISSION_OVERRIDES 存在的原因(建筑 0.18,程序化树冠
0.015~0.02)。树冠绝大部分是背光叶片卡片,远看塌成一团暗色,近看能看到
向阳面所以还行。apple 材质不在那张表里。

- 抠图植被把 diffuse 接回 Emission Color,FOLIAGE_EMISSION = 0.22。
  用带贴图的自发光而非平坦颜色:常量会把树干染成叶子绿,而这样每个像素
  下限是自身反照率的一个比例。不增加字节,emissiveTexture 指向 base color
  已在用的同一张图。
- 打开 export_tangents:apple 有法线贴图但图元无 TANGENT,缺失时切线由
  渲染器推导,在双面薄片叶子卡上不可靠。49/102 图元带上切线,顺带修正
  建筑法线贴图,GLB +0.83MB。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 12:00:06 +08:00
que01andClaude Opus 5 2139990818 feat: 树渲染改用 apple/fattree 模型,修复 Cesium alpha 抠图丢失
tree_style 新增 apple(SpeedTree Red Delicious,4475 tris,alpha 抠图叶片
+ 法线贴图)和 fattree(低面数卡通树,2238 tris,实体几何)。

高度改为按模型自身包围盒归一化到目标高度,树根落在 z=0,不再用魔数;
每棵树按序号做确定性抖动(缩放 ±14%、黄金角偏航、±3° 倾斜),
tree_row 采样高度全部相同,不抖动就是同一棵树盖章 156 次。

移除 polyhaven 样式和 island_tree_01 资产(76MB)+ ingest_tree.py:
该样式 append 的 *_LOD1 并不是完整的树,枝干只有 0.41 单位高,叶片是
挂在原点下方的平面簇,本是给源文件几何节点散布用的碎片。

Cesium 侧修三处:

- make_export_material 把 Alpha 恒定写死为 1.0,叶片卡片整块导出,而
  SpeedTree 图集抠掉的区域是纯黑,在 Cesium 里就是黑色色块。
- Blender 4.2 起 glTF 导出不再读 blend_method(仍可写但已失效,写 CLIP
  读回来是 HASHED),改为从节点树推断 alpha 模式,alpha 直连 BSDF 会落到
  BLEND。新增 materials.link_alpha_clip() 构造导出器识别的
  1 - (alpha < cutoff) 结构,得到 alphaMode=MASK。
- 新增 alpha_dilated_image():把不透明像素颜色向抠图区域外扩 8 圈,
  避免 mipmap 把黑色平均进叶缘。叶缘相邻的纯黑像素 10.3% → 0.6%。

另修两个既有 bug:

- 材质槽在 mesh 上,181 棵树共享一个 datablock,第一棵替换后其余会把结果
  再包一层,产生 Cesium Cesium Cesium... 的材质名;烘焙图缓存按材质名索引,
  每轮再嵌一份同样的贴图。GLB 22.46MB → 20.76MB,materials 270 → 23。
- shrub_02 从 glTF 带进来一个 Math 节点接在 Alpha 上,但其 JPEG 贴图 alpha
  全是 1.0,只判断「连了 Alpha」会误判为抠图材质。

模型资产为第三方素材,已 gitignore,缺失时回落到 natural;
来源见 assets/models/SOURCES.md。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 11:30:16 +08:00
que01andClaude Opus 4.8 b35b094ed2 docs: changelog 更新 — P0-P3 refactor + island_tree_01
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:22:04 +08:00
que01andClaude Opus 4.8 365b158878 docs: tree.py + ingest_tree.py 补充文档注释
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:20:40 +08:00
que01andClaude Opus 4.8 3c6c21ff2f config: nantaizi 默认 treeStyle 切换为 polyhaven
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:17:16 +08:00
que01andClaude Opus 4.8 243f0c8ced fix: load_tree_variants() 缺少 return variants 语句
函数在构建 variants 列表后删除了 imported objects 但忘记 return。
Python 隐式返回 None,导致 tree.assemble() 永远进入 'not variants'
分支(但 assemble 里也没有检查 None,只是 silently return 0)。

结果:tree 构建静默失败,场景里一棵树都没有。

181 棵树现在正确出现在 SCENE_DONE 和 GLB 里 (362 objects, 113k tris)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:17:07 +08:00
que01andClaude Opus 4.8 e8aecc7143 refactor: tree.assemble() 接管树构建,_add_polyhaven_trees 移除
把 polyhaven 树的实例化逻辑从 generate_scene.py 移到
osmassets/tree.py::assemble(),与 water/grass/scrub 的要素
注册表模式对齐。

generate_scene.py 现在只有一个 _assemble_building 残留(因为需要
make_prism / add_roof / add_wall_panel 这些 mesh 构建函数)。
后续 P2c 会把 building 也搬出去。

parity: control-1 vs p2b-unify = PARITY OK (两区域)
smoke: tree_style=polyhaven SCENE_DONE (181棵树, exit 0)
tests: 42/42 OK

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:05:14 +08:00
que01andClaude Opus 4.8 9ddf951186 chore: grass.py 参数名 add_grass_tufts_fn → add_grass_tufts (更 Pythonic)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 09:01:30 +08:00
que01andClaude Opus 4.8 b2136e708d chore: gitignore island_tree_01 模型资产(55MB + 20MB 贴图)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 08:57:35 +08:00
que01andClaude Opus 4.8 a621ef743b feat: 接入 Poly Haven island_tree_01 真实扫描树模型
tree_style 新增 'polyhaven' 选项,用 wm.append 从 vendored .blend
加载 LOD1 网格(4 种 branch+leaf 组合),通过实例化放置场景中的树。

每棵树约 625 tris / 2 meshes (branch+leaf),比旧 procedural tree
(~400 tris) 多了约 60%,但换来真实树形和 PBR 贴图,树叶有 alpha
透明度,在 Cesium 远距离比纯几何球体更可读。

纹理从 ~/Downloads 手动下载(Poly Haven CDN 的 API URL 不可用),
存放在 assets/models/polyhaven/island_tree_01/textures/(不入 git)。

默认 tree_style 仍为 'natural',parity 保持不变。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 08:57:24 +08:00
que01andClaude Opus 4.8 24e02e2041 refactor: 抽 osmassets 包,要素注册表,材质单一定义源 (P0-P3)
generate_scene.py 从 1271 → 816 行 (-455)

P0: 纯函数搬家
- osmassets/osm.py: parse_osm / Projector / parse_height
- osmassets/geom.py: clip_polygon / point_in_polygon / distance_to_ring / sample_tree_row 等
- blender/tests/test_pure.py: 42 个 unittest (脱离 bpy 运行)

P1: 单一定义源
- osmassets/catalog.py: ROAD_LAYERS + MATERIALS (含 cesium 导出参数)
- 对接 osm2streets_scene_style.json 做图层一致性 warning
- 干掉 road_mats / layer_z / 材质参数三份副本

P2: 要素注册表
- osmassets/{water,grass,scrub}.py: 每个要素一个 assemble() 函数
- build() 中的 if/elif 链收缩为注册表调用
- 计数器集中到 counts 字典

P3: 材质契约化
- catalog.py 扩展 CESIUM_EXPORT 段 (tint/metallic/emission)
- 标记已发现的死条目 Office White Metal Facade (四表各一组)

校验:
- parity.js + scene_digest.py + glb-digest.js 三位一体
- control-1 vs p0/p1/p2a/p2b/p3-counts: 两区域全 PARITY OK
- 42 个纯 Python 测试全部通过

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 17:59:32 +08:00
que01 23ae63bc2a feat: 草坪新增一些草 2026-07-29 14:46:29 +08:00
que01andClaude Opus 5 59628cba82 feat: add reimport stage for hand-edited GeoPackages
QGIS 手工修正后的回导流程此前是 README 里的三段 shell:一个硬编码
area-id 和 ogr2ogr 绝对路径的 for 循环、一段内联 node heredoc、再加一次
npm run build。改为一个 reimport 阶段:

  npm run build -- --config config/areas/<area-id>.json \
    --stages reimport,blender,cesium

scripts/reimport-gpkg.js 先把全部图层导出到临时目录并逐个校验,全部通过
才写回 osm2streets_web_out/。ogr2ogr 对不存在的图层退出码非 0 但仍会留下
0 字节文件,原先逐图层 mv 会静默用空图层覆盖好数据。

intermediates 与 reimport 同时指定直接报错——前者用 OSM 重建 GeoPackage,
正好抹掉后者要读回的手工修改。reimport 不含在 all 中。

同时新增 scripts/lib/scene-layers.js 作为 9 个渲染图层的唯一定义源。此前
该表在合并场景、场景样式 JSON、生成的 QGIS 工程、README 手工流程中各有
一份副本,改一处漏其余会导致图层叠放顺序出错并流入 Blender/Cesium。

验证:同一 OSM 输入下,改动前后 intermediates 产物逐字节一致
(scene_style.json、.qgz 符号定义、9 个图层几何与属性);reimport 对
未修改图层无损回导。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 17:21:59 +08:00
que01 2b18d0eb2b fix: synthesize T-junction sidewalk caps 2026-07-28 10:20:47 +08:00
que01 03ebb7c0ed fix: backfill missing sidewalk corners 2026-07-28 10:00:57 +08:00
que01 96c9baf540 feat: osm2streets上游箭头修复 2026-07-28 09:08:58 +08:00
que01 694f18826a Add multi-vehicle cruise selection preview 2026-07-27 15:55:29 +08:00
que01 4fc9397cec Fix cruise vehicle model orientation 2026-07-27 15:07:48 +08:00
que01 633f1ee364 Restore lightweight cruise car and keep lane offset 2026-07-27 14:53:40 +08:00
que01 d93212b685 Use clean ToyCar model and lane-offset cruise route 2026-07-27 14:31:56 +08:00
que01 9561ad8530 Use lightweight glTF car for cruise preview 2026-07-27 14:19:06 +08:00
que01 513ef62ab8 Allow zoom adjustment in vehicle follow mode 2026-07-27 14:12:09 +08:00
que01 235314af1a Replace tracked vehicle follow with chase camera 2026-07-27 14:06:46 +08:00
que01 d872ca6f32 Make vehicle following opt-in 2026-07-27 14:00:49 +08:00
que01 f1ddedf889 Add experimental Cesium vehicle cruise preview 2026-07-27 13:52:43 +08:00
que01 633c39e5e1 Remove Nantaizi building render overrides 2026-07-27 13:41:02 +08:00
que01 5919684888 Treat mislabeled Nantaizi buildings as offices 2026-07-27 13:28:55 +08:00
que01 a5c3ad3cf3 Generate Cesium preview pages from area builds 2026-07-27 13:06:57 +08:00
que01 61e4820a4c Refactor pipeline around area asset builds 2026-07-27 12:56:13 +08:00
que01 59a22ea697 Use lightweight natural tree rendering 2026-07-27 12:36:55 +08:00
que01 cf69c99d20 通用化项目结构:Blender 脚本去硬编码、config 路径占位符、layerPrefix 配置
- blender/generate_nantaizi.py → blender/generate_scene.py(去硬编码路径,
  --geojson 改为可选,--office-overrides 替代硬编码 way ID)
- blender/export_cesium.py CLI 参数改为必传,修复隐藏物体导出崩溃
- blender/README.md 重写为中文通用文档
- config/default.json 路径改为占位符,template.json 新增 blender 配置块
- scripts/build-osm2streets-qgis.js 新增 layerPrefix 配置驱动 QGIS 图层名
- package.json name → osm-gis-pipeline
- README.md 重写并增加实际运行示例
2026-07-24 17:09:43 +08:00
que01 fb2a36ac7e 成果暂存 2026-07-24 16:03:15 +08:00
que01 662f8d908b Add crosswalk and intersection surface rendering 2026-07-21 17:39:07 +08:00
que01 dc22543e9a Initial osm2streets QGIS workflow 2026-07-21 17:03:27 +08:00
83 changed files with 8845 additions and 15457 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.DS_Store
node_modules/
outputs/
__pycache__/
assets/models/speedtree/
assets/models/lyrog/
+204
View File
@@ -0,0 +1,204 @@
# OSM Asset Pipeline
把单个园区/片区 OSM XML 转为可消费的 Blender 场景和 Cesium GLB。osm2streets GeoJSON、GeoPackage、QGIS 工程和预览图都是中间资产,用来提供道路几何、调试标线效果,以及给 Blender/Cesium 生成提供输入。
## 目标产物
每个区域默认输出到 `outputs/<area-id>/`:
- `<area-id>.blend`:Blender 场景,包含道路、建筑、水体、植被等
- `<area-id>.png`:Blender 预览渲染
- `<area-id>.glb`:Cesium 可加载的 3D 模型
- `<area-id>.json`:Cesium 放置元数据和示例代码
- `<area-id>-cesium-preview.html`:Cesium 本地预览页
- `osm2streets_web_out/`:osm2streets GeoJSON 中间层
- `<area-id>.gpkg` / `<area-id>.qgz` / `<area-id>-preview.png`:QGIS 调试资产
## 环境
需要:
- macOS QGIS:默认 `/Applications/QGIS.app`
- Blender:默认 `/Applications/Blender.app`
- Node.js / npm
首次使用:
```bash
cd /Users/que01/osm2streets-qgis-workflow
npm install
```
## 主流程
默认构建南台子湖创新谷样例:
```bash
npm run build
```
指定区域配置:
```bash
npm run build:area -- --config config/areas/hanyang-block.json
```
只跑部分阶段:
```bash
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages intermediates
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages blender
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages cesium
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages preview
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages reimport
```
`intermediates` 会生成 osm2streets GeoJSON、GeoPackage、QGIS 工程和 QGIS 预览图。`blender` 使用 OSM 和 osm2streets GeoJSON 生成 `.blend`/`.png`。`cesium` 从 `.blend` 导出 `.glb`/`.json`,并生成 Cesium 预览 HTML。`preview` 只在已有 `.glb/.json` 时补生成 HTML。`reimport` 把手工编辑过的 GeoPackage 回导为 GeoJSON,不含在 `all` 里,详见 [QGIS 手工修正工作流](#qgis-手工修正工作流)。
## 区域配置
新区域从模板复制:
```bash
cp config/examples/template.json config/areas/my-area.json
```
核心配置:
```json
{
"id": "my-area",
"input": "/absolute/path/to/input.osm",
"outputRoot": "/absolute/path/to/outputs",
"qgisApp": "/Applications/QGIS.app",
"blenderApp": "/Applications/Blender.app",
"stages": {
"intermediates": true,
"blender": true,
"cesium": true
},
"qgis": {
"arrowScale": 0.8,
"arrowMergeTriangles": true,
"arrowOutlineSimplifyMeters": 0.05,
"intersectionCornerSourceMaxDimensionMeters": 2.6,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"layerPrefix": "osm2streets"
},
"blender": {
"treeStyle": "natural",
"officeOverrides": ""
}
}
```
QGIS road-layer knobs:
- `arrowScale`: scales osm2streets lane-arrow polygons before export.
- `arrowMergeTriangles`: merges each osm2streets lane-arrow triangle mesh into one valid polygon. This preserves the original arrow shape and turn direction while removing renderer gaps along shared triangle edges.
- `arrowOutlineSimplifyMeters`: removes sub-decimeter kinks from the merged arrow exterior. The default `0.05` removes the two malformed tail vertices without changing the arrow head; the remaining tail edge is aligned perpendicular to the shaft.
- `intersectionCornerSourceMaxDimensionMeters`: keeps only small osm2streets `sidewalk corner` polygons. Large intersection-marking polygons are not treated as sidewalk because they can cover the drivable junction.
`scripts/build-area.js` 会按 `id` 自动推导默认输出路径。确实需要定制时,可以增加 `outputs` 覆盖:
```json
{
"outputs": {
"areaDir": "/absolute/path/to/custom-area",
"blend": "/absolute/path/to/custom.blend",
"glb": "/absolute/path/to/custom.glb",
"cesiumPreview": "/absolute/path/to/custom-preview.html"
}
}
```
预览 Cesium 页面时,需要在输出目录启动 HTTP 服务,避免浏览器拦截本地文件请求:
```bash
cd outputs/my-area
python3 -m http.server 8765
```
然后打开 `http://localhost:8765/my-area-cesium-preview.html`。
## 实验:车辆巡航
`preview` 和 `cesium` 阶段会额外生成 `<area-id>-vehicle-route.json` 和 `<area-id>-vehicle-car.gltf`。路线文件从 OSM bounds 内的可行驶 `highway` way 提取道路中心线,并向右偏移约 1.3 米作为车辆行驶线,避免车辆压道路中心线。Cesium 预览页会加载多条道路段并显示多辆实验车辆循环巡航;`Vehicle` 下拉框决定 `Follow` 跟随哪一辆车。
这是用于验证高精度巡航可用性的预览层功能,不会改变 Blender/GLB 主资产本身。车辆模型是无 logo 的轻量预览模型,生成在输出目录中。
## 已沉淀区域
- `config/areas/nantaizi-lake-innovation-valley.json`
- `config/areas/hanyang-block.json`
## 低层命令
通常优先使用 `npm run build:area`。如果只想调试旧 QGIS/osm2streets 阶段,可以直接运行:
```bash
npm run build:qgis -- --config config/hanyang-block.json
```
Blender 低层命令:
```bash
/Applications/Blender.app/Contents/MacOS/Blender \
--background --factory-startup \
--python blender/generate_scene.py -- \
--osm "/path/to/input.osm" \
--geojson "/path/to/osm2streets_web_out" \
--output "/path/to/scene.blend" \
--render "/path/to/preview.png" \
--tree-style natural
```
Cesium GLB 低层导出:
```bash
/Applications/Blender.app/Contents/MacOS/Blender \
--background \
--python blender/export_cesium.py -- \
--blend "/path/to/scene.blend" \
--glb "/path/to/scene.glb" \
--metadata "/path/to/scene.json"
```
详见 [blender/README.md](blender/README.md)。
## QGIS 手工修正工作流
如果已经在现成的 `.qgz` 项目里直接编辑了 `gpkg` 图层,不要再重跑 `intermediates`,否则会把手工修改覆盖掉。推荐流程是:
1. 在 QGIS 中打开 `outputs/<area-id>/<area-id>.qgz`
2. 直接编辑项目内关联的 `gpkg` 图层并保存
3. 跑 `reimport` 回导 GeoJSON 并重建场景,再接 `blender,cesium`
南台子湖创新谷当前可直接使用下面这条命令:
```bash
npm run build -- --config config/areas/nantaizi-lake-innovation-valley.json --stages reimport,blender,cesium
```
`reimport` 阶段(`scripts/reimport-gpkg.js`)做两件事:
- 把 `<area-id>.gpkg` 里的 9 个图层逐个导出到 `osm2streets_web_out/<layer>.geojson`
- 按 `scripts/lib/scene-layers.js` 的图层表重建 `osm2streets_scene.geojson`(写入 `render_layer` / `z_index`)和 `osm2streets_scene_style.json`
说明:
- 这套流程假设你的手工修改已经保存在 `outputs/<area-id>/<area-id>.gpkg` 中
- 所有图层先导出到临时目录并校验通过后才写回 `osm2streets_web_out/`;任一图层缺失或导出结果不是合法 FeatureCollection,整批都不落盘(`ogr2ogr` 遇到不存在的图层会留下 0 字节文件,直接覆盖会静默损坏数据)
- `intermediates` 与 `reimport` 互斥,同时指定会直接报错:前者用 OSM 重建 `gpkg`,正好会抹掉后者要读回的手工修改
- `blender,cesium` 阶段读取的是 `osm2streets_web_out/*.geojson`,不是直接读取 `gpkg`
- 如果 Blender 当前环境不稳定,先确认 `geojson` 已完成回导,再单独排查 Blender 本身
- 增删图层或调整 `z_index` 只需改 `scripts/lib/scene-layers.js`,构建、场景合并、场景样式、QGIS 工程会一并同步
## 文档
- [docs/input-cases.md](docs/input-cases.md) - 已验证的 OSM 输入案例
- [docs/changelog.md](docs/changelog.md) - 变更记录
+47
View File
@@ -0,0 +1,47 @@
# 树模型资产来源
`assets/models/` 下的树模型是第三方素材,**已 gitignore**,不随仓库分发。
干净 checkout 缺这些文件时 `tree.assemble()` 返回 0,`generate_scene.py`
自动回落到 `natural` 样式,构建不会失败。
放置路径见 `blender/osmassets/tree.py` 顶部的常量。
## apple(`--tree-style apple`)
- 名称:RedDeliciousApple(SpeedTree 工具导出)
- 路径:`assets/models/speedtree/apple_low/`
- `RedDeliciousApple.obj` — 4475 tris,单网格
- `RedDeliciousApple.mtl` — 已重写,见文件内注释
- `textures/apple_color_2k.png` — 由原始 4096² PNG 降采样,**必须保留 alpha 通道**,
57% 的像素是抠掉的叶片卡片
- `textures/apple_normal_2k.png` — 同上降采样
原始素材另有 `.fbx` / `.cgf` / `.st` / `.tif` 以及 `_SS` / `_Subsurface` 贴图,
管线不用,未收录。
降采样命令(原始 4k 贴图 16MB + 20MB,降到 2k 后 4.3MB + 4.7MB):
```bash
sips -Z 2048 -s format png <原始>_Color.png --out textures/apple_color_2k.png
sips -Z 2048 -s format png <原始>_Normal.png --out textures/apple_normal_2k.png
```
## fattree(`--tree-style fattree`)
- 名称:fat tree,作者署名 Lyrog(付费素材)
- 路径:`assets/models/lyrog/fattree/`
- `fattree.blend` — 取其中名为 `fattree` 的对象,2238 tris
- `textures/fat_tree.png` — 原文件名带空格(`fat tree.png`),已改为下划线
源 .blend 里的贴图路径是 `//fat tree.png`,只在原始目录下能解析;
运行时不依赖它,`tree.py` 会丢掉源材质并按上面的路径重建一个 Principled 材质。
该 .blend 里另有两个 `plant` 对象(灌木),管线未使用。
## 已移除
`polyhaven/island_tree_01`(76MB)已于 2026-07-31 删除,连同 `--tree-style polyhaven`
和 `blender/tools/ingest_tree.py`。原因见 `docs/changelog.md`:该文件的 `*_LOD1`
对象不是完整的树,而是给几何节点散布用的枝叶碎片。
若要重新取用,Poly Haven 上是 CC0:https://polyhaven.com/a/island_tree_01
`polyhaven/shrub_02` 仍在使用(草丛散布),不受影响。
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,437 @@
{
"asset": {
"generator": "Khronos glTF Blender I/O v3.5.30",
"version": "2.0"
},
"scene": 0,
"scenes": [
{
"name": "Scene",
"nodes": [
0,
1,
2,
3
]
}
],
"nodes": [
{
"mesh": 0,
"name": "shrub_02_a",
"rotation": [
0.12589912116527557,
-0.6947680711746216,
0.006097283214330673,
0.708102822303772
],
"translation": [
-1.5478131771087646,
-0.005240630358457565,
-0.02073405683040619
]
},
{
"mesh": 1,
"name": "shrub_02_b",
"rotation": [
0.08358937501907349,
-0.746630847454071,
0.26227879524230957,
0.6056113243103027
],
"translation": [
0.0007123738760128617,
-0.006340932101011276,
-0.01680799387395382
]
},
{
"mesh": 2,
"name": "shrub_02_c",
"rotation": [
0.12648986279964447,
-0.7129753232002258,
0.3943961560726166,
0.5657898783683777
],
"translation": [
1.5559492111206055,
-0.005484403111040592,
-0.006101916544139385
]
},
{
"mesh": 3,
"name": "shrub_02_d",
"rotation": [
0.047377295792102814,
-0.7383221983909607,
-0.300414502620697,
0.60198575258255
],
"translation": [
3.258664131164551,
-0.004767145495861769,
-0.005447957664728165
]
}
],
"materials": [
{
"alphaCutoff": 0.5,
"alphaMode": "MASK",
"doubleSided": true,
"name": "shrub_02",
"normalTexture": {
"index": 0
},
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": 1
},
"metallicFactor": 0,
"metallicRoughnessTexture": {
"index": 2
}
}
}
],
"meshes": [
{
"name": "Plane.024",
"primitives": [
{
"attributes": {
"POSITION": 0,
"TEXCOORD_0": 1,
"NORMAL": 2
},
"indices": 3,
"material": 0
}
]
},
{
"name": "Plane.029",
"primitives": [
{
"attributes": {
"POSITION": 4,
"TEXCOORD_0": 5,
"NORMAL": 6
},
"indices": 7,
"material": 0
}
]
},
{
"name": "Plane.041",
"primitives": [
{
"attributes": {
"POSITION": 8,
"TEXCOORD_0": 9,
"NORMAL": 10
},
"indices": 11,
"material": 0
}
]
},
{
"name": "Plane.036",
"primitives": [
{
"attributes": {
"POSITION": 12,
"TEXCOORD_0": 13,
"NORMAL": 14
},
"indices": 15,
"material": 0
}
]
}
],
"textures": [
{
"sampler": 0,
"source": 0
},
{
"sampler": 0,
"source": 1
},
{
"sampler": 0,
"source": 2
}
],
"images": [
{
"mimeType": "image/jpeg",
"name": "shrub_02_nor_gl",
"uri": "textures/shrub_02_nor_gl_1k.jpg"
},
{
"mimeType": "image/jpeg",
"name": "shrub_02_diff",
"uri": "textures/shrub_02_diff_1k.jpg"
},
{
"mimeType": "image/jpeg",
"name": "shrub_02_rough",
"uri": "textures/shrub_02_arm_1k.jpg"
}
],
"accessors": [
{
"bufferView": 0,
"componentType": 5126,
"count": 5125,
"max": [
0.6156559586524963,
1.6821810007095337,
0.42684367299079895
],
"min": [
-0.9439988136291504,
-0.03012576885521412,
-0.863244354724884
],
"type": "VEC3"
},
{
"bufferView": 1,
"componentType": 5126,
"count": 5125,
"type": "VEC2"
},
{
"bufferView": 2,
"componentType": 5126,
"count": 5125,
"type": "VEC3"
},
{
"bufferView": 3,
"componentType": 5123,
"count": 22770,
"type": "SCALAR"
},
{
"bufferView": 4,
"componentType": 5126,
"count": 3600,
"max": [
0.9647624492645264,
1.0844767093658447,
0.30848613381385803
],
"min": [
-0.4038015305995941,
-0.10226154327392578,
-1.0773800611495972
],
"type": "VEC3"
},
{
"bufferView": 5,
"componentType": 5126,
"count": 3600,
"type": "VEC2"
},
{
"bufferView": 6,
"componentType": 5126,
"count": 3600,
"type": "VEC3"
},
{
"bufferView": 7,
"componentType": 5123,
"count": 15726,
"type": "SCALAR"
},
{
"bufferView": 8,
"componentType": 5126,
"count": 6346,
"max": [
1.287977695465088,
0.8719967007637024,
0.24143657088279724
],
"min": [
-0.8910231590270996,
-0.2947101294994354,
-1.22649085521698
],
"type": "VEC3"
},
{
"bufferView": 9,
"componentType": 5126,
"count": 6346,
"type": "VEC2"
},
{
"bufferView": 10,
"componentType": 5126,
"count": 6346,
"type": "VEC3"
},
{
"bufferView": 11,
"componentType": 5123,
"count": 27702,
"type": "SCALAR"
},
{
"bufferView": 12,
"componentType": 5126,
"count": 3528,
"max": [
0.22877177596092224,
1.153072476387024,
0.5660104751586914
],
"min": [
-1.051486849784851,
-0.09016040712594986,
-0.41910019516944885
],
"type": "VEC3"
},
{
"bufferView": 13,
"componentType": 5126,
"count": 3528,
"type": "VEC2"
},
{
"bufferView": 14,
"componentType": 5126,
"count": 3528,
"type": "VEC3"
},
{
"bufferView": 15,
"componentType": 5123,
"count": 15564,
"type": "SCALAR"
}
],
"bufferViews": [
{
"buffer": 0,
"byteLength": 61500,
"byteOffset": 0,
"target": 34962
},
{
"buffer": 0,
"byteLength": 41000,
"byteOffset": 61500,
"target": 34962
},
{
"buffer": 0,
"byteLength": 61500,
"byteOffset": 102500,
"target": 34962
},
{
"buffer": 0,
"byteLength": 45540,
"byteOffset": 164000,
"target": 34963
},
{
"buffer": 0,
"byteLength": 43200,
"byteOffset": 209540,
"target": 34962
},
{
"buffer": 0,
"byteLength": 28800,
"byteOffset": 252740,
"target": 34962
},
{
"buffer": 0,
"byteLength": 43200,
"byteOffset": 281540,
"target": 34962
},
{
"buffer": 0,
"byteLength": 31452,
"byteOffset": 324740,
"target": 34963
},
{
"buffer": 0,
"byteLength": 76152,
"byteOffset": 356192,
"target": 34962
},
{
"buffer": 0,
"byteLength": 50768,
"byteOffset": 432344,
"target": 34962
},
{
"buffer": 0,
"byteLength": 76152,
"byteOffset": 483112,
"target": 34962
},
{
"buffer": 0,
"byteLength": 55404,
"byteOffset": 559264,
"target": 34963
},
{
"buffer": 0,
"byteLength": 42336,
"byteOffset": 614668,
"target": 34962
},
{
"buffer": 0,
"byteLength": 28224,
"byteOffset": 657004,
"target": 34962
},
{
"buffer": 0,
"byteLength": 42336,
"byteOffset": 685228,
"target": 34962
},
{
"buffer": 0,
"byteLength": 31128,
"byteOffset": 727564,
"target": 34963
}
],
"samplers": [
{
"magFilter": 9729,
"minFilter": 9987
}
],
"buffers": [
{
"byteLength": 758692,
"uri": "shrub_02.bin"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 KiB

+22
View File
@@ -0,0 +1,22 @@
# Poly Haven CC0 textures
All files in this directory are from Poly Haven and are released under the
Poly Haven CC0 license. The license page is archived as `polyhaven-license.html`.
License: https://polyhaven.com/license
Assets:
- `concrete_floor_02`: https://polyhaven.com/a/concrete_floor_02
- `factory_wall`: https://polyhaven.com/a/factory_wall
- `corrugated_iron`: https://polyhaven.com/a/corrugated_iron
- `box_profile_metal_sheet`: https://polyhaven.com/a/box_profile_metal_sheet
- `corrugated_iron_03`: https://polyhaven.com/a/corrugated_iron_03
- `blue_metal_plate`: https://polyhaven.com/a/blue_metal_plate
- `leafy_grass`: https://polyhaven.com/a/leafy_grass
- `bark_brown_01`: https://polyhaven.com/a/bark_brown_01
- `white_plaster_02`: https://polyhaven.com/a/white_plaster_02
- `shrub_02`: https://polyhaven.com/a/shrub_02
Only the 1K diffuse and normal/bump maps needed by the Blender scene were
downloaded. They may be used commercially under the CC0 terms above.
Binary file not shown.

After

Width:  |  Height:  |  Size: 713 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 538 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 713 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 512 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 703 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 737 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

@@ -0,0 +1,77 @@
<!DOCTYPE html><html dir="ltr" lang="en"><head><meta charSet="utf-8"/><title>License • Poly Haven</title><meta name="description" content="CC0 means absolute freedom."/><meta name="keywords" content="Arch-viz,Game,Unreal,Unity,Blender,Maya,Max,free,cc0,creative commons"/><meta name="author" content="Poly Haven"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="rgb(234, 91, 12)"/><link rel="canonical" href="https://polyhaven.com/license"/><meta property="og:locale" content="en_US"/><meta property="og:type" content="website"/><meta property="og:title" content="License • Poly Haven"/><meta property="og:description" content="CC0 means absolute freedom."/><meta property="og:url" content="https://polyhaven.com/license"/><meta property="og:site_name" content="Poly Haven"/><meta property="twitter:card" content="summary_large_image"/><meta property="twitter:site" content="@polyhaven"/><meta name="next-head-count" content="16"/><link rel="icon" href="/favicon.ico"/><link rel="preconnect" href="https://fonts.gstatic.com"/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css"/><meta property="og:locale" content="en_US"/><meta property="og:type" content="website"/><meta property="og:site_name" content="Poly Haven"/><meta content="text/html;charset=utf-8" http-equiv="Content-Type"/><meta content="utf-8" http-equiv="encoding"/><meta name="theme-color" content="rgb(190, 111, 255)"/><meta property="commit_hash" content="7a7cf2e974f9e0af6224f3b3a906acba39c3081a"/><script src="/download-js/ua-parser.min.js"></script><script src="/download-js/zip.js"></script><script src="/download-js/download.js"></script><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link rel="preload" href="/_next/static/css/b31836ee847ea5ae.css" as="style"/><link rel="stylesheet" href="/_next/static/css/b31836ee847ea5ae.css" data-n-g=""/><link rel="preload" href="/_next/static/css/fa85ed313335bd4d.css" as="style"/><link rel="stylesheet" href="/_next/static/css/fa85ed313335bd4d.css" data-n-p=""/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-42372ed130431b0a.js"></script><script src="/_next/static/chunks/webpack-05a2a2a7b8359dfa.js" defer=""></script><script src="/_next/static/chunks/framework-b0ec748c7a4c483a.js" defer=""></script><script src="/_next/static/chunks/main-8663fe5437afb3c3.js" defer=""></script><script src="/_next/static/chunks/pages/_app-05967a333d7fcb8a.js" defer=""></script><script src="/_next/static/chunks/d9067523-78bffb2ceaf8b441.js" defer=""></script><script src="/_next/static/chunks/283-4596fa5c32c00036.js" defer=""></script><script src="/_next/static/chunks/4161-5cf5bf0b7cbcaac1.js" defer=""></script><script src="/_next/static/chunks/pages/license-70d72ab0240308d4.js" defer=""></script><script src="/_next/static/7a7cf2e974f9e0af6224f3b3a906acba39c3081a/_buildManifest.js" defer=""></script><script src="/_next/static/7a7cf2e974f9e0af6224f3b3a906acba39c3081a/_ssgManifest.js" defer=""></script><style data-href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap">@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:normal;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsjZ0C4k.woff) format('woff')}@font-face{font-family:'Open Sans';font-style:normal;font-weight:700;font-stretch:normal;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsg-1y4k.woff) format('woff')}@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:100%;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTSKmu0SC55K5gw.woff2) format('woff2');unicode-range:U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:100%;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTSumu0SC55K5gw.woff2) format('woff2');unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:100%;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTSOmu0SC55K5gw.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:100%;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTSymu0SC55K5gw.woff2) format('woff2');unicode-range:U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF}@font-face{font-family:'Open Sans';font-style:normal;font-weight:400;font-stretch:100%;font-display:swap;src:url(https://fonts.gstatic.com/s/opensans/v44/memvYaGs126MiZpBLine truncated
M9.84864 13.7904l-0.77047 -0.983574 -0.611784 -0.369057 -0.299479 0.888721 -0.593611 -0.476716 -0.396605 -1.48277 -0.305443 -0.302311 -0.305423 -0.0986227 -0.280049 0.41404 -0.330877 0.0263113 -0.386871 0.18408 -0.80472 0.260042 -0.468278 0.210411 -1.08926 -0.131537 -0.427684 -0.473285 -0.610846 0.341808 -0.0101735 0.801948 -0.914753 -0.821716 -0.447851 0.473325 -0.368259 1.15036 -0.32571 0.289345 -0.100498 0.0992012 2.80849 0 0.171872 -0.0551162 0.18414 -0.239316 0.570472 0.0123079 0.533747 -0.104288 0.582919 -0.294571 -0.067464 0.15346 -0.515455 0.196268 -0.251524 0.110472 -0.711723 0.00614397 -0.134888 0.0183721 -0.0368638 0.159504 0.0336721 0.0367641 4.57373 0 0.0381804 -0.200776 0.24542 -0.00430876 0.180788 -0.159245 -0.116177 0.215179 -0.21093 0.0861353 -0.00524631 0.0630156 1.97549 0zm-7.18116 -0.539812l-0.411048 -0.196248 -0.165668 -0.0368439 -0.177896 0.147156 -0.282303 0.165628 -0.134968 0.177996 -0.239276 0.233152 0.21472 -0.0920199 0.239316 0 0.300596 -0.141132 -0.3681 0.0552359 0.0736279 -0.171712 0.251504 -0.165748 0.190224 -0.073588 0.509271 0.098124zm4.14752 -0.920319l-0.251544 0.355852 -0.233192 0.171832 -0.429459 0.055176 -0.116596 0.239336 -0.441727 0.380328 0.423335 -0.15338 0.39878 -0.165648 -0.0674839 -0.116476 0.128884 -0.104368c0.0000199,0 0.0190503,0 0.0244761,0l0.245499 -0.104268 0.269796 -0.21474 0.0492315 -0.343643z
M3.44389 6.59599l-0.142688 -0.101635 0 -0.427006 0.175682 -0.108277 0.459042 -0.0321362 0.0439054 -1.0358 0.131696 -0.0338317 0 -0.663489 -0.153759 -0.0676635 0 -0.0947927 0.153759 -0.0745255c0.0719523,-0.232773 0.255114,-0.418867 0.541627,-0.531074l0.0292038 -0.186434 0.131896 -0.0339115 0.131856 0.0339115 0.0292636 0.186434c0.286512,0.112207 0.469675,0.298302 0.541627,0.531074l0.153679 0.0745255 0 0.0947927 -0.153679 0.0676635 0 0.663489 0.131637 0.0338317 0.0439653 1.0358 0.459042 0.0321362 0.175682 0.108277 0 0.427006 -0.151265 0.107699c-0.453696,-0.0555351 -0.907532,-0.0869332 -1.36131,-0.0896461 -0.456748,-0.00271292 -0.913876,0.0235585 -1.37086,0.0835819zm-0.2145 2.62066l0.22615 -2.37253c0.452619,-0.0604622 0.905537,-0.0869531 1.35822,-0.0842402 0.452998,0.00271292 0.906395,0.0346895 1.35995,0.0911621l0.225911 2.37018c-0.528202,-0.073588 -1.05664,-0.115778 -1.58486,-0.11883 -0.528202,-0.00307198 -1.05692,0.0326149 -1.58536,0.114262zm3.4786 3.24112l-3.78746 0 0.284657 -2.98671c0.536141,-0.0866539 1.0725,-0.124415 1.60856,-0.121204 0.536281,0.00313183 1.07314,0.0473963 1.61,0.124615l0.284238 2.9833zm-1.89731 -8.54534c0.305523,0 0.553217,0.247694 0.553217,0.553217 0,0.305503 -0.247694,0.553197 -0.553217,0.553197 -0.305503,0 -0.553197,-0.247694 -0.553197,-0.553197 0,-0.305523 0.247694,-0.553217 0.553197,-0.553217z"></path></svg> Project Lighthouse</span></a></div></div></div><div class="Nav_navItemWrapper__qSXyS "><a class="Nav_navItem__4T1Pr" href="/account?returnTo=/license"><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 512 512" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M256 48c-42.9 0-84.2 13-119.2 37.5-34.2 24-60.2 57.2-75.1 96.1L58 192h45.7l1.9-5c8.2-17.8 19.4-33.9 33.5-48 31.2-31.2 72.7-48.4 116.9-48.4s85.7 17.2 116.9 48.4c31.2 31.2 48.4 72.7 48.4 116.9 0 44.1-17.2 85.7-48.4 116.9-31.2 31.2-72.7 48.4-116.9 48.4-44.1 0-85.6-17.2-116.9-48.4-14-14-25.3-30.1-33.5-47.9l-1.9-5H58l3.6 10.4c14.9 38.9 40.9 72.1 75.1 96.1C171.8 451.1 213 464 256 464c114.7 0 208-93.3 208-208S370.7 48 256 48z"></path><path d="M48 277.4h189.7l-43.6 44.7L224 352l96-96-96-96-31 29.9 44.7 44.7H48v42.8z"></path></svg></a></div></div><div style="height:100%;display:flex"><div class="Nav_navItemWrapper__qSXyS Nav_compactNavItemWrapper__vgkE6 Nav_navItemMenuFlag__9a1Xp "><span class="Nav_navItem__4T1Pr"><img src="https://cdn.jsdelivr.net/gh/lipis/flag-icons/flags/4x3/gb.svg" style="display:inline-block;width:inherit;height:1em;vertical-align:middle"/></span><div class="Nav_subNav__wgdgY"><hr/><div class="Nav_navItemWrapper__qSXyS "><a class="Nav_navItem__4T1Pr" href="/translate">🤝 Help Translate!</a></div></div></div></div><div class="Nav_menuToggle__DpmqE"><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0z"></path><path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"></path></svg></div></div><div class="Layout_page__S1cKp"><div id="page" class="Page_page__9l_5_ "><div class="Page_pageContent__BFys9"><div class="TextPage_page__FDgnU"><h1>Asset License</h1><p>All assets (<a href="/hdris">HDRIs</a>, <a href="/textures">textures</a> and <a href="/models">3D models</a>) on this site are the original work of Poly Haven staff, or artists who willingly and directly donate/sell their work to Poly Haven.</p><p>Our assets are all licensed as <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0</a>, which is effectively <a href="https://en.wikipedia.org/wiki/Public_domain">Public Domain</a> even in jurisdictions that do not support the Public Domain.</p><p>Here&#x27;s an excerpt from the <a href="https://wiki.creativecommons.org/wiki/CC0_FAQ">CC0 FAQ page</a> to clarify:</p><q>Once the creator or a subsequent owner of a work applies CC0 to a work, the work is no longer his or hers in any meaningful sense under copyright law. Anyone can then use the work in any way and for any purpose, including commercial purposes [...] Think of CC0 as the &quot;no rights reserved&quot; option. CC0 is a useful tool for clarifying that you do not claim copyright in a work anywhere in the world.</q><p>In other words:</p><ul><li><strong>You can use our assets for any purpose</strong>, including commercial work.</li><li><strong>You do not need to give credit</strong> or attribution when using them (although it is appreciated).</li><li><strong>You can redistribute them</strong>, share them around, include them when sharing your own work, or even in a product you sell.</li></ul><p>More info: <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0 summary</a>, <a href="https://wiki.creativecommons.org/wiki/CC0">CC0 wiki</a>, <a href="https://wiki.creativecommons.org/wiki/CC0_FAQ">CC0 FAQ</a>.</p><h1>Why CC0?</h1><p>We believe the benefits of using this license outweigh the obvious drawbacks for us as a business.</p><p>Yes it&#x27;s possible that Line truncated
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb {
color: #fff;
background: #222;
border: 1px solid transparent;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-top {
margin-top: -10px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-top::before {
border-top: 8px solid transparent;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-top::after {
border-left: 8px solid transparent;
border-right: 8px solid transparent;
bottom: -6px;
left: 50%;
margin-left: -8px;
border-top-color: #222;
border-top-style: solid;
border-top-width: 6px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-bottom {
margin-top: 10px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-bottom::before {
border-bottom: 8px solid transparent;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-bottom::after {
border-left: 8px solid transparent;
border-right: 8px solid transparent;
top: -6px;
left: 50%;
margin-left: -8px;
border-bottom-color: #222;
border-bottom-style: solid;
border-bottom-width: 6px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-left {
margin-left: -10px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-left::before {
border-left: 8px solid transparent;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-left::after {
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
right: -6px;
top: 50%;
margin-top: -4px;
border-left-color: #222;
border-left-style: solid;
border-left-width: 6px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-right {
margin-left: 10px;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-right::before {
border-right: 8px solid transparent;
}
.t48ab8e1b-e046-46f8-b3a7-80973184a6fb.place-right::after {
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
left: -6px;
top: 50%;
margin-top: -4px;
border-right-color: #222;
border-right-style: solid;
border-right-width: 6px;
}
</style></div></div><div lang="en" dir="ltr"></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"_nextI18Next":{"initialI18nStore":{"en":{"common":{"tagline":"The Public 3D Asset Library","Director":"Director","Co-founder":"Co-founder","Assets":"Assets","All Assets":"All Assets","All Things":"All {{things}}","Models":"Models","Textures":"Textures","HDRIs":"HDRIs","Graphic-Design":"Graphic Design","corporate-sponsor_one":"Corporate Sponsor","corporate-sponsor_other":"Corporate Sponsors","also-supported-by":"Also supported by:","patron_one":"Patron","patron_other":"Patrons","hidden":"Hidden","visible":"Visible","remove-ads":"Remove Ads","please-wait":"Please wait...","missing-invalid":"Missing or invalid","email-address":"Email address","invalid-email":"Invalid email address","invalid-name-url":"Invalid name or url","display-name":"Display name","required":"Required","optional":"Optional","loading":"Loading...","support-polyhaven":"Support Poly Haven!","about-project":"About the Project","browse-n":"Browse {{number}}","access-now":"Access Now","n-patrons-to-go":"{{number}} patrons to go!","goal":{"to-go":"${{dollars}} to go","current":"Current goal:","complete":"Complete!","reached":"We reached our last goal! Something new should appear here soon :)"},"roadmap":{"whats-next":"What's Next?","title":"Poly Haven Roadmap","to-be-announced":"To be announced","target-patrons":"{{target}} patrons","join-support":"\u003cpatreonLink\u003eJoin {{numPatrons}} other patrons\u003c/patreonLink\u003e, support the future of free assets."},"nav":{"home":"Home","add-on":"Add-on","plugins":"Plugins","gallery":"Gallery","support-us":"Support Us","about-contact":"About/Contact","license":"License","privacy":"Privacy","news":"News","blog":"Blog","faq":"FAQ","map":"HDRI World Map","finances":"Finance Reports","stats":"Stats","contribute":"Contribute","api":"API","source":"Source","logout":"Logout","collections":"Collections","logo":"Logo","status":"Status"},"footer":{"thanks":"Thanks to our \u003clnk\u003ePatrons\u003c/lnk\u003e for making Poly Haven possible","join-ranks":"Join the ranks, support Poly Haven on Patreon"},"donation-box":{"b1":"Help us make \u003clnk\u003efree assets\u003c/lnk\u003e for everyone!","b2":"\u003clnk\u003eEarly access\u003c/lnk\u003e to upcoming assets.","b3":"Instant access to all content in \u003clnk\u003ethe Vaults\u003c/lnk\u003e.","b4":"Our Blender asset browser \u003clnk\u003eadd-on\u003c/lnk\u003e.","b5":"Bulk download \u0026 offline access with \u003clnk\u003eour cloud\u003c/lnk\u003e.","b6":"\u003clnk\u003eSponsor an asset\u003c/lnk\u003e with your name \u0026 link.","donate-monthly":"Donate monthly","monthly":"Monthly","donate-once":"Donate once","once":"Once","one-time-benefits-p1":"One time donations do not include any Patreon benefits, or count towards Vault progress.","one-time-benefits-p2":"Consider donating monthly instead."}},"license":{"title":"Asset License","description":"CC0 means absolute freedom.","p1":"All assets (\u003clnk1\u003eHDRIs\u003c/lnk1\u003e, \u003clnk2\u003etextures\u003c/lnk2\u003e and \u003clnk3\u003e3D models\u003c/lnk3\u003e) on this site are the original work of Poly Haven staff, or artists who willingly and directly donate/sell their work to Poly Haven.","p2":"Our assets are all licensed as \u003clnk1\u003eCC0\u003c/lnk1\u003e, which is effectively \u003clnk2\u003ePublic Domain\u003c/lnk2\u003e even in jurisdictions that do not support the Public Domain.","p3":"Here's an excerpt from the \u003clnk\u003eCC0 FAQ page\u003c/lnk\u003e to clarify:","p4":"In other words:","p5l1":"\u003cb\u003eYou can use our assets for any purpose\u003c/b\u003e, including commercial work.","p5l2":"\u003cb\u003eYou do not need to give credit\u003c/b\u003e or attribution when using them (although it is appreciated).","p5l3":"\u003cb\u003eYou can redistribute them\u003c/b\u003e, share them around, include them when sharing your own work, or even in a product you sell.","p6":"More info: \u003clnk1\u003eCC0 summary\u003c/lnk1\u003e, \u003clnk2\u003eCC0 wiki\u003c/lnk2\u003e, \u003clnk3\u003eCC0 FAQ\u003c/lnk3\u003e.","p7":"Why CC0?","p8":"We believe the benefits of using this license outweigh the obvious drawbacks for us as a business.","p9":"Yes it's possible that unethical users can (and do) resell our work for their own profit, at the cost of unwitting customers who didn't know they were purchasing content they could get here for free.","p10":"But what the 3D industry as a whole gains from our work being so freely available is immeasurable","p11":"3D art is also only the tip of the iceberg, we've heard from numerous data scientists, software developers, automotive engineers and AI researchers all using our assets in their work, which simply wouldn't be possible with more restrictive (even open source) licenses.","p12":"We don't have anything against Copyright in general, we simply believe we can do more good in the world by providing as much freedom Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 515 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 637 KiB

+84
View File
@@ -0,0 +1,84 @@
# Blender 3D 场景生成
该生成器将 OSM 建筑、水体、植被标签,以及可选的 osm2streets GeoJSON 道路图层,组合为 Blender 3D 场景。
项目主入口是根目录的区域管线:
```bash
npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json --stages blender,cesium
```
下面的命令适合单独调试 Blender 脚本。
## 生成场景
```bash
/Applications/Blender.app/Contents/MacOS/Blender \
--background --factory-startup \
--python blender/generate_scene.py -- \
--osm "/path/to/input.osm" \
--geojson "/path/to/osm2streets_web_out" \
--output "/path/to/output.blend" \
--render "/path/to/preview.png" \
--tree-style natural
```
`--geojson` 为可选参数。不提供时,道路使用简单的 OSM highway 折线,而非详细 osm2streets 几何。实际资产生成建议先跑 `intermediates` 阶段,为 Blender 提供 osm2streets 道路面、标线、斑马线和箭头。
`--tree-style` 可选 `apple`、`fattree`、`natural`、`procedural`。
- `apple`(拟真)——SpeedTree Red Delicious,4.5k tris,叶片是 alpha 抠图卡片,带法线贴图。
- `fattree`(卡通)——低面数卡通树,2.2k tris,纯实体几何,无抠图。
- `natural`——低面数树干 + 多层不规则树冠,不依赖外部模型。
- `procedural`——最轻,球形树冠。
`apple` 和 `fattree` 依赖 `assets/models/` 下的第三方模型(已 gitignore)。模型缺失时自动回落到 `natural`,干净 checkout 仍可构建;实际使用的样式记录在场景的 `tree_style_used` 属性里。
使用 `--office-overrides` 指定一组 OSM way ID(逗号分隔),这些建筑将渲染为办公楼风格,即使其 OSM 标签为 `building=industrial`:
```
--office-overrides "117753521,117753535"
```
### 说明
- OSM `bounds` 元素定义场景范围(排除远处的地铁等关系成员)
- `natural=tree` 节点 → 独立树木(默认低面数自然树冠)
- `natural=tree_row` 路径 → 沿路径均匀分布的树木
- `landuse=grass` → 绿色地面
- `natural=scrub` → 低矮灌木丛
- `amenity=fountain` → 低多边形喷泉
- 建筑:`building=industrial` → 厂房风格;其他 → 办公楼风格(带窗带)
- 植被和建筑高度从 OSM `height` 标签读取
- 程序化细节(窗带、屋顶设备、树冠)不改变 OSM 体量
- 纹理使用 Poly Haven 的 1K CC0 纹理,打包在 `.blend` 内
## 导出为 Cesium GLB
```bash
/Applications/Blender.app/Contents/MacOS/Blender \
--background \
--python blender/export_cesium.py -- \
--blend "/path/to/output.blend" \
--glb "/path/to/output_cesium.glb" \
--metadata "/path/to/output_cesium.json"
```
GLB 使用以 OSM bounds 中心为原点的局部 ENU 坐标系(X 东,Y 北,Z 上)。
使用配套的 JSON 元数据文件将模型放置到 Cesium 中。
区域管线的 `cesium` 阶段还会在输出目录生成 `<area-id>-cesium-preview.html`。
导出脚本会:
- 应用网格修改器并创建 UV
- 将 Blender 特有材质转换为 glTF 兼容 PBR 材质
- 烘焙色调覆盖基础色以实现干净的 Web 渲染
- 将所有纹理图片嵌入 GLB
- 写入包含 WGS84 锚点和 Cesium JS 辅助代码的 JSON 元数据
### 预览
在输出目录上启动 HTTP 服务后打开预览页:
```bash
cd /path/to/output
python3 -m http.server 8765
```
+624
View File
@@ -0,0 +1,624 @@
"""Export a Blender scene (from generate_scene.py) as a Cesium-ready GLB.
The authoring scene intentionally uses a few Blender-only nodes (for example
the grass tint and procedural tree crown variation). glTF has a smaller
material vocabulary, so this exporter creates temporary, export-only PBR
materials, unwraps the meshes, and embeds all referenced images in the GLB.
The model remains in a local ENU frame: X east, Y north, Z up. Use the
companion JSON file to place the GLB with Cesium.Transforms.eastNorthUpToFixedFrame.
"""
import json
import os
import sys
import bpy
import numpy as np
# --factory-startup does not put the script's own directory on sys.path, so the
# osmassets package next to this file is not importable without this.
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
from osmassets.materials import link_alpha_clip # noqa: E402
# Marks a material this exporter produced, so a second pass over an instanced
# mesh's shared slots can recognise its own output and leave it alone.
EXPORT_PREFIX = "Cesium "
# Fraction of its own albedo a cut-out foliage material emits, to keep the
# shadowed side of a crown off Cesium's near-black ambient floor. Kept well
# under the 0.18 the buildings use: a tree still has to read as lit from one
# side, it just must not go to black.
FOLIAGE_EMISSION = 0.25
# Multiplier on a cut-out foliage albedo before export.
#
# This is the knob that actually controls how dark the trees read, and it
# exists because the apple atlas is genuinely dark: its green texels average
# sRGB (0.249, 0.35, 0.12), a deep forest green, and the bark is darker still.
# Rendered at true albedo that is correct — but nothing else in this scene is
# at true albedo. Every other material goes through EXPORT_TINTS (grass mixes
# 72% toward a bright green, the ribbed facade 86% toward white) and
# EXPORT_EMISSION_OVERRIDES (0.18 on the buildings), all hand-tuned against
# Cesium's washed-out default lighting. A new asset dropped in untuned is the
# one thing rendering honestly, and next to the rest it reads as black.
#
# A gain rather than a tint, because a tint is what the other materials use and
# it is wrong here: they are single-surface, this is an atlas holding leaves,
# bark and fruit at once, and mixing it toward green would turn the trunk
# green. Scaling preserves the hue relationships and just lifts the whole
# thing into the same exposure as its neighbours.
FOLIAGE_ALBEDO_GAIN = 2.1
# Saturation multiplier applied with the gain, around each texel's own
# luminance. The gain alone lifts the crown to the right brightness but leaves
# it reading grey-green at distance: this atlas is desaturated to begin with
# (mean saturation 0.22), and mip-averaging a crown mixes leaves with bark and
# sky-gaps, pulling it further toward neutral exactly when the tree gets small.
#
# Scaling the distance from luminance pushes the leaves green without touching
# what is already neutral much, and without the hue shift a green tint would
# force on the trunk — bark just becomes a warmer brown, which it should be.
FOLIAGE_SATURATION = 1.75
EXPORT_TINTS = {
"Grass": ((0.12, 0.48, 0.08), 0.72),
"Tree Crown Dark": ((0.06, 0.22, 0.05), 0.18),
"Tree Crown Light": ((0.16, 0.42, 0.09), 0.16),
"Scrub Ground Cover": ((0.08, 0.28, 0.07), 0.28),
"Office White Plaster Facade": ((0.92, 0.94, 0.92), 0.38),
"Office White Metal Facade": ((0.92, 0.94, 0.92), 0.68),
"Office Light Flat Roof": ((0.82, 0.86, 0.88), 0.35),
"Industrial White Ribbed Facade": ((0.90, 0.93, 0.91), 0.86),
"Factory Blue Metal Roof": ((0.08, 0.50, 0.88), 0.58),
}
EXPORT_METALLIC_OVERRIDES = {
"Office White Plaster Facade": 0.0,
"Office White Metal Facade": 0.0,
"Industrial White Ribbed Facade": 0.08,
}
EXPORT_BASE_COLOR_OVERRIDES = {
"Tree Crown": (0.11, 0.34, 0.075),
"Tree Crown Dark": (0.065, 0.24, 0.055),
"Tree Crown Light": (0.14, 0.40, 0.085),
"Office White Plaster Facade": (0.93, 0.94, 0.91),
"Office White Metal Facade": (0.93, 0.94, 0.91),
"Office Light Flat Roof": (0.88, 0.90, 0.88),
}
EXPORT_EMISSION_OVERRIDES = {
"Tree Crown": ((0.04, 0.11, 0.035), 0.02),
"Tree Crown Dark": ((0.025, 0.07, 0.02), 0.015),
"Tree Crown Light": ((0.045, 0.12, 0.03), 0.015),
"Office White Plaster Facade": ((0.93, 0.94, 0.91), 0.18),
"Office White Metal Facade": ((0.93, 0.94, 0.91), 0.18),
"Office Light Flat Roof": ((0.88, 0.90, 0.88), 0.14),
"Industrial White Ribbed Facade": ((0.90, 0.93, 0.91), 0.18),
"Factory Blue Metal Roof": ((0.08, 0.50, 0.88), 0.12),
}
def cli_args():
values = {"blend": None, "glb": None, "metadata": None}
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
i = 0
while i < len(argv):
if argv[i].startswith("--") and i + 1 < len(argv):
values[argv[i][2:]] = argv[i + 1]
i += 2
else:
i += 1
if not values.get("blend"):
raise RuntimeError("--blend is required")
if not values.get("glb"):
raise RuntimeError("--glb is required")
if not values.get("metadata"):
raise RuntimeError("--metadata is required")
return values
def image_for(material, want_normal=False):
candidates = []
for node in material.node_tree.nodes:
if node.type != "TEX_IMAGE" or not node.image:
continue
name = os.path.basename(node.image.name).lower()
is_normal = "_nor_" in name or "_normal" in name or "_bump" in name
if is_normal == want_normal:
candidates.append(node.image)
return candidates[0] if candidates else None
def source_color(material):
color = tuple(material.diffuse_color[:3])
if len(color) != 3:
return (0.5, 0.5, 0.5)
return color
def principled_bsdf(material):
if not material.use_nodes:
return None
for node in material.node_tree.nodes:
if node.type == "BSDF_PRINCIPLED":
return node
return None
def source_principled_value(material, input_name, fallback):
node = principled_bsdf(material)
if not node or input_name not in node.inputs:
return fallback
return node.inputs[input_name].default_value
def source_texture_scale(material):
for node in material.node_tree.nodes:
if node.type == "MAPPING":
return tuple(node.inputs["Scale"].default_value[:3])
return (1.0, 1.0, 1.0)
def source_alpha_clipped(material):
"""Whether the source material carries its silhouette in a texture alpha.
Two conditions, because either alone gives a wrong answer. A link into the
Principled Alpha input is not enough: shrub_02 arrives from glTF with a
Math node wired there even though its JPEG diffuse is opaque, and taking
that at face value re-encodes an opaque texture as a PNG and makes Cesium
alpha-test 270 tufts for nothing. An alpha channel alone is not enough
either: fat_tree.png is RGBA with every texel at 1.0.
So ask both — the author wired alpha, and the texture actually cuts.
"""
node = principled_bsdf(material)
if not node or "Alpha" not in node.inputs:
return False
if not node.inputs["Alpha"].links:
return False
diffuse = image_for(material, want_normal=False)
return diffuse is not None and image_has_cutout(diffuse)
_CUTOUT_CACHE = {}
def image_has_cutout(image, threshold=0.5):
"""Whether any of the image's texels are transparent enough to be cut.
A full pass over the pixel buffer, so memoise it — the exporter asks once
per material and several materials can share one texture.
"""
if image.name in _CUTOUT_CACHE:
return _CUTOUT_CACHE[image.name]
width, height = image.size
result = False
if width and height:
alpha = np.empty(width * height * 4, dtype=np.float32)
image.pixels.foreach_get(alpha)
result = bool((alpha[3::4] < threshold).any())
_CUTOUT_CACHE[image.name] = result
return result
def tinted_image(source, name, tint, factor):
existing = bpy.data.images.get(name)
if existing:
return existing
width, height = source.size
pixels = np.empty(width * height * 4, dtype=np.float32)
source.pixels.foreach_get(pixels)
rgba = pixels.reshape((-1, 4))
rgba[:, :3] = rgba[:, :3] * (1.0 - factor) + np.asarray(
tint, dtype=np.float32) * factor
result = bpy.data.images.new(name, width=width, height=height, alpha=True)
result.file_format = "PNG"
result.colorspace_settings.name = "sRGB"
result.pixels.foreach_set(pixels)
result.pack()
return result
def cesium_tinted_image(material, source):
tint = EXPORT_TINTS.get(material.name)
if not tint or not source:
return source
color, factor = tint
safe_name = material.name.replace(" ", "_")
return tinted_image(
source, f"{EXPORT_PREFIX}{safe_name} Baked", color, factor)
def alpha_dilated_image(source, name, threshold=0.5, passes=8, gain=1.0,
saturation=1.0):
"""Flood the opaque colour outward underneath the cut-out, and lift it.
SpeedTree writes pure black wherever a leaf card is cut away — 97% of the
apple atlas's transparent area is exactly (0, 0, 0). An alpha mask hides
that at full resolution, but Cesium mip-maps the texture and every mip
level averages those black texels into the leaf edges, so the crown grows a
dark fringe that thickens with distance. Blender's preview renders at mip
0 and never shows it, which is why this only surfaces in the viewer.
Replacing the colour under the cut-out with its nearest opaque neighbours
leaves no black to bleed. Alpha is copied through untouched, so the
silhouette is byte-for-byte what it was.
`gain` and `saturation` grade the result into the same exposure and colour
as the rest of the scene — see FOLIAGE_ALBEDO_GAIN and FOLIAGE_SATURATION.
Both are applied after the flood so the filled border keeps matching the
leaves it was copied from, and the result is clipped at 1.0.
"""
existing = bpy.data.images.get(name)
if existing:
return existing
width, height = source.size
pixels = np.empty(width * height * 4, dtype=np.float32)
source.pixels.foreach_get(pixels)
rgba = pixels.reshape((height, width, 4))
rgb = rgba[..., :3].copy()
filled = rgba[..., 3] >= threshold
# Each pass pushes the colour one texel further out, so `passes` is how
# many mip levels' worth of filter footprint gets covered.
for _ in range(passes):
if filled.all():
break
weight = filled[..., None].astype(np.float32)
total = np.zeros_like(rgb)
count = np.zeros((height, width, 1), dtype=np.float32)
for shift, axis in ((1, 0), (-1, 0), (1, 1), (-1, 1)):
total += np.roll(rgb * weight, shift, axis=axis)
count += np.roll(weight, shift, axis=axis)
edge = (~filled) & (count[..., 0] > 0)
rgb[edge] = total[edge] / count[edge]
filled = filled | edge
if saturation != 1.0:
# Rec.709 luminance, so the push is around perceived brightness rather
# than the channel average.
luma = rgb @ np.asarray([0.2126, 0.7152, 0.0722], dtype=np.float32)
rgb = luma[..., None] + (rgb - luma[..., None]) * saturation
if gain != 1.0 or saturation != 1.0:
rgb = np.clip(rgb * gain, 0.0, 1.0)
dilated = rgba.copy()
dilated[..., :3] = rgb
result = bpy.data.images.new(name, width=width, height=height, alpha=True)
result.file_format = "PNG"
result.colorspace_settings.name = "sRGB"
result.pixels.foreach_set(dilated.ravel())
result.pack()
return result
def tree_crown_image():
name = "Cesium Tree Crown Baked"
existing = bpy.data.images.get(name)
if existing:
return existing
size = 256
x, y = np.meshgrid(
np.linspace(0.0, 1.0, size, dtype=np.float32),
np.linspace(0.0, 1.0, size, dtype=np.float32),
)
noise = (
np.sin((x * 17.0 + y * 7.0) * np.pi) * 0.24 +
np.sin((x * 43.0 - y * 31.0) * np.pi) * 0.13 +
np.sin((x * 89.0 + y * 67.0) * np.pi) * 0.07
)
noise = np.clip(0.5 + noise, 0.0, 1.0)[..., None]
dark = np.asarray((0.04, 0.17, 0.04), dtype=np.float32)
light = np.asarray((0.17, 0.46, 0.115), dtype=np.float32)
rgb = dark + (light - dark) * noise
rgba = np.concatenate(
(rgb, np.ones((size, size, 1), dtype=np.float32)), axis=2)
result = bpy.data.images.new(name, width=size, height=size, alpha=True)
result.file_format = "PNG"
result.colorspace_settings.name = "sRGB"
result.pixels.foreach_set(rgba.ravel())
result.pack()
return result
def make_export_material(material):
result = material.copy()
result.name = EXPORT_PREFIX + material.name
result.use_nodes = True
nodes = result.node_tree.nodes
links = result.node_tree.links
nodes.clear()
output = nodes.new("ShaderNodeOutputMaterial")
output.location = (520, 0)
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
bsdf.location = (250, 0)
base_color = EXPORT_BASE_COLOR_OVERRIDES.get(
material.name, source_color(material))
bsdf.inputs["Base Color"].default_value = (*base_color, 1.0)
bsdf.inputs["Roughness"].default_value = source_principled_value(
material, "Roughness", 0.8)
bsdf.inputs["Metallic"].default_value = EXPORT_METALLIC_OVERRIDES.get(
material.name, source_principled_value(material, "Metallic", 0.0))
emission = EXPORT_EMISSION_OVERRIDES.get(material.name)
if emission:
emission_color, emission_strength = emission
if "Emission Color" in bsdf.inputs:
bsdf.inputs["Emission Color"].default_value = (*emission_color, 1.0)
elif "Emission" in bsdf.inputs:
bsdf.inputs["Emission"].default_value = (*emission_color, 1.0)
if "Emission Strength" in bsdf.inputs:
bsdf.inputs["Emission Strength"].default_value = emission_strength
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
diffuse = image_for(material, want_normal=False)
normal = image_for(material, want_normal=True)
# Foliage that carries its silhouette in the texture's alpha has to keep
# that channel; every other material is flattened to opaque below.
alpha_clipped = source_alpha_clipped(material)
if material.name == "Tree Crown":
diffuse = tree_crown_image()
else:
diffuse = cesium_tinted_image(material, diffuse)
if alpha_clipped and diffuse is not None:
safe_name = material.name.replace(" ", "_")
diffuse = alpha_dilated_image(
diffuse, f"{EXPORT_PREFIX}{safe_name} Dilated",
gain=FOLIAGE_ALBEDO_GAIN, saturation=FOLIAGE_SATURATION)
if material.name in EXPORT_BASE_COLOR_OVERRIDES:
diffuse = None
normal = None
mapping = None
if diffuse or normal:
texcoord = nodes.new("ShaderNodeTexCoord")
texcoord.location = (-650, 0)
mapping = nodes.new("ShaderNodeMapping")
mapping.location = (-450, 0)
mapping.inputs["Scale"].default_value = source_texture_scale(material)
links.new(texcoord.outputs["UV"], mapping.inputs["Vector"])
diffuse_node = None
if diffuse:
image = nodes.new("ShaderNodeTexImage")
image.location = (-200, 80)
image.image = diffuse
image.extension = "REPEAT"
links.new(mapping.outputs["Vector"], image.inputs["Vector"])
links.new(image.outputs["Color"], bsdf.inputs["Base Color"])
diffuse_node = image
if normal:
normal_tex = nodes.new("ShaderNodeTexImage")
normal_tex.location = (-200, -180)
normal_tex.image = normal
normal_tex.image.colorspace_settings.name = "Non-Color"
normal_tex.extension = "REPEAT"
normal_map = nodes.new("ShaderNodeNormalMap")
normal_map.location = (20, -160)
normal_map.inputs["Strength"].default_value = 0.52
links.new(mapping.outputs["Vector"], normal_tex.inputs["Vector"])
links.new(normal_tex.outputs["Color"], normal_map.inputs["Color"])
links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"])
if alpha_clipped and diffuse_node is not None:
# A leaf crown is a handful of quads whose shape lives entirely in this
# channel. Pinning Alpha to 1.0 — which is what the rest of the scene
# wants — exports those quads whole, and the cut-away regions of a
# SpeedTree atlas are black, so Cesium draws black slabs.
link_alpha_clip(result, diffuse_node.outputs["Alpha"], bsdf,
cutoff=material.alpha_threshold)
# Lift the crown out of Cesium's ambient. The preview configures no
# environment map, so anything the sun does not hit directly falls to a
# weak default spherical-harmonic term — which is why every other
# material here carries an EXPORT_EMISSION_OVERRIDES entry. A crown is
# mostly self-shadowed leaf cards facing away from the sun, so at
# distance it collapses into one dark mass while a sunlit close-up
# still reads fine.
#
# Feed the diffuse back in as the emissive texture rather than using a
# flat colour: a constant would wash the bark with leaf green, whereas
# this floors every texel at a fraction of its own albedo. It costs no
# extra bytes — the exporter points emissiveTexture at the image the
# base colour already uses.
if "Emission Color" in bsdf.inputs:
links.new(diffuse_node.outputs["Color"], bsdf.inputs["Emission Color"])
elif "Emission" in bsdf.inputs:
links.new(diffuse_node.outputs["Color"], bsdf.inputs["Emission"])
if "Emission Strength" in bsdf.inputs:
bsdf.inputs["Emission Strength"].default_value = FOLIAGE_EMISSION
elif "Alpha" in bsdf.inputs:
bsdf.inputs["Alpha"].default_value = 1.0
return result
def unwrap_mesh(obj):
if obj.type != "MESH" or not obj.data.polygons:
return
# Imported assets ship authored UVs that map onto their own texture atlas;
# smart_project would scramble the leaves. Only the procedurally built
# meshes arrive without a UV layer, so that is the reliable discriminator.
if obj.data.uv_layers:
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
try:
bpy.ops.uv.smart_project(island_margin=0.025, area_weight=0.0)
finally:
bpy.ops.object.mode_set(mode="OBJECT")
def apply_mesh_modifiers(obj):
if obj.type != "MESH":
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
for modifier in list(obj.modifiers):
try:
bpy.ops.object.modifier_apply(modifier=modifier.name)
except RuntimeError:
pass
def triangulate_mesh(obj):
"""Split n-gons into triangles ahead of the exporter.
glTF has no n-gons, so the exporter triangulates on the way out regardless
— doing it here does not change a single output triangle. What it changes
is tangents: Blender can only build a tangent basis on tris and quads, and
every footprint this pipeline extrudes from OSM is an n-gon, so with
export_tangents on each one logged "切向空间只能只算三角/四边形" and shipped
without a basis. Triangulating first turns ~55 failures into tangents.
Skipped for meshes that are already triangles, which covers the instanced
props — those share one datablock across hundreds of objects and
modifier_apply refuses to touch multi-user data.
"""
if obj.type != "MESH" or not obj.data.polygons:
return
if all(len(polygon.vertices) <= 3 for polygon in obj.data.polygons):
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
modifier = obj.modifiers.new("ExportTriangulate", "TRIANGULATE")
modifier.min_vertices = 4
try:
bpy.ops.object.modifier_apply(modifier=modifier.name)
except RuntimeError:
# Multi-user data. The exporter still triangulates it, we just lose the
# tangent basis for that mesh.
obj.modifiers.remove(modifier)
def export(args):
if not os.path.exists(args["blend"]):
raise FileNotFoundError(args["blend"])
bpy.ops.wm.open_mainfile(filepath=args["blend"])
material_map = {}
meshes = []
unwrapped = set()
for obj in bpy.context.scene.objects:
if obj.type != "MESH":
continue
if obj.name == "Ground Plane":
continue
if obj.hide_viewport or obj.hide_render:
continue
meshes.append(obj)
apply_mesh_modifiers(obj)
# Hundreds of grass tufts share four mesh datablocks; unwrapping and
# triangulating are properties of the mesh, so once per datablock.
if obj.data.name not in unwrapped:
unwrapped.add(obj.data.name)
triangulate_mesh(obj)
unwrap_mesh(obj)
for slot in obj.material_slots:
if not slot.material:
continue
source = slot.material
# Instanced props share one mesh datablock, and material slots live
# on the mesh, so the first tree already swapped in the export
# material for all 181 of them. Without this the next instance
# wraps that result again — "Cesium Cesium Cesium ..." — and since
# the baked-image cache is keyed by material name, every round
# embeds another multi-megabyte copy of the same texture.
if source.name.startswith(EXPORT_PREFIX):
continue
if source.name not in material_map:
material_map[source.name] = make_export_material(source)
slot.material = material_map[source.name]
bpy.ops.object.select_all(action="DESELECT")
for obj in meshes:
obj.select_set(True)
bpy.context.view_layer.objects.active = meshes[0] if meshes else None
os.makedirs(os.path.dirname(args["glb"]), exist_ok=True)
bpy.ops.export_scene.gltf(
filepath=args["glb"],
export_format="GLB",
use_selection=True,
export_apply=False,
export_texcoords=True,
export_normals=True,
export_materials="EXPORT",
export_image_format="AUTO",
# The foliage materials carry a normal map, and glTF leaves tangent
# derivation to the renderer when TANGENT is absent. On thin
# double-sided leaf cards that derivation is unreliable, so ship real
# tangents — it costs four floats a vertex on meshes this small.
export_tangents=True,
export_extras=True,
export_cameras=False,
export_lights=False,
)
scene = bpy.context.scene
try:
bounds = json.loads(scene.get("osm_bounds", "{}"))
except (TypeError, ValueError):
bounds = {}
if bounds:
center_lon = (bounds["min_lon"] + bounds["max_lon"]) / 2.0
center_lat = (bounds["min_lat"] + bounds["max_lat"]) / 2.0
else:
center_lon = center_lat = 0.0
metadata = {
"asset": os.path.basename(args["glb"]),
"assets": [{
"id": "main",
"label": "Scene",
"type": "model",
"url": os.path.basename(args["glb"]),
"enabled": True,
}],
"coordinate_system": "local ENU meters (X east, Y north, Z up)",
"heading_correction_degrees": -90.0,
"anchor": {"longitude": center_lon, "latitude": center_lat, "height": 0.35},
"bounds": bounds,
"source_osm": scene.get("source_osm", ""),
"source_geojson": scene.get("source_geojson", ""),
"scene_stats": {
"buildings": scene.get("building_count", 0),
"industrial_buildings": scene.get("industrial_building_count", 0),
"lake_polygons": scene.get("lake_count", 0),
"trees": scene.get("tree_count", 0),
"grass_polygons": scene.get("grass_count", 0),
"scrub_polygons": scene.get("scrub_count", 0),
"fountains": scene.get("fountain_count", 0),
},
"cesium_js": (
"const p = Cesium.Cartesian3.fromDegrees(" +
f"{center_lon:.8f}, {center_lat:.8f}, 0.35);\n" +
"const enu = Cesium.Transforms.eastNorthUpToFixedFrame(p);\n" +
"const correction = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90.0));\n" +
"const modelMatrix = Cesium.Matrix4.multiplyByMatrix3(enu, correction, new Cesium.Matrix4());\n" +
"Cesium.Model.fromGltfAsync({ url: '" + os.path.basename(args["glb"]) +
"', modelMatrix }).then(model => viewer.scene.primitives.add(model));"
),
}
os.makedirs(os.path.dirname(args["metadata"]), exist_ok=True)
with open(args["metadata"], "w", encoding="utf-8") as handle:
json.dump(metadata, handle, ensure_ascii=False, indent=2)
handle.write("\n")
print("CESIUM_EXPORT_DONE", json.dumps({
"glb": args["glb"], "metadata": args["metadata"],
"meshes": len(meshes), "materials": len(material_map),
"anchor": [center_lon, center_lat],
}, ensure_ascii=True))
if __name__ == "__main__":
export(cli_args())
+999
View File
@@ -0,0 +1,999 @@
"""Build a lightweight 3D scene from an OSM export and optional osm2streets GeoJSON.
Run from Blender 4.x:
blender --background --factory-startup --python blender/generate_scene.py -- \
--osm "/path/to/input.osm" \
--output "/path/to/output.blend" \
--render "/path/to/preview.png"
The OSM bounds element is used deliberately. OSM exports may contain distant
relation members outside the requested area, so using every node for extent
would produce a misleadingly large model.
Optional osm2streets GeoJSON directory provides detailed road surfaces,
sidewalks, lane markings, and crosswalks. When omitted, roads fall back to
simple OSM highway polylines.
Vegetation: natural=tree nodes become individual trees, natural=tree_row ways
become evenly spaced rows, landuse=grass becomes green ground, natural=scrub
becomes low shrub volumes. amenity=fountain becomes low-poly fountain basins.
"""
import json
import math
import os
import sys
import bpy
from mathutils import Vector
# --factory-startup does not put the script's own directory on sys.path, so the
# osmassets package next to this file is not importable without this.
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
from osmassets import catalog # noqa: E402
from osmassets.geom import ( # noqa: E402 (needs the sys.path line above)
clip_polygon,
distance_to_ring,
feature_in_bounds,
geometry_rings,
point_in_polygon,
polygon_area,
sample_polygon_interior,
sample_ring_boundary,
sample_tree_row,
)
from osmassets.materials import ( # noqa: E402
from_spec as material_from_spec,
tint_base_color,
)
from osmassets.mesh import ( # noqa: E402
MeshBatch,
add_polyline,
add_roof,
add_wall_panel,
link_object_to_collection,
make_prism,
new_collection,
)
from osmassets.osm import Projector, parse_height, parse_osm # noqa: E402
from osmassets import water as _water # noqa: E402
from osmassets import grass as _grass # noqa: E402
from osmassets import scrub as _scrub # noqa: E402
from osmassets import tree as _tree # noqa: E402
# Building assembly stays in this file because it needs make_prism, add_roof,
# add_wall_panel, and add_building_details — Blender geometry helpers that
# live a few lines above. The other features moved to osmassets/{water,grass,
# scrub}.py and take only pure-geometry primitives (MeshBatch / clip_polygon).
def _assemble_building(ring, way_id, tag, args, buildings_c, building_mats):
industrial = (tag.get("building") == "industrial" and
way_id not in args["office_overrides"])
source_height = max(3.0, parse_height(tag, 12.0))
height = source_height if industrial or source_height >= 30.0 else 11.4
material = building_mats["industrial"] if industrial else building_mats["default"]
building_name = "Building_" + way_id
building_obj = make_prism(building_name, ring, 0.08, height,
material, buildings_c)
if building_obj:
building_obj["osm_height"] = source_height
building_obj["render_height"] = height
building_obj["building_kind"] = "industrial" if industrial else "office"
building_obj["osm_building_tag"] = tag.get("building", "")
building_obj["office_override"] = way_id in args["office_overrides"]
bevel = building_obj.modifiers.new("Soft facade edges", "BEVEL")
bevel.width = 0.16
bevel.segments = 2
roof_mat = (building_mats["industrial_roof"] if industrial
else building_mats["office_roof"])
add_roof(building_name, ring, height + 0.095, roof_mat, buildings_c)
add_building_details(building_name, ring, height, industrial,
building_mats, buildings_c)
return 1, int(industrial), ring
MODEL_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "assets", "models", "polyhaven"
))
CUSTOM_MODEL_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "assets", "models", "custom"
))
# Vendored under the name shrub_02, but the plant reads as a tufted grass, not
# as a bush: it belongs on the lawns. Scrub beds stay flat ground cover until a
# genuinely bush-shaped asset is sourced.
TUFT_MODEL = os.path.join(MODEL_ROOT, "shrub_02", "shrub_02_1k.gltf")
# Poly Haven ships it at ~27k triangles across four variants. The leaves are
# modelled as real geometry, so decimation eats them: at ~2.2k per variant the
# tufts render as bare twigs. Instancing makes the full mesh affordable anyway —
# every tuft shares one of four datablocks, so the scene and the exported GLB
# carry that geometry once no matter how many are scattered. 0 disables it.
TUFT_TARGET_TRIS = 0
# The variants stand 1.17-1.68m tall natively, which is shrub height. Roughly a
# third of that lands in the 0.3-0.8m range real lawn tufts occupy.
TUFT_SCALE_RANGE = (0.26, 0.46)
TUFT_SPACING = 1.7
TUFT_LIMIT_PER_LAWN = 100
# The vendored diffuse is a grey-green leaf over brown stems. Dropped onto the
# saturated lawn as-is it reads as dead weeds, so the base colour is mixed
# toward the lawn tint, a shade brighter so the tufts still separate from it.
TUFT_TINT = (0.15, 0.52, 0.09)
TUFT_TINT_FACTOR = 0.66
SCRUB_BUSH_MODEL = os.path.join(CUSTOM_MODEL_ROOT, "bush", "bush.glb")
SCRUB_BUSH_SPACING = 0.82
SCRUB_BUSH_INSET = 0.38
SCRUB_BUSH_LIMIT_PER_PATCH = 180
SCRUB_BUSH_HEIGHT = 1.575
SCRUB_BUSH_SCALE_JITTER = 0.16
SCRUB_BUSH_LEAF_TINT = (0.075, 0.31, 0.055)
SCRUB_BUSH_LEAF_TINT_FACTOR = 0.36
SCRUB_BUSH_TRUNK_TINT = (0.13, 0.095, 0.055)
SCRUB_BUSH_TRUNK_TINT_FACTOR = 0.18
SCRUB_TREE_MIN_AREA = 45.0
SCRUB_TREE_SPACING = 8.0
SCRUB_TREE_EDGE_CLEARANCE = 2.8
SCRUB_TREE_LIMIT_PER_PATCH = 5
SCRUB_TREE_HEIGHT_RANGE = (4.6, 6.2)
# Tree styles. The two built from mesh batches live in this file; the rest are
# vendored models handled by osmassets.tree, which owns that list. A model style
# whose asset is missing falls back to "natural" rather than planting nothing.
TREE_STYLES = frozenset(("natural", "procedural")) | frozenset(_tree.MODEL_STYLES)
def cli_args():
values = {"osm": None, "geojson": None, "output": None, "render": None,
"office_overrides": "", "tree_style": "natural"}
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
i = 0
while i < len(argv):
if argv[i].startswith("--") and i + 1 < len(argv):
values[argv[i][2:].replace("-", "_")] = argv[i + 1]
i += 2
else:
i += 1
if not values.get("osm"):
raise RuntimeError("--osm is required; --geojson is optional")
if not values.get("output"):
raise RuntimeError("--output is required")
if not values.get("render"):
raise RuntimeError("--render is required")
if values.get("office_overrides"):
try:
values["office_overrides"] = set(
w.strip() for w in values["office_overrides"].split(",") if w.strip()
)
except Exception:
values["office_overrides"] = set()
else:
values["office_overrides"] = set()
if values.get("tree_style") not in TREE_STYLES:
raise RuntimeError("--tree-style must be one of: "
+ ", ".join(sorted(TREE_STYLES)))
return values
def add_building_details(name, ring, height, industrial, materials, collection):
footprint = ring[:-1] if len(ring) > 1 and ring[0] == ring[-1] else ring
if len(footprint) < 3:
return
glass_mat = materials["factory_glass"] if industrial else materials["glass"]
glass_batch = MeshBatch(name + "_Windows", collection, glass_mat)
edges = list(zip(footprint, footprint[1:] + footprint[:1]))
if industrial:
band_height = min(1.8, max(0.75, height * 0.16))
band_base = max(0.9, height * 0.52)
for start, end in edges:
add_wall_panel(glass_batch, start, end, band_base, band_height,
thickness=0.055, inset=0.12)
else:
floor_height = 3.25
floor_count = max(1, int((height - 0.7) / floor_height))
for floor in range(floor_count):
band_base = 0.55 + floor * floor_height + 0.95
if band_base + 1.25 > height - 0.18:
break
for start, end in edges:
add_wall_panel(glass_batch, start, end, band_base, 1.25,
thickness=0.045, inset=0.10)
glass_batch.finish()
def add_geojson_layer(path, layer, projector, collection, material, z):
if not os.path.exists(path):
return 0
with open(path, "r", encoding="utf-8") as handle:
data = json.load(handle)
batch = MeshBatch("Road_" + layer, collection, material)
b = projector.bounds
xmin, ymin = projector.xy((b["min_lon"], b["min_lat"]))
xmax, ymax = projector.xy((b["max_lon"], b["max_lat"]))
count = 0
for feature in data.get("features", []):
if not feature_in_bounds(feature, projector):
continue
for ring in geometry_rings(feature.get("geometry")):
points = [projector.xy(pair) for pair in ring]
points = clip_polygon(points, xmin, xmax, ymin, ymax)
if len(points) >= 3:
batch.add_polygon(points, z)
count += 1
batch.finish()
return count
def add_tree_batch(positions, collection, trunk_material, leaf_material):
trunk = MeshBatch("Tree_Trunks", collection, trunk_material)
leaves = MeshBatch("Tree_Crowns", collection, leaf_material)
sides = 10
def add_blob(batch, cx, cy, cz, rx, ry, rz, phase):
rings = 5
start = len(batch.vertices)
for ring in range(rings):
latitude = -math.pi / 2 + math.pi * ring / (rings - 1)
ring_radius = math.cos(latitude)
for side in range(sides):
angle = math.tau * side / sides
variation = 1.0 + 0.09 * math.sin(phase + side * 1.73 + ring * 0.91)
batch.vertices.append((cx + rx * ring_radius * math.cos(angle) * variation,
cy + ry * ring_radius * math.sin(angle) * variation,
cz + rz * math.sin(latitude)))
for ring in range(rings - 1):
for side in range(sides):
next_side = (side + 1) % sides
batch.faces.append((start + ring * sides + side,
start + ring * sides + next_side,
start + (ring + 1) * sides + next_side,
start + (ring + 1) * sides + side))
for index, (x, y, height) in enumerate(positions):
base = len(trunk.vertices)
radius = max(0.12, height * 0.035)
trunk_top = height * 0.62
for z, ring_radius in ((0.0, radius), (trunk_top, radius * 0.68)):
for i in range(sides):
a = math.tau * i / sides
trunk.vertices.append((x + ring_radius * math.cos(a),
y + ring_radius * math.sin(a), z))
trunk.faces.append(tuple(base + i for i in range(sides - 1, -1, -1)))
for i in range(sides):
j = (i + 1) % sides
trunk.faces.append((base + i, base + j, base + sides + j, base + sides + i))
trunk.faces.append(tuple(base + sides + i for i in range(sides)))
crown_r = max(0.85, height * 0.30)
crown_z = height * 0.82
add_blob(leaves, x, y, crown_z, crown_r * 0.70,
crown_r * 0.62, crown_r * 0.72, index * 1.41)
add_blob(leaves, x - crown_r * 0.42, y + crown_r * 0.08,
crown_z * 0.98, crown_r * 0.52, crown_r * 0.48,
crown_r * 0.58, index * 2.17 + 0.7)
add_blob(leaves, x + crown_r * 0.40, y - crown_r * 0.05,
crown_z * 1.02, crown_r * 0.50, crown_r * 0.46,
crown_r * 0.55, index * 2.63 + 1.3)
trunk.finish()
leaves.finish()
def add_natural_tree_instances(positions, collection, trunk_material,
leaf_dark_material, leaf_light_material):
trunk = MeshBatch("Tree_Natural_Trunks", collection, trunk_material)
lower = MeshBatch("Tree_Natural_Crowns_Dark", collection, leaf_dark_material)
upper = MeshBatch("Tree_Natural_Crowns_Light", collection, leaf_light_material)
trunk_sides = 9
crown_sides = 9
crown_rings = 5
def add_blob(batch, cx, cy, cz, rx, ry, rz, phase, squash=1.0):
start = len(batch.vertices)
for ring in range(crown_rings):
latitude = -math.pi / 2 + math.pi * ring / (crown_rings - 1)
ring_radius = math.cos(latitude)
for side in range(crown_sides):
angle = math.tau * side / crown_sides
wobble = (
1.0 +
0.14 * math.sin(phase + side * 1.31 + ring * 0.83) +
0.07 * math.sin(phase * 0.7 + side * 2.11)
)
batch.vertices.append((
cx + rx * ring_radius * math.cos(angle) * wobble,
cy + ry * ring_radius * math.sin(angle) * wobble,
cz + rz * math.sin(latitude) * squash,
))
for ring in range(crown_rings - 1):
for side in range(crown_sides):
next_side = (side + 1) % crown_sides
batch.faces.append((
start + ring * crown_sides + side,
start + ring * crown_sides + next_side,
start + (ring + 1) * crown_sides + next_side,
start + (ring + 1) * crown_sides + side,
))
for index, (x, y, height) in enumerate(positions):
target_height = max(4.8, min(8.8, height * 1.08))
phase = index * 1.61803398875
trunk_height = target_height * (0.48 + 0.05 * math.sin(phase))
trunk_radius = max(0.13, target_height * 0.038)
lean_x = math.sin(phase * 1.7) * target_height * 0.025
lean_y = math.cos(phase * 1.3) * target_height * 0.025
base = len(trunk.vertices)
trunk_levels = [
(0.0, trunk_radius),
(trunk_height * 0.55, trunk_radius * 0.78),
(trunk_height, trunk_radius * 0.48),
]
for level_index, (z, radius) in enumerate(trunk_levels):
offset_x = lean_x * level_index / (len(trunk_levels) - 1)
offset_y = lean_y * level_index / (len(trunk_levels) - 1)
for side in range(trunk_sides):
angle = math.tau * side / trunk_sides
trunk.vertices.append((
x + offset_x + radius * math.cos(angle),
y + offset_y + radius * math.sin(angle),
z,
))
trunk.faces.append(tuple(base + i for i in range(trunk_sides - 1, -1, -1)))
for level_index in range(len(trunk_levels) - 1):
row = base + level_index * trunk_sides
next_row = row + trunk_sides
for side in range(trunk_sides):
next_side = (side + 1) % trunk_sides
trunk.faces.append((row + side, row + next_side,
next_row + next_side, next_row + side))
top_row = base + (len(trunk_levels) - 1) * trunk_sides
trunk.faces.append(tuple(top_row + i for i in range(trunk_sides)))
crown_x = x + lean_x
crown_y = y + lean_y
crown_z = trunk_height + target_height * 0.22
crown_r = target_height * (0.35 + 0.035 * math.sin(phase * 0.9))
# Dark lower mass gives the canopy volume when viewed obliquely.
add_blob(lower, crown_x, crown_y, crown_z - crown_r * 0.08,
crown_r * 0.95, crown_r * 0.78, crown_r * 0.52,
phase, squash=0.82)
add_blob(lower, crown_x - crown_r * 0.46, crown_y + crown_r * 0.05,
crown_z - crown_r * 0.02, crown_r * 0.62, crown_r * 0.50,
crown_r * 0.42, phase + 0.8, squash=0.80)
add_blob(lower, crown_x + crown_r * 0.42, crown_y - crown_r * 0.08,
crown_z, crown_r * 0.58, crown_r * 0.48,
crown_r * 0.40, phase + 1.9, squash=0.80)
# Lighter upper clumps break the silhouette without adding heavy geometry.
add_blob(upper, crown_x + crown_r * 0.05, crown_y + crown_r * 0.04,
crown_z + crown_r * 0.34, crown_r * 0.70,
crown_r * 0.58, crown_r * 0.38, phase + 2.7, squash=0.74)
add_blob(upper, crown_x - crown_r * 0.24, crown_y - crown_r * 0.22,
crown_z + crown_r * 0.23, crown_r * 0.46,
crown_r * 0.40, crown_r * 0.30, phase + 3.5, squash=0.72)
trunk.finish()
lower.finish()
upper.finish()
def load_tuft_variants():
"""Import the vendored Poly Haven plant once and return decimated meshes.
Returns [] when the asset is missing so a clean checkout still builds; the
lawns then fall back to plain textured ground.
"""
if not os.path.exists(TUFT_MODEL):
return []
before = set(bpy.data.objects)
try:
bpy.ops.import_scene.gltf(filepath=TUFT_MODEL)
except (RuntimeError, AttributeError) as error:
print("Grass tuft import failed, lawns stay flat:", error)
return []
imported = [obj for obj in set(bpy.data.objects) - before if obj.type == "MESH"]
variants = []
tinted = set()
for obj in sorted(imported, key=lambda item: item.name):
obj.data.calc_loop_triangles()
source_tris = len(obj.data.loop_triangles)
if TUFT_TARGET_TRIS and source_tris > TUFT_TARGET_TRIS:
modifier = obj.modifiers.new("TuftDecimate", "DECIMATE")
modifier.ratio = max(0.02, TUFT_TARGET_TRIS / source_tris)
bpy.context.view_layer.update()
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
mesh = bpy.data.meshes.new_from_object(evaluated)
else:
mesh = obj.data.copy()
mesh.name = "GrassTuft_" + obj.name
mesh.calc_loop_triangles()
# Nothing is saved yet at this point, so keep the datablock alive even
# if a scene ends up with no lawn polygons to instance it into.
mesh.use_fake_user = True
for material in mesh.materials:
# The vendored textures are JPEG with no alpha channel, so hashed
# transparency only costs sorting work in Blender and Cesium.
if hasattr(material, "blend_method"):
material.blend_method = "OPAQUE"
# All four variants share one material, so guard against stacking
# the mix node — and the tint with it — four times over.
if material.name not in tinted:
tint_base_color(material, TUFT_TINT, TUFT_TINT_FACTOR)
tinted.add(material.name)
variants.append(mesh)
for obj in imported:
bpy.data.objects.remove(obj, do_unlink=True)
tris = sum(len(mesh.loop_triangles) for mesh in variants)
detail = f"decimated to ~{TUFT_TARGET_TRIS} tris each" if TUFT_TARGET_TRIS else "full detail"
print(f"Grass tuft variants loaded: {len(variants)} ({detail}, {tris} tris shared)")
return variants
def tuft_density_wave(x, y):
# A lawn wants gentle clumping, not the hard banding a shrub bed needs:
# low amplitude keeps most of the polygon planted so the bare stretches
# read as mown patches rather than as dead ground.
return (math.sin(x * 0.21 + y * 0.17)
+ 0.55 * math.sin(x * 0.44 - y * 0.29 + 1.3))
def add_grass_tufts(name, ring, variants, collection):
"""Scatter the plant variants across a lawn polygon as grass tufts."""
xmin = min(x for x, _ in ring)
xmax = max(x for x, _ in ring)
ymin = min(y for _, y in ring)
ymax = max(y for _, y in ring)
def sample(spacing):
spots = []
cols = max(1, int(math.ceil((xmax - xmin) / spacing)))
rows = max(1, int(math.ceil((ymax - ymin) / spacing)))
for i in range(cols):
for j in range(rows):
# Jitter breaks up the lattice; without it the tufts read as a
# planted grid rather than as grass.
seed = (i * 73856093) ^ (j * 19349663)
jx = ((seed * 0.61803398875) % 1.0 - 0.5) * spacing * 0.8
jy = ((seed * 0.41421356237) % 1.0 - 0.5) * spacing * 0.8
x = xmin + (i + 0.5) * spacing + jx
y = ymin + (j + 0.5) * spacing + jy
if not point_in_polygon((x, y), ring):
continue
# Keep tufts off the kerb line so they do not overhang paving.
if distance_to_ring((x, y), ring) < 0.45:
continue
if tuft_density_wave(x, y) < -0.85:
continue
spots.append((x, y, seed))
return spots
# Adapt spacing to the lawn so a large polygon does not explode the export.
spacing = TUFT_SPACING
spots = sample(spacing)
while len(spots) > TUFT_LIMIT_PER_LAWN and spacing < 12.0:
spacing *= 1.22
spots = sample(spacing)
min_scale, max_scale = TUFT_SCALE_RANGE
span = max_scale - min_scale
for index, (x, y, seed) in enumerate(spots):
mesh = variants[index % len(variants)]
obj = bpy.data.objects.new(f"{name}_Tuft_{index:03d}", mesh)
scale = min_scale + span * ((seed * 0.754877666) % 1.0)
# Sunk slightly below the lawn surface so the stems never float.
obj.location = (x, y, 0.008)
obj.rotation_euler = (
math.radians(-4.0 + 8.0 * ((seed * 0.5698403) % 1.0)),
math.radians(-4.0 + 8.0 * ((seed * 0.3317554) % 1.0)),
math.tau * ((seed * 0.61803398875) % 1.0),
)
obj.scale = (scale, scale * (0.90 + 0.20 * ((seed * 0.2236068) % 1.0)), scale)
collection.objects.link(obj)
return len(spots)
def _bake_imported_mesh(obj, name):
mesh = obj.data.copy()
mesh.transform(obj.matrix_world.to_3x3().to_4x4())
mesh.name = name
mesh.use_fake_user = True
return mesh
def _measure_meshes(meshes):
zs = [vertex.co.z for mesh in meshes for vertex in mesh.vertices]
if not zs:
return 1.0, 0.0
low, high = min(zs), max(zs)
return max(high - low, 1e-6), low
def _discard_imported_mesh_objects(objects):
for obj in objects:
mesh = obj.data if obj.type == "MESH" else None
bpy.data.objects.remove(obj, do_unlink=True)
if mesh is not None and mesh.users == 0:
bpy.data.meshes.remove(mesh)
def load_scrub_bush_variant():
"""Import the optional custom bush once for edge instancing."""
if not os.path.exists(SCRUB_BUSH_MODEL):
return None
before = set(bpy.data.objects)
try:
bpy.ops.import_scene.gltf(filepath=SCRUB_BUSH_MODEL)
except (RuntimeError, AttributeError) as error:
print("Scrub bush import failed, scrub stays flat:", error)
return None
imported = [obj for obj in set(bpy.data.objects) - before if obj.type == "MESH"]
if not imported:
print("Scrub bush import produced no mesh objects, scrub stays flat")
return None
meshes = []
for index, obj in enumerate(sorted(imported, key=lambda item: item.name)):
mesh = _bake_imported_mesh(obj, f"ScrubBush_{index:02d}_{obj.name}")
mesh.calc_loop_triangles()
for material in mesh.materials:
if material is None:
continue
material_name = material.name.lower()
if "leaf" in material_name:
tint_base_color(
material, SCRUB_BUSH_LEAF_TINT,
SCRUB_BUSH_LEAF_TINT_FACTOR)
elif "trunk" in material_name or "twig" in material_name:
tint_base_color(
material, SCRUB_BUSH_TRUNK_TINT,
SCRUB_BUSH_TRUNK_TINT_FACTOR)
if getattr(material, "blend_method", "OPAQUE") == "BLEND":
material.blend_method = "HASHED"
material.alpha_threshold = 0.45
material.show_transparent_back = False
meshes.append(mesh)
height, base_z = _measure_meshes(meshes)
_discard_imported_mesh_objects(imported)
tris = sum(len(mesh.loop_triangles) for mesh in meshes)
print(f"Scrub bush loaded: {len(meshes)} mesh(es), {tris} tris shared")
return {"meshes": meshes, "height": height, "base_z": base_z}
def add_scrub_edge_bushes(name, ring, variant, collection):
if not variant:
return 0
samples = sample_ring_boundary(
ring, SCRUB_BUSH_SPACING, inset=SCRUB_BUSH_INSET,
max_samples=SCRUB_BUSH_LIMIT_PER_PATCH)
if not samples:
return 0
base_scale = SCRUB_BUSH_HEIGHT / variant["height"]
for index, (x, y, angle, seed) in enumerate(samples):
jitter = 1.0 + SCRUB_BUSH_SCALE_JITTER * (
2.0 * ((seed * 0.61803398875) % 1.0) - 1.0)
scale = base_scale * jitter
z = 0.065 - variant["base_z"] * scale
rotation = angle + math.tau * 0.08 * ((seed * 0.41421356237) % 1.0 - 0.5)
for mesh_index, mesh in enumerate(variant["meshes"]):
obj = bpy.data.objects.new(
f"{name}_Bush_{index:03d}_{mesh_index:02d}", mesh)
obj.location = (x, y, z)
obj.rotation_euler = (0.0, 0.0, rotation)
obj.scale = (scale, scale, scale)
collection.objects.link(obj)
return len(samples)
def add_scrub_patch(name, ring, ground_material, collection, bush_variant=None):
if len(ring) < 3:
return None, 0
if ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3:
return None, 0
ground = MeshBatch(name, collection, ground_material)
ground.add_polygon(ring, 0.055)
obj = ground.finish()
bush_count = add_scrub_edge_bushes(name, ring, bush_variant, collection)
if obj:
obj["scrub_texture"] = "Poly Haven leafy_grass, scrub-tinted"
obj["scrub_style"] = (
"edge bush instances" if bush_count else "flat foliage ground cover"
)
obj["scrub_edge_bushes"] = bush_count
return obj, bush_count
def sample_scrub_interior_trees(ring, way_id):
if polygon_area(ring) < SCRUB_TREE_MIN_AREA:
return []
try:
seed = int(way_id)
except (TypeError, ValueError):
seed = sum(ord(char) for char in str(way_id))
samples = sample_polygon_interior(
ring, SCRUB_TREE_SPACING,
edge_clearance=SCRUB_TREE_EDGE_CLEARANCE,
max_samples=SCRUB_TREE_LIMIT_PER_PATCH,
seed=seed)
min_height, max_height = SCRUB_TREE_HEIGHT_RANGE
span = max_height - min_height
trees = []
for x, y, sample_seed in samples:
height = min_height + span * ((sample_seed * 0.754877666) % 1.0)
trees.append((x, y, height))
return trees
def add_fountain(name, x, y, collection, materials):
def cylinder(part_name, radius, depth, z, material, vertices=48):
bpy.ops.mesh.primitive_cylinder_add(
vertices=vertices, radius=radius, depth=depth,
location=(x, y, z))
obj = bpy.context.object
obj.name = name + "_" + part_name
link_object_to_collection(obj, collection)
obj.data.materials.append(material)
for polygon in obj.data.polygons:
polygon.use_smooth = True
return obj
basin = cylinder("Basin", 3.0, 0.32, 0.16,
materials["fountain_stone"])
basin["osm_feature"] = "amenity=fountain"
cylinder("Water", 2.52, 0.045, 0.335,
materials["fountain_water"])
cylinder("Pedestal", 0.30, 0.78, 0.72,
materials["fountain_stone"], vertices=32)
bpy.ops.mesh.primitive_uv_sphere_add(
segments=20, ring_count=10, radius=0.22,
location=(x, y, 1.30))
crown = bpy.context.object
crown.name = name + "_Water_Crown"
link_object_to_collection(crown, collection)
crown.data.materials.append(materials["fountain_spray"])
for index in range(8):
angle = math.tau * index / 8.0
radius = 0.50
bpy.ops.mesh.primitive_uv_sphere_add(
segments=12, ring_count=6, radius=0.075,
location=(x + math.cos(angle) * radius,
y + math.sin(angle) * radius,
1.02 + 0.10 * math.sin(angle * 2.0)))
droplet = bpy.context.object
droplet.name = name + "_Droplet_" + str(index + 1)
link_object_to_collection(droplet, collection)
droplet.data.materials.append(materials["fountain_spray"])
def look_at(obj, target):
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat("-Z", "Y").to_euler()
def clear_scene():
bpy.ops.object.select_all(action="SELECT")
bpy.ops.object.delete(use_global=False)
for collection in list(bpy.data.collections):
if collection.name != "Collection" and collection.users == 0:
bpy.data.collections.remove(collection)
def configure_scene():
scene = bpy.context.scene
scene.render.engine = "BLENDER_EEVEE_NEXT"
scene.render.resolution_x = 1200
scene.render.resolution_y = 900
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.film_transparent = False
scene.world.color = (0.055, 0.075, 0.095)
scene.view_settings.look = "AgX - Medium High Contrast"
def configure_default_viewport():
workspace = bpy.data.workspaces.get("Layout")
if workspace:
try:
bpy.context.window.workspace = workspace
except (AttributeError, RuntimeError):
pass
for screen in bpy.data.screens:
for area in screen.areas:
if area.type != "VIEW_3D":
continue
space = area.spaces.active
space.shading.type = "MATERIAL"
space.shading.light = "STUDIO"
space.shading.color_type = "MATERIAL"
space.overlay.show_floor = False
if space.region_3d:
space.region_3d.view_perspective = "CAMERA"
space.region_3d.view_camera_zoom = 0.0
def build(args):
bounds, ways, point_features = parse_osm(args["osm"])
projector = Projector(bounds)
clear_scene()
configure_scene()
ground_c = new_collection("00_Ground")
water_c = new_collection("01_Water")
green_c = new_collection("02_Green")
roads_c = new_collection("03_Roads")
buildings_c = new_collection("04_Buildings")
props_c = new_collection("05_Props")
ground_mat = material_from_spec(catalog.MATERIALS["ground"])
water_mat = material_from_spec(catalog.MATERIALS["water"])
grass_mat = material_from_spec(catalog.MATERIALS["grass"])
scrub_mat = material_from_spec(catalog.MATERIALS["scrub"])
# Ordering note: the tuft import creates its own materials, so it stays
# between the ground materials and the props. Material creation order fixes
# the material indices in the exported GLB.
tuft_variants = load_tuft_variants()
scrub_bush_variant = load_scrub_bush_variant()
fountain_mats = {
key: material_from_spec(catalog.MATERIALS[key])
for key in ("fountain_stone", "fountain_water", "fountain_spray")
}
building_mats = {
key: material_from_spec(catalog.MATERIALS["building_" + key])
for key in ("default", "industrial", "office_roof", "industrial_roof",
"glass", "factory_glass")
}
road_mats = {
layer["id"]: material_from_spec(spec)
for layer, spec in zip(catalog.ROAD_LAYERS, catalog.road_material_specs())
}
b = bounds
scene_xmin, scene_ymin = projector.xy((b["min_lon"], b["min_lat"]))
scene_xmax, scene_ymax = projector.xy((b["max_lon"], b["max_lat"]))
ground_ring = [projector.xy((b["min_lon"] - 0.0012, b["min_lat"] - 0.0012)),
projector.xy((b["max_lon"] + 0.0012, b["min_lat"] - 0.0012)),
projector.xy((b["max_lon"] + 0.0012, b["max_lat"] + 0.0012)),
projector.xy((b["min_lon"] - 0.0012, b["max_lat"] + 0.0012))]
ground_batch = MeshBatch("Ground Plane", ground_c, ground_mat)
ground_batch.add_polygon(ground_ring, -0.35)
ground_batch.finish()
grass_rings = []
scrub_trees = []
tree_rows = []
# Counters were previously individual ints scattered through the loop body.
# Collecting them into a dict lets the scene[...] and SCENE_DONE sections
# read from a single place. The keys are kept alphabetically so the
# SCENE_DONE JSON order from control-1 stays byte-for-byte identical.
counts = {
"building_count": 0,
"fountain_count": 0,
"grass_count": 0,
"grass_tuft_count": 0,
"industrial_count": 0,
"lake_count": 0,
"scrub_bush_count": 0,
"scrub_count": 0,
"scrub_tree_count": 0,
}
def add_scrub_patch_with_bushes(name, ring, ground_material, collection):
obj, bush_count = add_scrub_patch(
name, ring, ground_material, collection, scrub_bush_variant)
counts["scrub_bush_count"] += bush_count
return obj
focus_points = []
for way in ways:
coords = way["coords"]
if not any(projector.inside(c) for c in coords):
continue
ring = projector.ring(coords)
tag = way["tags"]
if tag.get("natural") == "water" or tag.get("water") == "lake":
counts["lake_count"] += _water.assemble(ring, scene_xmin, scene_xmax,
scene_ymin, scene_ymax,
water_c, water_mat)
elif tag.get("landuse") == "grass":
added, tufts, ring_pts = _grass.assemble(
ring, way["id"], scene_xmin, scene_xmax, scene_ymin, scene_ymax,
green_c, grass_mat, tuft_variants, add_grass_tufts)
counts["grass_count"] += added
counts["grass_tuft_count"] += tufts
if ring_pts:
grass_rings.append(ring_pts)
focus_points.extend(ring_pts)
elif tag.get("natural") == "scrub" and len(ring) >= 3:
added, ring_pts = _scrub.assemble(ring, way["id"], scene_xmin, scene_xmax,
scene_ymin, scene_ymax, green_c, scrub_mat,
add_scrub_patch_with_bushes)
counts["scrub_count"] += added
if ring_pts:
focus_points.extend(ring_pts)
new_scrub_trees = sample_scrub_interior_trees(ring_pts, way["id"])
scrub_trees.extend(new_scrub_trees)
counts["scrub_tree_count"] += len(new_scrub_trees)
elif tag.get("natural") == "tree_row":
tree_rows.append((ring, tag))
focus_points.extend(ring)
elif "building" in tag and len(ring) >= 3:
added, ind_added, ring_pts = _assemble_building(
ring, str(way["id"]), tag, args, buildings_c, building_mats)
counts["building_count"] += added
counts["industrial_count"] += ind_added
if ring_pts:
focus_points.extend(ring_pts)
geojson_dir = args.get("geojson")
road_counts = {}
if geojson_dir and os.path.isdir(geojson_dir):
for problem in catalog.check_layers(geojson_dir):
print("Layer catalog warning:", problem)
for layer in catalog.ROAD_LAYERS:
layer_id = layer["id"]
road_counts[layer_id] = add_geojson_layer(
os.path.join(geojson_dir, layer_id + ".geojson"), layer_id,
projector, roads_c, road_mats[layer_id], layer["z"])
if road_counts.get("road_surface", 0) == 0:
for way in ways:
highway = way["tags"].get("highway")
if highway and len(way["coords"]) >= 2:
width = {"secondary": 7.0, "residential": 5.5, "service": 3.5}.get(highway, 4.0)
add_polyline("OSM_Road_" + str(way["id"]), way["coords"], projector,
roads_c, road_mats["road_surface"], width, 0.03)
trees = []
individual_tree_count = 0
for feature in point_features:
if feature["tags"].get("natural") != "tree":
continue
if not projector.inside(feature["coord"]):
continue
x, y = projector.xy(feature["coord"])
trees.append((x, y, parse_height(feature["tags"], 5.5)))
individual_tree_count += 1
trees.extend(scrub_trees)
row_tree_count = 0
for row, row_tags in tree_rows:
row_samples = sample_tree_row(row, spacing=5.0,
height=parse_height(row_tags, 5.0))
trees.extend(row_samples)
row_tree_count += len(row_samples)
tree_style = args.get("tree_style")
tree_style_used = tree_style
if trees:
# A model style returns 0 when its vendored asset is missing; that drops
# through to "natural" so a clean checkout still gets trees.
placed = (_tree.assemble(trees, props_c, tree_style)
if tree_style in _tree.MODEL_STYLES else 0)
if not placed:
tree_style_used = "procedural" if tree_style == "procedural" else "natural"
tree_trunk = material_from_spec(catalog.MATERIALS["tree_trunk"])
if tree_style_used == "procedural":
add_tree_batch(
trees, props_c, tree_trunk,
material_from_spec(catalog.MATERIALS["tree_crown"]))
else:
add_natural_tree_instances(
trees, props_c, tree_trunk,
material_from_spec(catalog.MATERIALS["tree_crown_dark"]),
material_from_spec(catalog.MATERIALS["tree_crown_light"]))
for feature in point_features:
if feature["tags"].get("amenity") != "fountain":
continue
if not projector.inside(feature["coord"]):
continue
fx, fy = projector.xy(feature["coord"])
add_fountain("Fountain_" + str(feature["id"]), fx, fy,
props_c, fountain_mats)
counts["fountain_count"] += 1
bpy.ops.object.light_add(type="SUN", location=(0, 0, 500))
sun = bpy.context.object
sun.name = "Sun"
sun.data.energy = 3.0
sun.rotation_euler = (math.radians(28), math.radians(-22), math.radians(-32))
bpy.ops.object.light_add(type="AREA", location=(0, -220, 420))
area = bpy.context.object
area.name = "Fill Light"
area.data.energy = 1700
area.data.shape = "DISK"
area.data.size = 260
look_at(area, (0, 0, 0))
width = (b["max_lon"] - b["min_lon"]) * projector.m_per_lon
height = (b["max_lat"] - b["min_lat"]) * projector.m_per_lat
if focus_points:
min_fx = min(point[0] for point in focus_points)
max_fx = max(point[0] for point in focus_points)
min_fy = min(point[1] for point in focus_points)
max_fy = max(point[1] for point in focus_points)
focus_x = (min_fx + max_fx) / 2
focus_y = (min_fy + max_fy) / 2
focus_span = max(max_fx - min_fx, (max_fy - min_fy) * 1.25)
cam_location = (focus_x + focus_span * 0.78,
focus_y - focus_span * 0.92,
focus_span * 1.22)
camera_target = (focus_x, focus_y, 3)
else:
cam_location = (width * 0.78, -height * 1.15, max(width, height) * 1.22)
camera_target = (0, 0, 3)
bpy.ops.object.camera_add(location=cam_location)
camera = bpy.context.object
camera.name = "Scene Overview Camera"
camera.data.lens = 48
camera.data.clip_start = 0.1
camera.data.clip_end = 5000.0
look_at(camera, camera_target)
bpy.context.scene.camera = camera
configure_default_viewport()
scene = bpy.context.scene
scene.render.filepath = args["render"]
scene["source_osm"] = args["osm"]
scene["source_geojson"] = geojson_dir or ""
scene["osm_bounds"] = json.dumps(bounds, ensure_ascii=True)
scene["building_count"] = counts["building_count"]
scene["industrial_building_count"] = counts["industrial_count"]
scene["office_override_way_ids"] = json.dumps(sorted(args["office_overrides"]))
scene["lake_count"] = counts["lake_count"]
scene["grass_count"] = counts["grass_count"]
scene["grass_tuft_count"] = counts["grass_tuft_count"]
scene["scrub_count"] = counts["scrub_count"]
scene["scrub_bush_count"] = counts["scrub_bush_count"]
scene["scrub_tree_count"] = counts["scrub_tree_count"]
scene["fountain_count"] = counts["fountain_count"]
scene["tree_node_count"] = individual_tree_count
scene["tree_row_count"] = row_tree_count
scene["tree_count"] = len(trees)
scene["tree_style"] = tree_style
# Differs from tree_style when a model style's asset was missing.
scene["tree_style_used"] = tree_style_used
scene["road_feature_counts"] = json.dumps(road_counts, ensure_ascii=True)
os.makedirs(os.path.dirname(args["output"]), exist_ok=True)
os.makedirs(os.path.dirname(args["render"]), exist_ok=True)
try:
bpy.ops.file.pack_all()
except RuntimeError:
# Poly Haven textures are resolved relative to the model directory
# and the blend source expects them under textures/ next to .blend.
# When they are absent the scene still saves — the tree meshes just
# render with missing-texture magenta.
print("Some external resources could not be packed; saving anyway")
bpy.ops.wm.save_as_mainfile(filepath=args["output"])
bpy.ops.render.render(write_still=True)
print("SCENE_DONE", json.dumps({"output": args["output"],
"render": args["render"],
"buildings": counts["building_count"],
"industrial_buildings": counts["industrial_count"],
"lake": counts["lake_count"],
"grass": counts["grass_count"],
"grass_tufts": counts["grass_tuft_count"],
"scrub": counts["scrub_count"],
"scrub_bushes": counts["scrub_bush_count"],
"scrub_trees": counts["scrub_tree_count"],
"fountains": counts["fountain_count"],
"tree_nodes": individual_tree_count,
"tree_row_instances": row_tree_count,
"trees": len(trees),
"tree_style": tree_style_used,
"road_features": road_counts}, ensure_ascii=True))
if __name__ == "__main__":
build(cli_args())
+12
View File
@@ -0,0 +1,12 @@
"""Reusable pieces of the OSM → Blender/Cesium asset pipeline.
The package is split by dependency, not by feature:
- `osm` and `geom` are pure Python. They import no `bpy` and can be run and
tested with a plain interpreter (`python3 -m unittest discover blender/tests`).
- everything else may touch `bpy` and only runs inside Blender.
Keeping that line sharp is what makes the geometry testable at all; before the
split it was interleaved with scene construction and could only be exercised by
rendering a whole area.
"""
+195
View File
@@ -0,0 +1,195 @@
"""Single source of truth for the scene's road layers and materials.
Before this module the same facts lived in several places at once: the nine
osm2streets layers had their draw order in `scripts/lib/scene-layers.js`, their
Blender heights in a `layer_z` dict, and their colours in a `road_mats` dict —
three copies across two languages, kept in sync by hand. Everything the scene
builder needs is now declared here, once.
Two deliberate non-goals:
- The colours here are NOT derived from `scene-layers.js`. That file's `fill`
values are QGIS sRGB hex for a 2D debug map; these are linear Blender base
colours for a 3D scene, and the two were tuned separately. `check_layers`
cross-checks the layer *set and order* — the part that must agree — and
leaves the palettes alone.
- Order is load-bearing. Material creation order fixes the material indices in
the exported GLB, and layer order fixes mesh creation order, so both lists
are sequences, not dicts, and appending is the only safe edit.
"""
import json
import os
# Draw order, bottom first. `z` is the Blender height in metres that keeps the
# markings above the asphalt without z-fighting; `id` matches the GeoJSON file
# stem written by the intermediates stage.
ROAD_LAYERS = [
{"id": "road_surface", "material": "Road Asphalt",
"color": (0.055, 0.065, 0.070), "z": 0.03},
{"id": "intersection_surface", "material": "Intersection Asphalt",
"color": (0.065, 0.075, 0.080), "z": 0.035},
{"id": "sidewalks", "material": "Sidewalk",
"color": (0.49, 0.51, 0.49), "z": 0.065},
{"id": "sidewalk_corners", "material": "Sidewalk Corner",
"color": (0.49, 0.51, 0.49), "z": 0.067},
{"id": "lane_separators", "material": "Lane Separator",
"color": (0.85, 0.84, 0.72), "z": 0.090},
{"id": "center_lines", "material": "Center Line",
"color": (0.94, 0.58, 0.06), "z": 0.092},
{"id": "crosswalks", "material": "Crosswalk",
"color": (0.95, 0.94, 0.82), "z": 0.094},
{"id": "vehicle_stop_lines", "material": "Stop Line",
"color": (0.95, 0.94, 0.82), "z": 0.096},
{"id": "lane_arrows_webscale", "material": "Lane Arrow",
"color": (0.95, 0.94, 0.82), "z": 0.098},
]
SCENE_STYLE_FILE = "osm2streets_scene_style.json"
# Material specs. `kind` selects the builder:
# solid — flat base colour
# textured — Poly Haven diffuse + normal, optionally tinted
# `procedural` adds noise-driven base colour and bump on top of a solid.
MATERIALS = {
"ground": {"kind": "solid", "name": "Ground", "color": (0.27, 0.32, 0.24)},
"water": {"kind": "solid", "name": "Lake Water", "color": (0.035, 0.22, 0.30),
"roughness": 0.18, "metallic": 0.05},
"grass": {"kind": "textured", "name": "Grass",
"diffuse": "leafy_grass_diff_1k.jpg",
"normal": "leafy_grass_nor_gl_1k.jpg",
"roughness": 0.92, "scale": 7.0,
"tint": (0.12, 0.48, 0.08), "tint_factor": 0.72},
"scrub": {"kind": "textured", "name": "Scrub Ground Cover",
"diffuse": "leafy_grass_diff_1k.jpg",
"normal": "leafy_grass_nor_gl_1k.jpg",
"roughness": 0.96, "scale": 15.0,
"tint": (0.085, 0.30, 0.065), "tint_factor": 0.46},
"fountain_stone": {"kind": "solid", "name": "Fountain Stone",
"color": (0.42, 0.45, 0.43), "roughness": 0.72},
"fountain_water": {"kind": "solid", "name": "Fountain Water",
"color": (0.03, 0.32, 0.42), "roughness": 0.16,
"metallic": 0.05},
"fountain_spray": {"kind": "solid", "name": "Fountain Spray",
"color": (0.20, 0.70, 0.78), "roughness": 0.12,
"metallic": 0.02},
"building_default": {"kind": "textured", "name": "Office White Plaster Facade",
"diffuse": "white_plaster_02_diff_1k.jpg",
"normal": "white_plaster_02_nor_gl_1k.jpg",
"roughness": 0.82, "scale": 4.2, "metallic": 0.0,
"tint": (0.92, 0.94, 0.92), "tint_factor": 0.38},
"building_industrial": {"kind": "textured",
"name": "Industrial White Ribbed Facade",
"diffuse": "corrugated_iron_03_diff_1k.jpg",
"normal": "corrugated_iron_03_nor_gl_1k.jpg",
"roughness": 0.56, "scale": 2.4, "metallic": 0.16,
"tint": (0.86, 0.92, 0.94), "tint_factor": 0.68},
"building_office_roof": {"kind": "textured", "name": "Office Light Flat Roof",
"diffuse": "concrete_floor_02_diff_1k.jpg",
"normal": "concrete_floor_02_bump_1k.jpg",
"roughness": 0.84, "scale": 5.0,
"normal_is_bump": True,
"tint": (0.82, 0.86, 0.88), "tint_factor": 0.35},
"building_industrial_roof": {"kind": "textured",
"name": "Factory Blue Metal Roof",
"diffuse": "blue_metal_plate_diff_1k.jpg",
"normal": "blue_metal_plate_nor_gl_1k.jpg",
"roughness": 0.48, "scale": 3.4, "metallic": 0.28,
"tint": (0.03, 0.42, 0.78), "tint_factor": 0.45},
"building_glass": {"kind": "solid", "name": "Office Blue Gray Glass",
"color": (0.12, 0.20, 0.24), "roughness": 0.22,
"metallic": 0.10},
"building_factory_glass": {"kind": "solid", "name": "Factory Dark Windows",
"color": (0.10, 0.14, 0.15), "roughness": 0.28,
"metallic": 0.08},
"tree_trunk": {"kind": "textured", "name": "Tree Trunk",
"diffuse": "bark_brown_01_diff_1k.jpg",
"normal": "bark_brown_01_nor_gl_1k.jpg",
"roughness": 0.92, "scale": 5.0},
"tree_crown_dark": {"kind": "solid", "name": "Tree Crown Dark",
"color": (0.065, 0.25, 0.055), "roughness": 0.90,
"procedural": {"colors": ((0.035, 0.14, 0.035),
(0.12, 0.36, 0.08)),
"scale": 3.2, "detail": 3.8,
"bump_strength": 0.08},
"cesium": {"tint": ((0.06, 0.22, 0.05), 0.18)}},
"tree_crown_light": {"kind": "solid", "name": "Tree Crown Light",
"color": (0.13, 0.42, 0.09), "roughness": 0.88,
"procedural": {"colors": ((0.07, 0.25, 0.05),
(0.22, 0.56, 0.13)),
"scale": 3.6, "detail": 3.4,
"bump_strength": 0.07},
"cesium": {"tint": ((0.16, 0.42, 0.09), 0.16)}},
"tree_crown": {"kind": "solid", "name": "Tree Crown",
"color": (0.10, 0.36, 0.08), "roughness": 0.88,
"procedural": {"colors": ((0.04, 0.18, 0.04),
(0.18, 0.50, 0.12)),
"scale": 2.8, "detail": 3.2,
"bump_strength": 0.10},
"cesium": {"tint": None,
"base_color": (0.11, 0.34, 0.075),
"emission": ((0.04, 0.11, 0.035), 0.02)}},
}
# Cesium-specific overrides that don't have a home in the material system yet:
# metallic overrides (flat values, not materials) and emission overrides for
# colours that export_cesium.py hand-tuned separately.
CESIUM_EXPORT = {
"metallic_overrides": {
"Office White Plaster Facade": 0.0,
"Industrial White Ribbed Facade": 0.08,
},
"emission_overrides": {
"Office White Plaster Facade": ((0.93, 0.94, 0.91), 0.18),
"Office Light Flat Roof": ((0.88, 0.90, 0.88), 0.14),
"Industrial White Ribbed Facade": ((0.90, 0.93, 0.91), 0.18),
"Factory Blue Metal Roof": ((0.08, 0.50, 0.88), 0.12),
},
}
def road_material_specs():
"""Road layer materials as MATERIALS-shaped specs, in draw order."""
return [{"kind": "solid", "name": layer["material"], "color": layer["color"]}
for layer in ROAD_LAYERS]
def check_layers(geojson_dir):
"""Warn when the intermediates stage and this catalog disagree on layers.
The style JSON is written next to the GeoJSON by the intermediates and
reimport stages. A layer added on the JS side but not here would be
silently dropped from the 3D scene, which is exactly the kind of drift the
single-source-of-truth split is meant to make loud. Warn rather than fail:
a stale or absent output directory should not block a rebuild.
"""
style_path = os.path.join(geojson_dir or "", SCENE_STYLE_FILE)
if not geojson_dir or not os.path.exists(style_path):
return []
try:
with open(style_path, "r", encoding="utf-8") as handle:
style = json.load(handle)
except (OSError, ValueError) as error:
return ["Could not read %s: %s" % (style_path, error)]
upstream = [entry.get("id") for entry in style.get("layers", [])]
local = [layer["id"] for layer in ROAD_LAYERS]
problems = []
for missing in [i for i in upstream if i not in local]:
problems.append(
"layer '%s' exists in %s but not in catalog.ROAD_LAYERS "
"(it will not reach the 3D scene)" % (missing, SCENE_STYLE_FILE))
for extra in [i for i in local if i not in upstream]:
problems.append(
"layer '%s' is in catalog.ROAD_LAYERS but not in %s "
"(no GeoJSON will be produced for it)" % (extra, SCENE_STYLE_FILE))
if not problems and upstream != local:
problems.append(
"layer draw order differs: %s produces %s, catalog stacks %s"
% (SCENE_STYLE_FILE, upstream, local))
return problems
+241
View File
@@ -0,0 +1,241 @@
"""Planar geometry helpers for the OSM → asset pipeline.
Pure Python: no `bpy`, so this runs and tests outside Blender. All functions
work in projected metres (see `osmassets.osm.Projector`) unless the name says
otherwise; `geometry_rings` and `feature_in_bounds` take raw GeoJSON and are the
two exceptions, operating on lon/lat.
Rings are lists of (x, y) tuples. A repeated closing point is tolerated
everywhere but never required.
"""
import math
def geometry_rings(geometry):
"""Exterior rings of a GeoJSON Polygon/MultiPolygon; holes are dropped."""
if not geometry:
return []
kind = geometry.get("type")
coordinates = geometry.get("coordinates", [])
if kind == "Polygon":
return coordinates[:1]
if kind == "MultiPolygon":
return [polygon[0] for polygon in coordinates if polygon]
return []
def feature_in_bounds(feature, projector):
"""True when any coordinate of the feature falls inside the padded bounds."""
def walk(value):
if isinstance(value, list) and value and isinstance(value[0], (int, float)):
return projector.inside(value)
return any(walk(v) for v in value) if isinstance(value, list) else False
return walk(feature.get("geometry", {}).get("coordinates", []))
def clip_polygon(ring, xmin, xmax, ymin, ymax):
"""Sutherland-Hodgman clip of a ring against an axis-aligned box."""
if len(ring) < 3:
return []
def clip_edge(points, inside, intersection):
if not points:
return []
result = []
previous = points[-1]
previous_inside = inside(previous)
for current in points:
current_inside = inside(current)
if current_inside != previous_inside:
result.append(intersection(previous, current))
if current_inside:
result.append(current)
previous = current
previous_inside = current_inside
return result
ring = clip_edge(
ring, lambda p: p[0] >= xmin,
lambda a, b: (xmin, a[1] + (b[1] - a[1]) * (xmin - a[0]) /
(b[0] - a[0]) if b[0] != a[0] else a[1]))
ring = clip_edge(
ring, lambda p: p[0] <= xmax,
lambda a, b: (xmax, a[1] + (b[1] - a[1]) * (xmax - a[0]) /
(b[0] - a[0]) if b[0] != a[0] else a[1]))
ring = clip_edge(
ring, lambda p: p[1] >= ymin,
lambda a, b: (a[0] + (b[0] - a[0]) * (ymin - a[1]) /
(b[1] - a[1]) if b[1] != a[1] else a[0], ymin))
ring = clip_edge(
ring, lambda p: p[1] <= ymax,
lambda a, b: (a[0] + (b[0] - a[0]) * (ymax - a[1]) /
(b[1] - a[1]) if b[1] != a[1] else a[0], ymax))
return ring
def sample_tree_row(points, spacing, height):
"""Evenly space (x, y, height) samples along a polyline.
The trailing point is appended only when the last regular sample stops well
short of it, so a row does not end in a double-planted tree.
"""
if len(points) < 2:
return []
samples = [(points[0][0], points[0][1], height)]
distance_until_next = spacing
for start, end in zip(points, points[1:]):
dx = end[0] - start[0]
dy = end[1] - start[1]
segment_length = math.hypot(dx, dy)
if segment_length == 0:
continue
while distance_until_next <= segment_length:
ratio = distance_until_next / segment_length
samples.append((start[0] + dx * ratio, start[1] + dy * ratio, height))
distance_until_next += spacing
distance_until_next -= segment_length
last = points[-1]
if math.hypot(samples[-1][0] - last[0], samples[-1][1] - last[1]) > spacing * 0.45:
samples.append((last[0], last[1], height))
return samples
def polygon_area(ring):
"""Unsigned shoelace area; 0.0 for degenerate rings."""
return abs(signed_polygon_area(ring))
def signed_polygon_area(ring):
"""Signed shoelace area; positive for counter-clockwise rings."""
if len(ring) < 3:
return 0.0
area = 0.0
for (x1, y1), (x2, y2) in zip(ring, ring[1:] + ring[:1]):
area += x1 * y2 - x2 * y1
return area * 0.5
def sample_ring_boundary(ring, spacing, inset=0.0, max_samples=None):
"""Evenly sample a closed ring's boundary.
Returns (x, y, angle, index) samples. ``angle`` follows the local edge
direction, and ``inset`` moves the sample toward the polygon interior.
"""
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3 or spacing <= 0.0:
return []
edges = []
perimeter = 0.0
winding = signed_polygon_area(ring)
for index, (start, end) in enumerate(zip(ring, ring[1:] + ring[:1])):
dx = end[0] - start[0]
dy = end[1] - start[1]
length = math.hypot(dx, dy)
if length <= 1e-9:
continue
ux = dx / length
uy = dy / length
# Counter-clockwise rings have their interior on the left side of each
# edge; clockwise rings have it on the right.
inward = (-uy, ux) if winding >= 0.0 else (uy, -ux)
edges.append((perimeter, start, ux, uy, length, inward, index))
perimeter += length
if not edges:
return []
count = max(1, int(perimeter / spacing))
if max_samples:
count = min(count, max_samples)
step = perimeter / count
samples = []
edge_cursor = 0
for sample_index in range(count):
target = (sample_index + 0.5) * step
while edge_cursor + 1 < len(edges) and (
edges[edge_cursor][0] + edges[edge_cursor][4] < target
):
edge_cursor += 1
edge_start, start, ux, uy, length, inward, _ = edges[edge_cursor]
along = max(0.0, min(length, target - edge_start))
x = start[0] + ux * along
y = start[1] + uy * along
sx = x + inward[0] * inset
sy = y + inward[1] * inset
if inset > 0.0 and not point_in_polygon((sx, sy), ring):
sx, sy = x, y
samples.append((sx, sy, math.atan2(uy, ux), sample_index))
return samples
def sample_polygon_interior(ring, spacing, edge_clearance=0.0, max_samples=None,
seed=0):
"""Jittered interior samples for sparse planting inside a polygon."""
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3 or spacing <= 0.0 or polygon_area(ring) <= 1e-9:
return []
xmin = min(x for x, _ in ring)
xmax = max(x for x, _ in ring)
ymin = min(y for _, y in ring)
ymax = max(y for _, y in ring)
cols = max(1, int(math.ceil((xmax - xmin) / spacing)))
rows = max(1, int(math.ceil((ymax - ymin) / spacing)))
samples = []
for col in range(cols):
for row in range(rows):
sample_seed = ((col + 1) * 73856093) ^ ((row + 1) * 19349663) ^ seed
jx = ((sample_seed * 0.61803398875) % 1.0 - 0.5) * spacing * 0.7
jy = ((sample_seed * 0.41421356237) % 1.0 - 0.5) * spacing * 0.7
x = xmin + (col + 0.5) * spacing + jx
y = ymin + (row + 0.5) * spacing + jy
if not point_in_polygon((x, y), ring):
continue
if edge_clearance > 0.0 and distance_to_ring((x, y), ring) < edge_clearance:
continue
samples.append((x, y, sample_seed))
if max_samples and len(samples) > max_samples:
samples.sort(key=lambda item: (item[2] * 0.754877666) % 1.0)
samples = samples[:max_samples]
return samples
def point_in_polygon(point, ring):
x, y = point
inside = False
j = len(ring) - 1
for i, (xi, yi) in enumerate(ring):
xj, yj = ring[j]
crosses = ((yi > y) != (yj > y))
if crosses:
x_at_y = (xj - xi) * (y - yi) / (yj - yi) + xi
if x < x_at_y:
inside = not inside
j = i
return inside
def distance_to_ring(point, ring):
"""Shortest distance from a point to the ring's edges (not its interior)."""
px, py = point
best = float("inf")
count = len(ring)
for index in range(count):
ax, ay = ring[index]
bx, by = ring[(index + 1) % count]
dx = bx - ax
dy = by - ay
length_sq = dx * dx + dy * dy
if length_sq <= 1e-9:
distance = math.hypot(px - ax, py - ay)
else:
t = ((px - ax) * dx + (py - ay) * dy) / length_sq
t = max(0.0, min(1.0, t))
distance = math.hypot(px - (ax + t * dx), py - (ay + t * dy))
if distance < best:
best = distance
return best
+22
View File
@@ -0,0 +1,22 @@
"""Grass feature assembly (`landuse=grass`) with optional tuft scattering."""
from osmassets.geom import clip_polygon
from osmassets.mesh import MeshBatch
def assemble(ring, way_id, scene_xmin, scene_xmax, scene_ymin, scene_ymax,
green_c, grass_mat, tuft_variants, add_grass_tufts):
ring = clip_polygon(ring, scene_xmin, scene_xmax, scene_ymin, scene_ymax)
name = "Grass_" + str(way_id)
focus = list(ring)
if len(ring) < 3:
return 0, 0, focus
batch = MeshBatch(name, green_c, grass_mat)
batch.add_polygon(ring, 0.015)
obj = batch.finish()
tufts = 0
if tuft_variants:
tufts = add_grass_tufts(name, ring, tuft_variants, green_c)
if obj:
obj["grass_tufts"] = tufts
return 1, tufts, focus
+218
View File
@@ -0,0 +1,218 @@
"""Blender material construction.
Requires `bpy`; only runs inside Blender. The catalog (`osmassets.catalog`)
declares *what* a material is, this module builds it — that split is what keeps
the catalog importable by plain Python, and by anything else that wants to read
the scene's material definitions without launching Blender.
"""
import os
import bpy
TEXTURE_ROOT = os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "..",
"assets", "textures", "polyhaven"
))
def principled_bsdf(material):
if not material.use_nodes:
return None
for node in material.node_tree.nodes:
if node.type == "BSDF_PRINCIPLED":
return node
return None
def make_material(name, color, roughness=0.8, metallic=0.0):
material = bpy.data.materials.get(name) or bpy.data.materials.new(name)
material.diffuse_color = (*color, 1.0)
material.use_nodes = True
bsdf = principled_bsdf(material)
if bsdf:
bsdf.inputs["Base Color"].default_value = (*color, 1.0)
bsdf.inputs["Roughness"].default_value = roughness
bsdf.inputs["Metallic"].default_value = metallic
return material
def add_procedural_surface(material, colors, scale=2.0, detail=2.0, bump_strength=0.08,
object_space=False):
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = principled_bsdf(material)
if not bsdf:
return
noise = nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = scale
noise.inputs["Detail"].default_value = detail
noise.inputs["Roughness"].default_value = 0.65
texcoord = nodes.new("ShaderNodeTexCoord")
ramp = nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (*colors[0], 1.0)
ramp.color_ramp.elements[1].color = (*colors[1], 1.0)
bump = nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = bump_strength
bump.inputs["Distance"].default_value = 0.12
# "Generated" normalises across the object bounding box, so on a mesh that
# spans the whole scene the noise stretches to tens of metres and vanishes.
# Object space keeps the scale in metres, which is what foliage needs.
source = "Object" if object_space else "Generated"
links.new(texcoord.outputs[source], noise.inputs["Vector"])
links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
links.new(noise.outputs["Fac"], bump.inputs["Height"])
links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])
def tint_base_color(material, tint, factor):
"""Mix an existing material's base colour toward `tint`.
Imported assets arrive with their own diffuse texture wired up. Rather than
replacing it — which throws away the leaf detail — this splices a mix node
in front of the Base Color input so the texture survives at (1 - factor).
"""
if factor <= 0.0 or not material.use_nodes:
return
bsdf = principled_bsdf(material)
if not bsdf:
return
nodes = material.node_tree.nodes
links = material.node_tree.links
base = bsdf.inputs["Base Color"]
tint_node = nodes.new("ShaderNodeRGB")
tint_node.outputs["Color"].default_value = (*tint, 1.0)
mix = nodes.new("ShaderNodeMixRGB")
mix.blend_type = "MIX"
mix.inputs["Fac"].default_value = factor
if base.is_linked:
# Capture the upstream socket before relinking; Blender drops the old
# link as soon as the input takes a new one.
links.new(base.links[0].from_socket, mix.inputs[1])
else:
mix.inputs[1].default_value = base.default_value
links.new(tint_node.outputs["Color"], mix.inputs[2])
links.new(mix.outputs["Color"], base)
def make_textured_material(name, diffuse_file, normal_file, roughness,
scale, normal_is_bump=False, metallic=0.0,
tint=None, tint_factor=0.0):
diffuse_path = os.path.join(TEXTURE_ROOT, diffuse_file)
normal_path = os.path.join(TEXTURE_ROOT, normal_file)
if not os.path.exists(diffuse_path) or not os.path.exists(normal_path):
return make_material(name, (0.5, 0.5, 0.5), roughness, metallic)
material = make_material(name, (0.5, 0.5, 0.5), roughness, metallic)
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = principled_bsdf(material)
if not bsdf:
return material
texcoord = nodes.new("ShaderNodeTexCoord")
mapping = nodes.new("ShaderNodeMapping")
mapping.inputs["Scale"].default_value = (scale, scale, scale)
diffuse = nodes.new("ShaderNodeTexImage")
diffuse.image = bpy.data.images.load(diffuse_path, check_existing=True)
diffuse.extension = "REPEAT"
normal = nodes.new("ShaderNodeTexImage")
normal.image = bpy.data.images.load(normal_path, check_existing=True)
normal.image.colorspace_settings.name = "Non-Color"
normal.extension = "REPEAT"
links.new(texcoord.outputs["Generated"], mapping.inputs["Vector"])
links.new(mapping.outputs["Vector"], diffuse.inputs["Vector"])
links.new(mapping.outputs["Vector"], normal.inputs["Vector"])
if tint and tint_factor > 0.0:
tint_node = nodes.new("ShaderNodeRGB")
tint_node.outputs["Color"].default_value = (*tint, 1.0)
mix = nodes.new("ShaderNodeMixRGB")
mix.blend_type = "MIX"
mix.inputs["Fac"].default_value = tint_factor
links.new(diffuse.outputs["Color"], mix.inputs[1])
links.new(tint_node.outputs["Color"], mix.inputs[2])
links.new(mix.outputs["Color"], bsdf.inputs["Base Color"])
else:
links.new(diffuse.outputs["Color"], bsdf.inputs["Base Color"])
if normal_is_bump:
bump = nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = 0.22
bump.inputs["Distance"].default_value = 0.12
links.new(normal.outputs["Color"], bump.inputs["Height"])
links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])
else:
normal_map = nodes.new("ShaderNodeNormalMap")
normal_map.inputs["Strength"].default_value = 0.52
links.new(normal.outputs["Color"], normal_map.inputs["Color"])
links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"])
return material
def link_alpha_clip(material, alpha_output, bsdf, cutoff=0.5):
"""Wire a texture's alpha into `bsdf` as a hard cut-out.
The obvious wiring — alpha straight into the Alpha socket — is wrong for
anything destined for glTF. Blender 4.2 stopped deriving a material's
alpha mode from `blend_method` (still writable, now a no-op: setting 'CLIP'
reads back 'HASHED') and made the exporter infer it from the node tree
instead. It recognises exactly a few shapes; a bare link is not one of
them, and falls through to alphaMode=BLEND. Foliage exported as BLEND
makes Cesium depth-sort thousands of leaf quads it cannot order correctly.
So build the shape the exporter looks for — `1 - (alpha < cutoff)` — which
it reads back as alphaMode=MASK with this cutoff. EEVEE gets the same
thing for free: alpha is 0 or 1 by the time it reaches the BSDF, so the
viewport shows the crisp cut-out Cesium will, not a dithered approximation.
See the exporter's `detect_alpha_clip` in
scripts/addons_core/io_scene_gltf2/blender/exp/material/search_node_tree.py.
"""
nodes = material.node_tree.nodes
links = material.node_tree.links
less_than = nodes.new("ShaderNodeMath")
less_than.operation = "LESS_THAN"
less_than.location = (-60, 320)
less_than.inputs[1].default_value = cutoff
invert = nodes.new("ShaderNodeMath")
invert.operation = "SUBTRACT"
invert.location = (110, 320)
invert.inputs[0].default_value = 1.0
links.new(alpha_output, less_than.inputs[0])
links.new(less_than.outputs["Value"], invert.inputs[1])
links.new(invert.outputs["Value"], bsdf.inputs["Alpha"])
# EEVEE Next takes its cut-out handling from surface_render_method, not
# from blend_method. 'DITHERED' still casts a leaf-shaped shadow;
# 'BLENDED' does not.
material.surface_render_method = "DITHERED"
material.alpha_threshold = cutoff
# Leaf cards are single-sided quads seen from both sides; culling
# backfaces would empty out half of every crown.
material.use_backface_culling = False
def from_spec(spec):
"""Build a material from a `catalog.MATERIALS` entry."""
if spec["kind"] == "textured":
return make_textured_material(
spec["name"], spec["diffuse"], spec["normal"],
roughness=spec.get("roughness", 0.8), scale=spec["scale"],
normal_is_bump=spec.get("normal_is_bump", False),
metallic=spec.get("metallic", 0.0),
tint=spec.get("tint"), tint_factor=spec.get("tint_factor", 0.0))
material = make_material(spec["name"], spec["color"],
spec.get("roughness", 0.8),
spec.get("metallic", 0.0))
procedural = spec.get("procedural")
if procedural:
add_procedural_surface(material, procedural["colors"],
scale=procedural["scale"],
detail=procedural["detail"],
bump_strength=procedural["bump_strength"],
object_space=procedural.get("object_space", False))
return material
+126
View File
@@ -0,0 +1,126 @@
"""Mesh and collection construction for the Blender scene.
Requires `bpy`; only runs inside Blender.
`MeshBatch` is the workhorse: most of the scene is flat polygons and extruded
prisms, and batching them into one mesh datablock per logical group keeps the
object count (and the glTF node count) down. Callers accumulate geometry and
call `finish()` once.
"""
import math
import bpy
def new_collection(name):
collection = bpy.data.collections.new(name)
bpy.context.scene.collection.children.link(collection)
return collection
def link_object_to_collection(obj, collection):
for current in list(obj.users_collection):
current.objects.unlink(obj)
collection.objects.link(obj)
class MeshBatch:
"""Accumulates polygons/prisms into a single mesh object."""
def __init__(self, name, collection, material):
self.name = name
self.collection = collection
self.material = material
self.vertices = []
self.faces = []
def add_polygon(self, ring, z):
if len(ring) < 3:
return
if ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3:
return
start = len(self.vertices)
self.vertices.extend((x, y, z) for x, y in ring)
self.faces.append(tuple(range(start, start + len(ring))))
def add_prism(self, ring, base, height):
if len(ring) < 3:
return
if ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3:
return
start = len(self.vertices)
self.vertices.extend((x, y, base) for x, y in ring)
self.vertices.extend((x, y, base + height) for x, y in ring)
n = len(ring)
self.faces.append(tuple(range(start, start + n)))
self.faces.append(tuple(range(start + n, start + 2 * n)))
for i in range(n):
j = (i + 1) % n
self.faces.append((start + i, start + j, start + n + j, start + n + i))
def finish(self):
if not self.vertices:
return None
mesh = bpy.data.meshes.new(self.name + "Mesh")
mesh.from_pydata(self.vertices, [], self.faces)
mesh.materials.append(self.material)
# Foliage reads as blobby volume, so it wants smooth normals; the built
# environment wants its facets. The name prefix is the discriminator.
if self.name.startswith("Tree_") or self.name.startswith("Scrub_"):
for polygon in mesh.polygons:
polygon.use_smooth = True
mesh.update()
obj = bpy.data.objects.new(self.name, mesh)
self.collection.objects.link(obj)
return obj
def make_prism(name, ring, base, height, material, collection):
batch = MeshBatch(name, collection, material)
batch.add_prism(ring, base, height)
return batch.finish()
def add_roof(name, ring, z, material, collection):
batch = MeshBatch(name + "_Roof", collection, material)
batch.add_polygon(ring, z)
return batch.finish()
def add_wall_panel(batch, start, end, base, height, thickness=0.045, inset=0.08):
"""Add a thin inset slab along a facade edge, used for window bands."""
dx, dy = end[0] - start[0], end[1] - start[1]
length = math.hypot(dx, dy)
if length < 3.0:
return
ux, uy = dx / length, dy / length
a = (start[0] + dx * inset, start[1] + dy * inset)
b = (end[0] - dx * inset, end[1] - dy * inset)
nx, ny = -uy * thickness / 2, ux * thickness / 2
panel = [(a[0] + nx, a[1] + ny), (b[0] + nx, b[1] + ny),
(b[0] - nx, b[1] - ny), (a[0] - nx, a[1] - ny)]
batch.add_prism(panel, base, height)
def add_polyline(name, coords, projector, collection, material, width, z):
"""Bevelled curve along lon/lat coordinates; the OSM highway road fallback."""
points = [projector.xy(c) for c in coords]
if len(points) < 2:
return
curve = bpy.data.curves.new(name, "CURVE")
curve.dimensions = "3D"
curve.resolution_u = 1
curve.bevel_depth = width / 2
curve.bevel_resolution = 1
spline = curve.splines.new("POLY")
spline.points.add(len(points) - 1)
for point, (x, y) in zip(spline.points, points):
point.co = (x, y, z, 1)
obj = bpy.data.objects.new(name, curve)
collection.objects.link(obj)
obj.data.materials.append(material)
+89
View File
@@ -0,0 +1,89 @@
"""OSM XML parsing and the local metric projection.
Pure Python: no `bpy`, so this runs and tests outside Blender.
"""
import math
import xml.etree.ElementTree as ET
def tags(element):
return {t.attrib.get("k", ""): t.attrib.get("v", "")
for t in element.findall("tag")}
def parse_osm(path):
root = ET.parse(path).getroot()
bounds_node = root.find("bounds")
if bounds_node is None:
raise RuntimeError("OSM file does not contain a bounds element")
bounds = {"min_lon": float(bounds_node.attrib["minlon"]),
"min_lat": float(bounds_node.attrib["minlat"]),
"max_lon": float(bounds_node.attrib["maxlon"]),
"max_lat": float(bounds_node.attrib["maxlat"])}
nodes = {}
point_features = []
for node in root.findall("node"):
try:
node_id = int(node.attrib["id"])
coord = (float(node.attrib["lon"]), float(node.attrib["lat"]))
node_tags = tags(node)
nodes[node_id] = coord
if node_tags:
point_features.append({"id": node.attrib.get("id", ""),
"coord": coord, "tags": node_tags})
except (KeyError, ValueError):
continue
ways = []
for way in root.findall("way"):
if way.attrib.get("action") == "delete":
continue
refs = []
for ref in way.findall("nd"):
try:
refs.append(int(ref.attrib["ref"]))
except (KeyError, ValueError):
pass
coords = [nodes[r] for r in refs if r in nodes]
if len(coords) >= 2:
ways.append({"id": way.attrib.get("id", ""),
"coords": coords, "tags": tags(way)})
return bounds, ways, point_features
def parse_height(feature_tags, default):
try:
return max(0.5, float(feature_tags.get("height", default)))
except ValueError:
return default
class Projector:
"""Equirectangular projection about the centre of the OSM bounds.
Output is metres in a local ENU frame (X east, Y north), which is what both
the Blender scene and the Cesium GLB are authored in.
"""
def __init__(self, bounds):
self.bounds = bounds
self.lon0 = (bounds["min_lon"] + bounds["max_lon"]) / 2
self.lat0 = (bounds["min_lat"] + bounds["max_lat"]) / 2
self.m_per_lat = 111320.0
self.m_per_lon = 111320.0 * math.cos(math.radians(self.lat0))
def xy(self, lon_lat):
lon, lat = lon_lat
return ((lon - self.lon0) * self.m_per_lon,
(lat - self.lat0) * self.m_per_lat)
def inside(self, lon_lat, pad=0.00035):
lon, lat = lon_lat
b = self.bounds
return (b["min_lon"] - pad <= lon <= b["max_lon"] + pad and
b["min_lat"] - pad <= lat <= b["max_lat"] + pad)
def ring(self, coords):
return [self.xy(c) for c in coords]
+13
View File
@@ -0,0 +1,13 @@
"""Scrub feature assembly (`natural=scrub`). Flat ground cover only."""
from osmassets.geom import clip_polygon
def assemble(ring, way_id, scene_xmin, scene_xmax, scene_ymin, scene_ymax,
green_c, scrub_mat, add_scrub_patch_fn):
ring = clip_polygon(ring, scene_xmin, scene_xmax, scene_ymin, scene_ymax)
focus = list(ring)
if len(ring) < 3:
return 0, focus
add_scrub_patch_fn("Scrub_" + str(way_id), ring, scrub_mat, green_c)
return 1, focus
+318
View File
@@ -0,0 +1,318 @@
"""Instanced tree assets — the model side of `--tree-style`.
Two vendored models, reduced to one runtime shape: import once, bake the source
object's orientation into a mesh copy, measure it, then link one lightweight
object per tree that reuses that datablock. Nothing is duplicated per tree, so
the .blend and the exported GLB carry each mesh and each texture exactly once
no matter how many trees are planted.
apple SpeedTree Red Delicious, 4.5k tris, alpha-cut leaf cards
fattree low-poly cartoon tree, 2.2k tris, opaque geometry
Materials are rebuilt here rather than taken from the source files, because
neither arrives usable. 57% of the apple's colour texture is transparent —
those are leaf cards, and without an alpha-clipped setup the crown renders as a
solid ball of intersecting quads. fattree ships a bare Diffuse BSDF and a
texture path that only resolves next to the original .blend.
A third style, `polyhaven`, used to live here. It appended what the Poly Haven
island_tree_01 file calls its LOD1 objects, but those are not whole trees: the
branch parts are 0.4-unit twigs and the leaf parts are flat clusters hanging
below their own origin, both meant to be scattered by the geometry-nodes setup
in that file. Planting them directly gave twigs, which is what sent us looking
for these two models. Removed along with the 78MB asset.
"""
import math
import os
from collections import namedtuple
import bpy
from osmassets.materials import link_alpha_clip
MODEL_ROOT = os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "..",
"assets", "models",
))
APPLE_DIR = os.path.join(MODEL_ROOT, "speedtree", "apple_low")
APPLE_OBJ = os.path.join(APPLE_DIR, "RedDeliciousApple.obj")
APPLE_COLOR = os.path.join(APPLE_DIR, "textures", "apple_color_2k.png")
APPLE_NORMAL = os.path.join(APPLE_DIR, "textures", "apple_normal_2k.png")
FATTREE_DIR = os.path.join(MODEL_ROOT, "lyrog", "fattree")
FATTREE_BLEND = os.path.join(FATTREE_DIR, "fattree.blend")
FATTREE_COLOR = os.path.join(FATTREE_DIR, "textures", "fat_tree.png")
MIN_TREE_HEIGHT = 4.0
# Leaf cards are cut at half opacity: the apple atlas's alpha is near-binary
# already, so a different threshold only changes edge thickness.
ALPHA_CUTOFF = 0.5
# Golden angle. Successive trees face directions that never repeat and never
# settle into a pattern, so a tree_row reads as planted rather than stamped.
GOLDEN_TURN = 0.61803398875
SCALE_JITTER = 0.14
TILT_JITTER = math.radians(3.0)
# meshes — mesh datablocks instanced together at one transform
# height — the variant's own height, what a target height is divided by
# base_z — the variant's own ground line, what drops the trunk onto z=0
TreeVariant = namedtuple("TreeVariant", "meshes height base_z")
# --------------------------------------------------------------------------
# import plumbing
def _bake(obj, name):
"""Copy obj's mesh with its rotation and scale applied, but not its
position.
Orientation has to be baked: the OBJ importer leaves the apple's Y-up to
Z-up conversion sitting on the object, so a raw mesh copy would plant the
tree on its side. Position must *not* be, because a source file's
translation is where the artist parked the model in their own scene —
fattree sits 2.9m up in the air — and baking that in would offset every
instance by it. Dropping it costs nothing: `base_z` measures whatever
ground line the mesh ends up with, and assemble() corrects for it.
"""
mesh = obj.data.copy()
mesh.transform(obj.matrix_world.to_3x3().to_4x4())
mesh.name = name
mesh.use_fake_user = True
return mesh
def _measure(meshes):
"""Return (height, base_z) for a variant's meshes in their shared space."""
zs = [vertex.co.z for mesh in meshes for vertex in mesh.vertices]
if not zs:
return 1.0, 0.0
low, high = min(zs), max(zs)
return max(high - low, 1e-6), low
def _discard(objects):
"""Remove imported objects along with the meshes they brought in.
The _bake copies carry a fake user and survive. Dropping only the objects
would strand their original meshes at zero users, which in turn keeps the
source materials and their megabytes of texture alive in the file.
"""
for obj in objects:
mesh = obj.data if obj.type == "MESH" else None
bpy.data.objects.remove(obj, do_unlink=True)
if mesh is not None and mesh.users == 0:
bpy.data.meshes.remove(mesh)
def _purge_orphans(before_materials, before_images):
"""Drop the materials and images an import created that nothing now uses.
Both importers build a material from the source file's own description and
load its textures. We replace that material, so without this the .blend
ships a second, unreferenced copy of every 2k texture.
"""
for material in set(bpy.data.materials) - before_materials:
if material.users == 0:
bpy.data.materials.remove(material)
for image in set(bpy.data.images) - before_images:
if image.users == 0:
bpy.data.images.remove(image)
def _image(path, non_color=False):
"""Load a texture once, keyed by filename so repeat calls share it."""
key = os.path.basename(path)
image = bpy.data.images.get(key)
if image is None:
image = bpy.data.images.load(path)
image.name = key
if non_color:
image.colorspace_settings.name = "Non-Color"
return image
def _foliage_material(name, color_path, normal_path=None, alpha_clip=False,
roughness=0.72):
"""Principled setup for a textured tree, alpha-clipped when asked.
The cut-out goes through materials.link_alpha_clip rather than straight
into the Alpha socket — see that function for why the extra two nodes are
what makes the crown survive the trip to Cesium.
"""
material = bpy.data.materials.get(name)
if material:
return material
material = bpy.data.materials.new(name)
material.use_nodes = True
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = next(n for n in nodes if n.type == "BSDF_PRINCIPLED")
bsdf.inputs["Roughness"].default_value = roughness
bsdf.inputs["Metallic"].default_value = 0.0
color_tex = nodes.new("ShaderNodeTexImage")
color_tex.image = _image(color_path)
color_tex.location = (-540, 260)
links.new(color_tex.outputs["Color"], bsdf.inputs["Base Color"])
if normal_path and os.path.exists(normal_path):
normal_tex = nodes.new("ShaderNodeTexImage")
normal_tex.image = _image(normal_path, non_color=True)
normal_tex.location = (-540, -140)
normal_map = nodes.new("ShaderNodeNormalMap")
normal_map.location = (-250, -140)
links.new(normal_tex.outputs["Color"], normal_map.inputs["Color"])
links.new(normal_map.outputs["Normal"], bsdf.inputs["Normal"])
if alpha_clip:
link_alpha_clip(material, color_tex.outputs["Alpha"], bsdf,
cutoff=ALPHA_CUTOFF)
return material
# --------------------------------------------------------------------------
# loaders — each returns [] when its model is absent, so a clean checkout
# still builds and the caller falls back to procedural trees
def _load_apple():
"""SpeedTree Red Delicious: one mesh, alpha-cut leaf cards, normal-mapped."""
if not os.path.exists(APPLE_OBJ):
return []
# Build ours first: the OBJ importer reuses an already-loaded image when the
# .mtl resolves to the same file, so the 2k textures land in the file once.
material = _foliage_material("AppleTree", APPLE_COLOR, APPLE_NORMAL,
alpha_clip=True, roughness=0.68)
before_objects = set(bpy.data.objects)
before_materials = set(bpy.data.materials)
before_images = set(bpy.data.images)
bpy.ops.wm.obj_import(filepath=APPLE_OBJ)
imported = [obj for obj in set(bpy.data.objects) - before_objects
if obj.type == "MESH"]
if not imported:
return []
meshes = []
for index, obj in enumerate(imported):
mesh = _bake(obj, "AppleTree_%02d" % index)
mesh.materials.clear()
mesh.materials.append(material)
meshes.append(mesh)
height, base_z = _measure(meshes)
_discard(imported)
_purge_orphans(before_materials, before_images)
return [TreeVariant(meshes, height, base_z)]
def _load_fattree():
"""Low-poly cartoon tree: opaque geometry, one diffuse texture.
The crown is real geometry and the texture's alpha is 1.0 everywhere, so
unlike the apple this needs no cut-out — and no normal map, which the
source does not ship.
"""
if not os.path.exists(FATTREE_BLEND):
return []
before_objects = set(bpy.data.objects)
before_materials = set(bpy.data.materials)
before_images = set(bpy.data.images)
try:
bpy.ops.wm.append(
filepath=FATTREE_BLEND + "/Object/fattree",
directory=FATTREE_BLEND + "/Object/",
files=[{"name": "fattree"}],
link=False,
)
except RuntimeError:
return []
imported = [obj for obj in set(bpy.data.objects) - before_objects
if obj.type == "MESH"]
obj = bpy.data.objects.get("fattree")
if obj is None:
_discard(imported)
_purge_orphans(before_materials, before_images)
return []
material = _foliage_material("FatTree", FATTREE_COLOR, alpha_clip=False,
roughness=0.85)
mesh = _bake(obj, "FatTree")
mesh.materials.clear()
mesh.materials.append(material)
height, base_z = _measure([mesh])
_discard(imported)
_purge_orphans(before_materials, before_images)
return [TreeVariant([mesh], height, base_z)]
LOADERS = {
"apple": _load_apple,
"fattree": _load_fattree,
}
# The styles this module can serve, for the CLI to validate against.
MODEL_STYLES = tuple(LOADERS)
def assemble(positions, collection, style="apple"):
"""Place instanced trees of `style` at `positions`.
positions is a list of (x, y, height) tuples as gathered by the two
tree-collecting loops (point nodes + tree_row samples). `height` is the
OSM height where tagged and a constant default otherwise, which means every
sample along one tree_row arrives with an identical value — the per-index
jitter below is what stops a row of forty from reading as one tree stamped
forty times.
Returns the number of trees placed, or 0 when the style's model is absent
or unknown, which is the caller's signal to fall back to procedural trees.
"""
loader = LOADERS.get(style)
if loader is None:
return 0
variants = loader()
if not variants:
return 0
for index, (x, y, target_height) in enumerate(positions):
variant = variants[index % len(variants)]
# Irrational periods stand in for an RNG: no repeat over any realistic
# tree count, and a pure function of the index, so rebuilding an area
# plants the identical forest.
scale_wobble = 1.0 + SCALE_JITTER * math.sin(index * 2.399963)
target = max(MIN_TREE_HEIGHT, target_height) * scale_wobble
factor = target / variant.height
yaw = ((index * GOLDEN_TURN) % 1.0) * math.tau
tilt_x = TILT_JITTER * math.sin(index * 1.114517)
tilt_y = TILT_JITTER * math.cos(index * 0.927295)
# Scaled and negated, the variant's own ground line drops the trunk
# onto z=0 whatever the source file used as its origin.
z = -variant.base_z * factor
for slot, mesh in enumerate(variant.meshes):
obj = bpy.data.objects.new(
"Tree_%s_%04d_%d" % (style, index, slot), mesh)
obj.location = (x, y, z)
obj.scale = (factor, factor, factor)
obj.rotation_euler = (tilt_x, tilt_y, yaw)
collection.objects.link(obj)
tris = 0
for variant in variants:
for mesh in variant.meshes:
mesh.calc_loop_triangles()
tris += len(mesh.loop_triangles)
print("Tree style %r: %d variants, %d tris per instance, %d planted"
% (style, len(variants), tris // max(1, len(variants)), len(positions)))
return len(positions)
+15
View File
@@ -0,0 +1,15 @@
"""Water feature assembly (`natural=water` or `water=lake`)."""
from osmassets.geom import clip_polygon
from osmassets.mesh import MeshBatch
def assemble(ring, scene_xmin, scene_xmax, scene_ymin, scene_ymax,
water_c, water_mat):
ring = clip_polygon(ring, scene_xmin, scene_xmax, scene_ymin, scene_ymax)
if len(ring) < 3:
return 0
batch = MeshBatch("Lake Surface", water_c, water_mat)
batch.add_polygon(ring, 0.10)
batch.finish()
return 1
+372
View File
@@ -0,0 +1,372 @@
"""Tests for the bpy-free half of the pipeline.
python3 -m unittest discover blender/tests
These run without Blender, which is the point of the osmassets split: before
it, the only way to exercise clip_polygon or sample_tree_row was to render a
whole area and look at the picture.
The expected values are derived from the geometry, not captured from the
implementation — a test that just records current output would ratify a bug.
"""
import math
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from osmassets.geom import (
clip_polygon,
distance_to_ring,
feature_in_bounds,
geometry_rings,
point_in_polygon,
polygon_area,
sample_polygon_interior,
sample_ring_boundary,
sample_tree_row,
signed_polygon_area,
)
from osmassets.osm import Projector, parse_height, parse_osm, tags
SQUARE = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]
class GeometryRingsTest(unittest.TestCase):
def test_polygon_keeps_only_the_exterior_ring(self):
geometry = {"type": "Polygon", "coordinates": [["outer"], ["hole"]]}
self.assertEqual(geometry_rings(geometry), [["outer"]])
def test_multipolygon_takes_each_exterior_ring(self):
geometry = {"type": "MultiPolygon",
"coordinates": [[["a"], ["a hole"]], [["b"]]]}
self.assertEqual(geometry_rings(geometry), [["a"], ["b"]])
def test_unsupported_and_empty_geometry(self):
self.assertEqual(geometry_rings(None), [])
self.assertEqual(geometry_rings({}), [])
self.assertEqual(geometry_rings({"type": "LineString",
"coordinates": [[0, 0], [1, 1]]}), [])
self.assertEqual(geometry_rings({"type": "MultiPolygon",
"coordinates": [[], [["b"]]]}), [["b"]])
class ClipPolygonTest(unittest.TestCase):
def test_polygon_inside_the_box_is_unchanged(self):
clipped = clip_polygon(SQUARE, -1.0, 11.0, -1.0, 11.0)
self.assertEqual([(round(x, 6), round(y, 6)) for x, y in clipped], SQUARE)
def test_half_outside_polygon_is_cut_at_the_boundary(self):
clipped = clip_polygon(SQUARE, 0.0, 5.0, 0.0, 10.0)
self.assertTrue(all(x <= 5.0 + 1e-9 for x, _ in clipped))
# A 10x10 square clipped to half its width is a 5x10 rectangle.
self.assertAlmostEqual(polygon_area(clipped), 50.0, places=6)
def test_polygon_fully_outside_collapses(self):
self.assertEqual(clip_polygon(SQUARE, 20.0, 30.0, 20.0, 30.0), [])
def test_degenerate_input(self):
self.assertEqual(clip_polygon([], 0, 1, 0, 1), [])
self.assertEqual(clip_polygon([(0.0, 0.0), (1.0, 1.0)], 0, 1, 0, 1), [])
def test_axis_aligned_edge_does_not_divide_by_zero(self):
# A vertical edge crossing the x clip plane exercises the b[0] == a[0]
# guard in the intersection lambdas.
ring = [(5.0, -5.0), (5.0, 5.0), (-5.0, 5.0), (-5.0, -5.0)]
clipped = clip_polygon(ring, 0.0, 10.0, 0.0, 10.0)
self.assertAlmostEqual(polygon_area(clipped), 25.0, places=6)
class PolygonAreaTest(unittest.TestCase):
def test_square(self):
self.assertAlmostEqual(polygon_area(SQUARE), 100.0)
def test_winding_does_not_change_the_sign(self):
self.assertAlmostEqual(polygon_area(list(reversed(SQUARE))), 100.0)
self.assertGreater(signed_polygon_area(SQUARE), 0.0)
self.assertLess(signed_polygon_area(list(reversed(SQUARE))), 0.0)
def test_degenerate(self):
self.assertEqual(polygon_area([(0.0, 0.0), (1.0, 1.0)]), 0.0)
class SampleRingBoundaryTest(unittest.TestCase):
def test_samples_closed_boundary_evenly(self):
samples = sample_ring_boundary(SQUARE, spacing=10.0)
self.assertEqual(len(samples), 4)
self.assertEqual([(round(x, 6), round(y, 6)) for x, y, _, _ in samples],
[(5.0, 0.0), (10.0, 5.0), (5.0, 10.0), (0.0, 5.0)])
def test_repeated_closing_point_is_ignored(self):
open_samples = sample_ring_boundary(SQUARE, spacing=10.0)
closed_samples = sample_ring_boundary(SQUARE + [SQUARE[0]], spacing=10.0)
self.assertEqual(open_samples, closed_samples)
def test_inset_moves_samples_inside_for_either_winding(self):
ccw = sample_ring_boundary(SQUARE, spacing=10.0, inset=1.0)
cw = sample_ring_boundary(list(reversed(SQUARE)), spacing=10.0, inset=1.0)
self.assertTrue(all(point_in_polygon((x, y), SQUARE) for x, y, _, _ in ccw))
self.assertTrue(all(point_in_polygon((x, y), SQUARE) for x, y, _, _ in cw))
self.assertEqual([(round(x, 6), round(y, 6)) for x, y, _, _ in ccw],
[(5.0, 1.0), (9.0, 5.0), (5.0, 9.0), (1.0, 5.0)])
def test_max_samples_reduces_density(self):
samples = sample_ring_boundary(SQUARE, spacing=1.0, max_samples=5)
self.assertEqual(len(samples), 5)
def test_degenerate_input(self):
self.assertEqual(sample_ring_boundary([(0.0, 0.0)], spacing=1.0), [])
self.assertEqual(sample_ring_boundary(SQUARE, spacing=0.0), [])
class SamplePolygonInteriorTest(unittest.TestCase):
def test_samples_are_inside_and_clear_of_edges(self):
samples = sample_polygon_interior(SQUARE, spacing=3.0, edge_clearance=1.0,
seed=42)
self.assertTrue(samples)
for x, y, _ in samples:
self.assertTrue(point_in_polygon((x, y), SQUARE))
self.assertGreaterEqual(distance_to_ring((x, y), SQUARE), 1.0)
def test_seed_is_deterministic(self):
first = sample_polygon_interior(SQUARE, spacing=3.0, seed=7)
second = sample_polygon_interior(SQUARE, spacing=3.0, seed=7)
self.assertEqual(first, second)
def test_max_samples_reduces_density(self):
samples = sample_polygon_interior(SQUARE, spacing=1.0, max_samples=4,
seed=99)
self.assertEqual(len(samples), 4)
def test_degenerate_input(self):
self.assertEqual(sample_polygon_interior([(0.0, 0.0)], spacing=1.0), [])
self.assertEqual(sample_polygon_interior(SQUARE, spacing=0.0), [])
class PointInPolygonTest(unittest.TestCase):
def test_inside_and_outside(self):
self.assertTrue(point_in_polygon((5.0, 5.0), SQUARE))
self.assertFalse(point_in_polygon((15.0, 5.0), SQUARE))
self.assertFalse(point_in_polygon((5.0, -0.5), SQUARE))
def test_concave_notch_is_excluded(self):
# An L shape: the notch at (8, 8) is outside even though it sits inside
# the bounding box.
shape = [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0),
(5.0, 5.0), (5.0, 10.0), (0.0, 10.0)]
self.assertTrue(point_in_polygon((2.0, 8.0), shape))
self.assertFalse(point_in_polygon((8.0, 8.0), shape))
class DistanceToRingTest(unittest.TestCase):
def test_distance_is_to_the_edge_not_the_interior(self):
# Centre of the square: 5m from every edge, even though it is inside.
self.assertAlmostEqual(distance_to_ring((5.0, 5.0), SQUARE), 5.0)
self.assertAlmostEqual(distance_to_ring((1.0, 5.0), SQUARE), 1.0)
def test_outside_point(self):
self.assertAlmostEqual(distance_to_ring((-3.0, 5.0), SQUARE), 3.0)
def test_closes_the_ring(self):
# Nearest edge is the implicit closing segment from (0,10) back to (0,0).
self.assertAlmostEqual(distance_to_ring((-2.0, 9.0), SQUARE), 2.0)
def test_repeated_vertex_does_not_divide_by_zero(self):
ring = [(0.0, 0.0), (0.0, 0.0), (4.0, 0.0)]
self.assertAlmostEqual(distance_to_ring((2.0, 3.0), ring), 3.0)
class SampleTreeRowTest(unittest.TestCase):
def test_even_spacing_along_a_straight_line(self):
samples = sample_tree_row([(0.0, 0.0), (10.0, 0.0)], spacing=5.0, height=6.0)
self.assertEqual([(round(x, 6), round(y, 6)) for x, y, _ in samples],
[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)])
self.assertTrue(all(h == 6.0 for _, _, h in samples))
def test_spacing_carries_across_segment_joins(self):
# Two 3m segments with 4m spacing: the second sample must land 1m into
# the second segment, not restart at its origin.
samples = sample_tree_row([(0.0, 0.0), (3.0, 0.0), (6.0, 0.0)],
spacing=4.0, height=5.0)
xs = [round(x, 6) for x, _, _ in samples]
self.assertEqual(xs, [0.0, 4.0, 6.0])
def test_trailing_point_is_skipped_when_it_would_double_plant(self):
# Endpoint sits 0.2m past the last sample, well under spacing * 0.45.
samples = sample_tree_row([(0.0, 0.0), (5.2, 0.0)], spacing=5.0, height=5.0)
self.assertEqual([round(x, 6) for x, _, _ in samples], [0.0, 5.0])
def test_zero_length_segment_is_skipped(self):
samples = sample_tree_row([(0.0, 0.0), (0.0, 0.0), (10.0, 0.0)],
spacing=5.0, height=5.0)
self.assertEqual([round(x, 6) for x, _, _ in samples], [0.0, 5.0, 10.0])
def test_too_few_points(self):
self.assertEqual(sample_tree_row([(0.0, 0.0)], spacing=5.0, height=5.0), [])
BOUNDS = {"min_lon": 114.0, "min_lat": 30.0, "max_lon": 114.01, "max_lat": 30.01}
class ProjectorTest(unittest.TestCase):
def setUp(self):
self.projector = Projector(BOUNDS)
def test_centre_of_bounds_is_the_origin(self):
x, y = self.projector.xy((114.005, 30.005))
self.assertAlmostEqual(x, 0.0, places=6)
self.assertAlmostEqual(y, 0.0, places=6)
def test_axes_point_east_and_north(self):
east, _ = self.projector.xy((114.006, 30.005))
_, north = self.projector.xy((114.005, 30.006))
self.assertGreater(east, 0.0)
self.assertGreater(north, 0.0)
def test_longitude_metres_shrink_with_latitude(self):
self.assertAlmostEqual(
self.projector.m_per_lon,
111320.0 * math.cos(math.radians(30.005)),
places=6,
)
self.assertLess(self.projector.m_per_lon, self.projector.m_per_lat)
def test_inside_honours_the_pad(self):
self.assertTrue(self.projector.inside((114.005, 30.005)))
# Default pad is 0.00035 degrees, so just outside the box still counts.
self.assertTrue(self.projector.inside((114.0102, 30.005)))
self.assertFalse(self.projector.inside((114.02, 30.005)))
self.assertFalse(self.projector.inside((114.0102, 30.005), pad=0.0))
def test_ring_projects_every_coordinate(self):
ring = self.projector.ring([(114.0, 30.0), (114.01, 30.01)])
self.assertEqual(len(ring), 2)
self.assertLess(ring[0][0], 0.0)
self.assertGreater(ring[1][0], 0.0)
class FeatureInBoundsTest(unittest.TestCase):
def setUp(self):
self.projector = Projector(BOUNDS)
def test_polygon_with_one_inside_vertex_counts(self):
feature = {"geometry": {"type": "Polygon", "coordinates": [[
[120.0, 40.0], [114.005, 30.005], [120.0, 40.0]]]}}
self.assertTrue(feature_in_bounds(feature, self.projector))
def test_feature_fully_outside(self):
feature = {"geometry": {"type": "Polygon", "coordinates": [[
[120.0, 40.0], [120.1, 40.1], [120.0, 40.0]]]}}
self.assertFalse(feature_in_bounds(feature, self.projector))
def test_missing_geometry(self):
self.assertFalse(feature_in_bounds({}, self.projector))
class ParseHeightTest(unittest.TestCase):
def test_reads_the_tag(self):
self.assertEqual(parse_height({"height": "24"}, 12.0), 24.0)
def test_missing_tag_falls_back(self):
self.assertEqual(parse_height({}, 12.0), 12.0)
def test_unparsable_tag_falls_back(self):
self.assertEqual(parse_height({"height": "about 20m"}, 12.0), 12.0)
def test_clamped_to_half_a_metre(self):
self.assertEqual(parse_height({"height": "0.1"}, 12.0), 0.5)
self.assertEqual(parse_height({"height": "-5"}, 12.0), 0.5)
OSM_SAMPLE = """<?xml version='1.0' encoding='UTF-8'?>
<osm version='0.6'>
<bounds minlon='114.0' minlat='30.0' maxlon='114.01' maxlat='30.01'/>
<node id='1' lon='114.001' lat='30.001'/>
<node id='2' lon='114.002' lat='30.002'/>
<node id='3' lon='114.003' lat='30.003'/>
<node id='4' lon='114.004' lat='30.004'>
<tag k='natural' v='tree'/>
<tag k='height' v='7'/>
</node>
<node id='bad' lon='oops' lat='30.0'/>
<way id='10'>
<nd ref='1'/><nd ref='2'/><nd ref='3'/>
<tag k='building' v='yes'/>
</way>
<way id='11' action='delete'>
<nd ref='1'/><nd ref='2'/>
<tag k='building' v='yes'/>
</way>
<way id='12'>
<nd ref='1'/><nd ref='999'/>
</way>
</osm>
"""
class ParseOsmTest(unittest.TestCase):
def setUp(self):
handle = tempfile.NamedTemporaryFile("w", suffix=".osm", delete=False,
encoding="utf-8")
handle.write(OSM_SAMPLE)
handle.close()
self.path = handle.name
def tearDown(self):
os.unlink(self.path)
def test_bounds(self):
bounds, _, _ = parse_osm(self.path)
self.assertEqual(bounds, {"min_lon": 114.0, "min_lat": 30.0,
"max_lon": 114.01, "max_lat": 30.01})
def test_only_tagged_nodes_become_point_features(self):
_, _, points = parse_osm(self.path)
self.assertEqual([p["id"] for p in points], ["4"])
self.assertEqual(points[0]["tags"], {"natural": "tree", "height": "7"})
def test_deleted_ways_are_dropped(self):
_, ways, _ = parse_osm(self.path)
self.assertNotIn("11", [w["id"] for w in ways])
def test_way_below_two_resolvable_nodes_is_dropped(self):
# Way 12 references a node that does not exist, leaving one coordinate.
_, ways, _ = parse_osm(self.path)
self.assertEqual([w["id"] for w in ways], ["10"])
self.assertEqual(len(ways[0]["coords"]), 3)
self.assertEqual(ways[0]["tags"], {"building": "yes"})
def test_unparsable_node_is_skipped_not_fatal(self):
_, _, points = parse_osm(self.path)
self.assertNotIn("bad", [p["id"] for p in points])
def test_missing_bounds_is_an_error(self):
handle = tempfile.NamedTemporaryFile("w", suffix=".osm", delete=False,
encoding="utf-8")
handle.write("<osm version='0.6'></osm>")
handle.close()
try:
with self.assertRaises(RuntimeError):
parse_osm(handle.name)
finally:
os.unlink(handle.name)
class TagsTest(unittest.TestCase):
def test_reads_key_value_children(self):
import xml.etree.ElementTree as ET
element = ET.fromstring(
"<way><tag k='building' v='yes'/><tag k='height' v='9'/></way>")
self.assertEqual(tags(element), {"building": "yes", "height": "9"})
def test_untagged_element(self):
import xml.etree.ElementTree as ET
self.assertEqual(tags(ET.fromstring("<way/>")), {})
if __name__ == "__main__":
unittest.main()
+171
View File
@@ -0,0 +1,171 @@
"""Dump a stable structural digest of a .blend built by generate_scene.py.
Run inside Blender:
Blender --background --factory-startup \
--python blender/tools/scene_digest.py -- \
--blend /path/to/scene.blend --out /path/to/digest.json
The digest is the parity contract for the osmassets refactor: it must stay
byte-identical across a pure restructuring. Fields that a control run (same
code, run twice) proves unstable belong in UNSTABLE_* below rather than in the
digest, otherwise the check is noise and gets ignored.
Floats are rounded to 6 decimals: Blender round-trips them through single
precision, so the last digits of a repr are not a meaningful signal.
"""
import json
import os
import sys
import bpy
# Object-level custom properties Blender adds on its own; not ours to compare.
IGNORED_PROP_KEYS = {"_RNA_UI", "cycles"}
def cli_args():
values = {"blend": None, "out": None}
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
i = 0
while i < len(argv):
if argv[i].startswith("--") and i + 1 < len(argv):
values[argv[i][2:]] = argv[i + 1]
i += 2
else:
i += 1
for key in ("blend", "out"):
if not values.get(key):
raise RuntimeError("--%s is required" % key)
return values
def rounded(value):
"""Normalise Blender's float/vector/array soup into plain JSON."""
if isinstance(value, float):
return round(value, 6)
if isinstance(value, (int, str, bool)) or value is None:
return value
if hasattr(value, "__len__") and not isinstance(value, (str, bytes)):
return [rounded(item) for item in value]
return str(value)
def custom_props(datablock):
out = {}
for key in sorted(datablock.keys()):
if key in IGNORED_PROP_KEYS:
continue
try:
out[key] = rounded(datablock[key])
except (TypeError, ValueError):
out[key] = "<unreadable>"
return out
def material_digest(material):
node_types = {}
if material.use_nodes and material.node_tree:
for node in material.node_tree.nodes:
node_types[node.type] = node_types.get(node.type, 0) + 1
entry = {
"name": material.name,
"diffuse_color": rounded(material.diffuse_color),
"use_nodes": material.use_nodes,
# Node identity is unstable (Blender names them Mix.001, Mix.002 …
# depending on creation order across datablocks), so compare the
# type histogram and the link count instead of the graph itself.
"node_types": dict(sorted(node_types.items())),
"link_count": (len(material.node_tree.links)
if material.use_nodes and material.node_tree else 0),
"props": custom_props(material),
}
if material.use_nodes and material.node_tree:
for node in material.node_tree.nodes:
if node.type != "BSDF_PRINCIPLED":
continue
for socket in ("Base Color", "Roughness", "Metallic"):
if socket in node.inputs:
entry["bsdf_" + socket.replace(" ", "_").lower()] = rounded(
node.inputs[socket].default_value)
break
return entry
def object_digest(obj):
entry = {
"name": obj.name,
"type": obj.type,
"collections": sorted(c.name for c in obj.users_collection),
"location": rounded(obj.location),
"rotation_euler": rounded(obj.rotation_euler),
"scale": rounded(obj.scale),
"data": obj.data.name if obj.data else None,
"materials": [slot.material.name if slot.material else None
for slot in obj.material_slots],
"modifiers": [(m.name, m.type) for m in obj.modifiers],
"props": custom_props(obj),
}
if obj.type == "MESH":
mesh = obj.data
entry["vertices"] = len(mesh.vertices)
entry["polygons"] = len(mesh.polygons)
entry["uv_layers"] = [layer.name for layer in mesh.uv_layers]
entry["smooth_polygons"] = sum(1 for p in mesh.polygons if p.use_smooth)
# Bounding box catches geometry that moved without changing topology;
# a vertex-by-vertex hash would be exact but too brittle to act on.
entry["bound_box"] = [rounded(corner) for corner in obj.bound_box]
elif obj.type == "CURVE":
entry["splines"] = len(obj.data.splines)
entry["points"] = sum(len(s.points) for s in obj.data.splines)
entry["bevel_depth"] = rounded(obj.data.bevel_depth)
elif obj.type == "LIGHT":
entry["light_type"] = obj.data.type
entry["energy"] = rounded(obj.data.energy)
elif obj.type == "CAMERA":
entry["lens"] = rounded(obj.data.lens)
entry["clip"] = [rounded(obj.data.clip_start), rounded(obj.data.clip_end)]
return entry
def digest(blend_path):
bpy.ops.wm.open_mainfile(filepath=blend_path)
scene = bpy.context.scene
return {
"scene": {
"name": scene.name,
"engine": scene.render.engine,
"resolution": [scene.render.resolution_x, scene.render.resolution_y],
"world_color": rounded(scene.world.color) if scene.world else None,
"camera": scene.camera.name if scene.camera else None,
"props": custom_props(scene),
},
"collections": sorted(c.name for c in bpy.data.collections),
"counts": {
"objects": len(bpy.data.objects),
"meshes": len(bpy.data.meshes),
"materials": len(bpy.data.materials),
"images": len(bpy.data.images),
},
"objects": [object_digest(obj)
for obj in sorted(bpy.data.objects, key=lambda o: o.name)],
"materials": [material_digest(mat)
for mat in sorted(bpy.data.materials, key=lambda m: m.name)],
"images": sorted(image.name for image in bpy.data.images),
}
if __name__ == "__main__":
args = cli_args()
result = digest(args["blend"])
os.makedirs(os.path.dirname(os.path.abspath(args["out"])), exist_ok=True)
with open(args["out"], "w", encoding="utf-8") as handle:
json.dump(result, handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
print("DIGEST_DONE", json.dumps({
"blend": args["blend"], "out": args["out"],
"objects": len(result["objects"]),
"materials": len(result["materials"]),
}))
+32
View File
@@ -0,0 +1,32 @@
{
"id": "hanyang-block",
"input": "/Users/que01/Desktop/汉阳区区块.osm",
"outputRoot": "/Users/que01/osm2streets-qgis-workflow/outputs",
"qgisApp": "/Applications/QGIS.app",
"blenderApp": "/Applications/Blender.app",
"stages": {
"intermediates": true,
"blender": true,
"cesium": true
},
"qgis": {
"arrowScale": 0.8,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"layerPrefix": "osm2streets"
},
"osm2streets": {
"debug_each_step": false,
"dual_carriageway_experiment": false,
"sidepath_zipping_experiment": false,
"inferred_sidewalks": true,
"osm2lanes": true
},
"blender": {
"treeStyle": "natural",
"officeOverrides": ""
}
}
@@ -0,0 +1,35 @@
{
"id": "nantaizi-lake-innovation-valley",
"input": "/Users/que01/Desktop/南台子湖创新谷OSM.osm",
"outputRoot": "/Users/que01/osm2streets-qgis-workflow/outputs",
"qgisApp": "/Applications/QGIS.app",
"blenderApp": "/Applications/Blender.app",
"stages": {
"intermediates": true,
"blender": true,
"cesium": true
},
"qgis": {
"arrowScale": 0.8,
"arrowMergeTriangles": true,
"arrowOutlineSimplifyMeters": 0.05,
"intersectionCornerSourceMaxDimensionMeters": 2.6,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"layerPrefix": "osm2streets"
},
"osm2streets": {
"debug_each_step": false,
"dual_carriageway_experiment": false,
"sidepath_zipping_experiment": false,
"inferred_sidewalks": true,
"osm2lanes": true
},
"blender": {
"treeStyle": "apple",
"officeOverrides": ""
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"qgisApp": "/Applications/QGIS.app",
"input": "/absolute/path/to/input.osm",
"outDir": "/absolute/path/to/osm2streets_web_out",
"gpkg": "/absolute/path/to/output.gpkg",
"project": "/absolute/path/to/output.qgz",
"preview": "/absolute/path/to/output_preview.png",
"arrowScale": 0.8,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"layerPrefix": "osm2streets",
"osm2streets": {
"debug_each_step": false,
"dual_carriageway_experiment": false,
"sidepath_zipping_experiment": false,
"inferred_sidewalks": true,
"osm2lanes": true
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"id": "my-area",
"input": "/absolute/path/to/input.osm",
"outputRoot": "/absolute/path/to/outputs",
"qgisApp": "/Applications/QGIS.app",
"blenderApp": "/Applications/Blender.app",
"stages": {
"intermediates": true,
"blender": true,
"cesium": true
},
"qgis": {
"arrowScale": 0.8,
"arrowMergeTriangles": true,
"arrowOutlineSimplifyMeters": 0.05,
"intersectionCornerSourceMaxDimensionMeters": 2.6,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"layerPrefix": "osm2streets"
},
"osm2streets": {
"debug_each_step": false,
"dual_carriageway_experiment": false,
"sidepath_zipping_experiment": false,
"inferred_sidewalks": true,
"osm2lanes": true
},
"blender": {
"treeStyle": "natural",
"officeOverrides": ""
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"qgisApp": "/Applications/QGIS.app",
"input": "/Users/que01/Desktop/汉阳区区块.osm",
"outDir": "/Users/que01/Downloads/hanyang_osm2streets/out",
"gpkg": "/Users/que01/Downloads/hanyang_osm2streets/hanyang_osm2streets.gpkg",
"project": "/Users/que01/Downloads/hanyang_osm2streets/hanyang_osm2streets.qgz",
"preview": "/Users/que01/Downloads/hanyang_osm2streets/hanyang_osm2streets_preview.png",
"arrowScale": 0.8,
"clipPad": 0.002,
"canvasPad": 0.001,
"previewPad": 0.0007,
"canvasExtent": null,
"previewExtent": null,
"osm2streets": {
"debug_each_step": false,
"dual_carriageway_experiment": false,
"sidepath_zipping_experiment": false,
"inferred_sidewalks": true,
"osm2lanes": true
}
}
+120
View File
@@ -0,0 +1,120 @@
# Changelog
## 2026-07-31(三)远看发黑的真正原因:反照率没被提亮
(二)里加的 emissive 提到 0.8 仍然发黑。原因是 emissive 乘的是本来就很暗的
反照率:0.8 × 深绿 ≈ sRGB `[0.22, 0.31, 0.11]`,还是暗的。**要提的是反照率本身。**
用户给的 Cesium 截图定位了问题:草是亮黄绿、建筑近白、路面浅灰,只有树是暗的。
这棵树的图集叶片本来就是深绿——绿色系像素均值 sRGB `[0.249, 0.35, 0.12]`。按真实
反照率渲染是对的,但**场景里其他材质都被手工提亮过**(`EXPORT_TINTS` 草 0.72、
带肋墙面 0.86,`EXPORT_EMISSION_OVERRIDES` 建筑 0.18),全是针对 Cesium 偏白的
默认光照调出来的。新资产没调过,是唯一一个如实渲染的东西,放在旁边就显得发黑。
- 新增 `FOLIAGE_ALBEDO_GAIN = 2.1`,在抠图植被的 dilate 那一遍里顺带乘上去。
用增益而不是 tint:其他材质是单一表面所以 tint 合适,而这是一张同时装着叶片、
树皮、果实的图集,往绿色混会把树干也染绿。缩放保留色相关系,只是把整体抬到和
邻居一样的曝光。叶片 sRGB `[0.249, 0.35, 0.12]` → `[0.36, 0.50, 0.18]`,
过曝到纯白的像素只占 0.4%
- `FOLIAGE_EMISSION` 回调到 0.25:它的职责只是给背光面兜底,不是主要提亮手段
- 增益之后远看仍偏灰绿,再加 `FOLIAGE_SATURATION = 1.75`,绕各像素自身
Rec.709 亮度做饱和度拉伸。这张图集本来就偏灰(平均饱和度 0.22),而远看时
mip 会把叶片、树皮和缝隙混在一起,越小越往中性靠。绕亮度拉伸能把叶片推绿而
基本不动本来就中性的部分,也没有绿色 tint 强加给树干的色相偏移——树皮只是变
暖一点。叶片 sRGB → `[0.262, 0.529, 0.021]`,整体饱和度 0.22 → 0.34
- 新增 `triangulate_mesh()`:`export_tangents` 打开后刷了 55 行
「切向空间只能只算三角/四边形」——`MeshBatch` 建的 OSM 轮廓都是 n-gon,
Blender 只能给三角/四边形算切线。glTF 本来就只有三角形,导出时无论如何都会
三角化,所以提前做不改变任何一个输出三角形(实测三角数 51719 前后一致),
但切线从 49/102 变成 102/102,警告归零
排查中被数据排除的假设,记下来免得重走:贴图颜色全链路逐位一致(不是 gamma);
模拟 mip 链可见像素亮度 0.127→0.124(不是 mipmap);法线贴图抠图区是干净平面法线
(不是法线污染);把导出的 GLB 重新导入 Blender 渲染,树是正常的(文件没问题)。
## 2026-07-31(二)远看整棵树发黑
黑色色块修掉后,Cesium 里近看正常、远看整棵树是暗色块。逐项排查:
- 贴图颜色全链路无偏移:源 4k / 降采样 2k / GLB 里导出的 PNG,opaque 均值都是 sRGB `[0.409, 0.406, 0.362]`,不是 gamma 问题
- 模拟 GPU mip 链(逐级 box 降采样,按 0.5 cutoff 取可见像素):可见像素亮度 mip0→mip6 只从 0.127 变到 0.124,覆盖率稳定在 0.42,不是 mipmap 变暗
- 法线贴图抠图区域是干净的平面法线 `[0.494, 0.512, 0.988]`,无黑像素,mip 后趋于更平,不是法线污染
真实原因是**缺少 emissive 补偿**。预览页没有配置任何环境贴图(`skyBox` / `skyAtmosphere` / `sun` 全部关闭),Cesium 只剩一个很弱的默认球谐环境光,所以太阳直射不到的面接近全黑——这正是 `EXPORT_EMISSION_OVERRIDES` 存在的原因,建筑 0.18、程序化树冠 0.015~0.02。树冠绝大部分是背光的叶片卡片,远看整体塌成一团暗色,而近看能看到向阳面所以还行。apple 材质不在那张表里,一点补偿都没有。
- 抠图植被改为把 diffuse 接回 Emission Color,强度 `FOLIAGE_EMISSION = 0.22`。用带贴图的自发光而不是平坦颜色:常量会把树干也染成叶子绿,而这样每个像素的下限是它自身反照率的一个比例。不增加字节,导出器让 `emissiveTexture` 指向 base color 已经在用的那张图
- glTF 导出打开 `export_tangents`:apple 材质有法线贴图但图元没有 TANGENT,缺失时由渲染器自行推导切线,而在双面薄片叶子卡上这个推导不可靠。全场景 49/102 个图元带上切线,顺带修正建筑法线贴图,GLB +0.83MB
如果远处仍偏暗,调 `export_cesium.py` 的 `FOLIAGE_EMISSION` 一个常量即可。
## 2026-07-31
- 树渲染改用两个第三方模型,`tree_style` 新增 `apple` / `fattree`:
- `apple` — SpeedTree Red Delicious,4475 tris,叶片 alpha 抠图 + 法线贴图(4k 贴图降采样为 2k)
- `fattree` — 低面数卡通树,2238 tris,实体几何
- 高度不再用魔数缩放,改为按模型自身包围盒归一化到目标高度,树根落在 z=0
- 每棵树按序号做确定性抖动:缩放 ±14%、黄金角偏航、±3° 倾斜,成排的行道树不再是同一棵树盖章
- 移除 `polyhaven` 树样式和 island_tree_01 资产(76MB)+ `blender/tools/ingest_tree.py`。该样式 append 的 `*_LOD1` 对象并不是完整的树:枝干只有 0.41 单位高,叶片是挂在原点下方的平面簇,原本是给源文件里的几何节点散布用的,直接种下去只有树枝
- 修复 Cesium 导出丢失 alpha 抠图:`make_export_material` 原本把 Alpha 恒定写死为 1.0,叶片卡片整块导出,而 SpeedTree 图集抠掉的区域是纯黑,在 Cesium 里表现为黑色色块
- Blender 4.2 起 glTF 导出不再读 `blend_method`(仍可写但已失效,写 `CLIP` 读回来是 `HASHED`),改为从节点树推断 alpha 模式。新增 `materials.link_alpha_clip()` 构造导出器识别的 `1 - (alpha < cutoff)` 节点形状,得到 `alphaMode=MASK`,同时 EEVEE 里也变成硬边抠图
- 新增 `alpha_dilated_image()`:把不透明像素的颜色向抠图区域外扩 8 圈。97.5% 的透明像素是纯黑,Cesium 生成 mipmap 时会把黑色平均进叶片边缘。叶片边缘相邻的纯黑像素占比从 10.3% 降到 0.6%
- 修复导出器对实例化网格重复包装材质:材质槽在 mesh 上,181 棵树共享一个 datablock,第一棵替换后其余 180 棵会把结果再包一次,产生 `Cesium Cesium Cesium ...` 的材质名,且烘焙图缓存按材质名索引,每轮都会再嵌一份同样的贴图。GLB 22.46MB → 20.76MB,materials 270 → 23
- `source_alpha_clipped()` 同时要求「材质连了 Alpha」和「贴图确实有抠图」:shrub_02 从 glTF 带进来一个 Math 节点接在 Alpha 上,但它的 JPEG 贴图 alpha 全是 1.0,只判断前者会把它误判为抠图材质,白白重编码成 1.2MB PNG 并让 Cesium 对 270 丛草做 alpha test
- 场景新增 `tree_style` / `tree_style_used` 属性;模型资产缺失时自动回落到 `natural`
## 2026-07-30
- 重构 Blender 脚本为 `osmassets` 包:`generate_scene.py` 从 1271 行缩减到 826 行 (-35%),纯函数可脱离 Blender 测试 (42 个 unittest)
- `osm.py` — OSM 解析 / Projector / parse_height(无 bpy)
- `geom.py` — 平面几何纯函数(无 bpy)
- `materials.py` — Blender 材质创建
- `mesh.py` — MeshBatch / prism / roof / polyline
- `catalog.py` — 道路图层和材质规格的唯一定义源,含 cesium 导出参数
- 要素注册表:`water.py` / `grass.py` / `scrub.py` / `tree.py`,各导出一个 `assemble()` 函数
- 新增 parity 工具链:`scene_digest.py` + `glb-digest.js` + `parity.js`,两区域全 PARITY OK
- 接入 Poly Haven island_tree_01 真实扫描树模型:`tree_style` 新增 `polyhaven` 选项(已于 2026-07-31 移除,见上)
- 新增 `blender/tools/ingest_tree.py` 用于离线减面导出树模型(已于 2026-07-31 移除)
- `nantaizi-lake-innovation-valley` 配置默认切换为 `treeStyle: polyhaven`(现为 `apple`)
## 2026-07-28
- 新增 `reimport` 阶段(`scripts/reimport-gpkg.js`),把 QGIS 手工修正过的 `<area-id>.gpkg` 回导为 `osm2streets_web_out/*.geojson` 并重建 `osm2streets_scene.geojson` / `osm2streets_scene_style.json`。手工修正流程从「`ogr2ogr` 循环 + 内联 node 脚本 + `npm run build`」三步压缩为一条命令:
```bash
npm run build -- --config config/areas/<area-id>.json --stages reimport,blender,cesium
```
- `reimport` 先把全部图层导出到临时目录并逐个校验,全部通过才写回输出目录:`ogr2ogr` 对不存在的图层退出码非 0 但仍会留下 0 字节文件,逐图层直接覆盖会静默损坏数据。
- `intermediates` 与 `reimport` 同时指定时直接报错:前者会用 OSM 重建 GeoPackage,正好抹掉后者要读回的手工修改。`reimport` 不含在 `all` 中。
- 新增 `scripts/lib/scene-layers.js` 作为 9 个渲染图层的唯一定义源(id、`z_index`、配色、描边宽度)。此前该表在合并场景、场景样式 JSON、生成的 QGIS 工程、README 手工流程中各有一份副本,改一处漏其余会导致图层叠放顺序错误并流入 Blender/Cesium。构建产物(GeoJSON、GeoPackage、`.qgz` 符号、样式 JSON)与改动前逐字节一致。
## 2026-07-27
- 实验分支新增 Cesium 车辆巡航预览:从 OSM 可行驶 `highway` 提取 bounds 内路线,输出 `<area-id>-vehicle-route.json`,并在预览页中驱动车辆循环移动。
- 巡航路线从道路中心线向右偏移约 1.3 米,车辆模型改为无 logo 的轻量预览车。
- 车辆巡航预览支持多辆车同时行驶,并通过 `Vehicle` 下拉框选择 Follow 目标。
- 将项目主入口重构为区域资产管线:`scripts/build-area.js`。
- 新增 `config/areas/nantaizi-lake-innovation-valley.json` 和 `config/areas/hanyang-block.json`,支持按 OSM 输入生成独立输出目录。
- `npm run build` 现在默认走区域资产管线;旧 QGIS 管线保留为 `npm run build:qgis`。
- `cesium` 阶段会生成 `<area-id>-cesium-preview.html` 本地预览页。
- 修复 Blender 脚本对 `--tree-style` 和 `--office-overrides` 这类连字符参数的解析。
## 2026-07-24
- Blender 场景生成器通用化:`generate_nantaizi.py` → `generate_scene.py`
- 去除所有硬编码默认路径(--osm / --geojson / --output / --render 均为 CLI 必传)
- `--geojson` 改为可选参数,不传时回退到 OSM highway 折线
- `--office-overrides` 替代硬编码的 `OFFICE_OVERRIDE_WAY_IDS`
- `export_cesium.py` 同样去除硬编码默认路径,CLI 参数改为必传
- `config/default.json` 路径改用占位符 `/absolute/path/to/...`
- `config/examples/template.json` 新增 `layerPrefix` 和 `blender` 配置块
- `scripts/build-osm2streets-qgis.js` 新增 `layerPrefix` 配置支持
- 包名改为 `osm-gis-pipeline`
- 文档全面更新为中文通用描述
## 2026-07-17
- Added configurable input/output paths through JSON config files.
- Added [config/default.json](/Users/que01/osm2streets-qgis-workflow/config/default.json) for `/Users/que01/Downloads/osm.xml`.
- Added [config/hanyang-block.json](/Users/que01/osm2streets-qgis-workflow/config/hanyang-block.json) for `/Users/que01/Desktop/汉阳区区块.osm`.
- Added [config/examples/template.json](/Users/que01/osm2streets-qgis-workflow/config/examples/template.json) for new areas.
- Updated OSM node coordinate parsing to support both single-quoted and double-quoted XML attributes.
- Verified QGIS outputs for both a smaller Overpass-style XML input and a larger JOSM-generated `.osm` input.
+87
View File
@@ -0,0 +1,87 @@
# Input Cases
这个工具目前验证过两类 OSM XML 输入。
## Case 1: Overpass/OSM XML
配置:
- [config/default.json](/Users/que01/osm2streets-qgis-workflow/config/default.json)
输入:
- `/Users/que01/Downloads/osm.xml`
特点:
- XML 属性使用双引号,例如 `lat="30.x" lon="114.x"`。
- 数据规模较小,适合调样式。
- 已生成路面、人行道、中心线、停止线、方向箭头。
最近一次验证规模:
- nodes: 1368
- ways: 100
- relations: 9
- road_surface: 133
- sidewalks: 102
- lane_arrows_webscale: 1565
## Case 2: JOSM OSM XML
配置:
- [config/hanyang-block.json](/Users/que01/osm2streets-qgis-workflow/config/hanyang-block.json)
输入:
- `/Users/que01/Desktop/汉阳区区块.osm`
特点:
- XML 属性使用单引号,例如 `lat='30.x' lon='114.x'`。
- 文件头包含 `generator='JOSM'`。
- 数据规模更大,osm2streets 会输出较多拓扑裁切提示,例如 `trimmed into oblivion`、`layers don't match`。
- 这些提示不一定阻止产物生成,但如果 QGIS 里出现明显断口,优先检查原始 OSM 路网连接、裁剪边界和 `layer` 标签。
最近一次验证规模:
- nodes: 6360
- ways: 696
- relations: 59
- road_surface: 1894
- sidewalks: 1379
- lane_arrows_webscale: 19390
## 建新配置的建议
从模板复制:
```bash
cp /Users/que01/osm2streets-qgis-workflow/config/examples/template.json \
/Users/que01/osm2streets-qgis-workflow/config/my-area.json
```
至少修改:
- `input`
- `outDir`
- `gpkg`
- `project`
- `preview`
运行:
```bash
cd /Users/que01/osm2streets-qgis-workflow
node scripts/build-osm2streets-qgis.js --config config/my-area.json
```
## 兼容性说明
脚本的 OSM bbox 解析已兼容:
- `lat="..." lon="..."`
- `lat='...' lon='...'`
osm2streets 本身仍要求输入是标准 OSM XML。若输入来自其它 GIS 格式,先转换成 OSM XML 或改造脚本入口。
+112
View File
@@ -0,0 +1,112 @@
# 重构施工计划:`osmassets` 包化(P0–P3)
> 临时工作文档。P3 收尾后把结论并入 `docs/changelog.md`,本文件删除。
## 目标
把「从 OSM 生成 Blender / Cesium 资产」的逻辑从两个单体脚本里拆成可复用的库,使得:
- 新增一种 OSM 要素 = 新增一个 `features/*.py` + 注册一行,不改 `build()`
- 道路图层表、材质规格只有一份定义,JS 侧与 Python 侧不再各存一份
- `export_cesium.py` 不再靠材质名字符串跟 `generate_scene.py` 对接
- 纯几何 / 解析逻辑脱离 `bpy`,可用系统 python 直接测
## 硬约束:严格产物一致
P0–P3 全程 **不改变任何输出**。每期结束必须通过 parity 校验,任何差异都要么消除、要么在本文件里逐条记录原因。
已知缺陷(本轮**只记录、不修**):
| # | 位置 | 现象 |
|---|---|---|
| D1 | `export_cesium.py:26,34,40,52` | `"Office White Metal Facade"` 四张表里都有,`generate_scene.py` 里已无此材质——死条目 |
| D2 | `scene-layers.js:15` vs `generate_scene.py:1017` | 同一批图层的颜色两侧各自手调,无一致性保证 |
| D3 | `generate_scene.py:788` | `tuft_density_wave` 注释仍在跟已删除的 hedge banding 作对比 |
## Parity 工具与基线
`outputs/` 已在 `.gitignore` 中,基线快照放 `outputs/_refactor-baseline/`,不入库。
| 工具 | 位置 | 作用 |
|---|---|---|
| 场景摘要 | `blender/tools/scene_digest.py` | 在 Blender 内打开 `.blend`,输出稳定 JSON:对象名/顶点数/面数/材质槽/自定义属性、材质参数、场景属性 |
| GLB 摘要 | `scripts/glb-digest.js` | 纯 Node 读 GLB 的 JSON chunk,输出 node/mesh/material 清单与 PBR 参数,附 buffer 字节长度 |
| 驱动 | `scripts/parity.sh <label>` | 跑 blender+cesium 阶段 → 收集 `SCENE_DONE` / `CESIUM_EXPORT_DONE` / 两份摘要 / 渲染 PNG 到 `outputs/_refactor-baseline/<label>/` |
**先做对照实验(control)**:用未改动的代码连跑两次,diff 两份摘要。这一步确定哪些字段天然不确定,把这些字段列入忽略名单。没做这步的 parity 校验是假的。
已完成,结论如下(`control-1` vs `control-2`,两区域):
- `.blend` **结构摘要两次完全一致** —— 这是主校验信号,可信
- `.blend` 文件 sha256 不一致:内嵌绝对路径 + 图片打包顺序随哈希表走
- 渲染 PNG sha256 不一致:EEVEE 非位级可复现
- GLB 结构(node / mesh / primitive / material / image)两次完全一致,但 accessor 数 399 vs 398、buffer 差 720 字节:glTF 导出器会去重相同 accessor,而 `smart_project` 的 UV 带浮点噪声,一次能去重一次不能
忽略名单(写在 `scripts/parity.js:IGNORED_PATHS`,附原因):`files.{blend,glb,render}.sha256`、`files.{glb,render}.bytes`、`glbDigest.{fileBytes,buffers,counts.accessors}`。
保留比对的即真正的契约:`SCENE_DONE` / `CESIUM_EXPORT_DONE` 标记、`.blend` 全量结构摘要、GLB 的 node/mesh/material/image 结构、`<area>.json` 元数据。加上 `control-1`、`control-2` 两份基线已落盘。
样本区域:
- `nantaizi-lake-innovation-valley` — 主样本,OSM + osm2streets GeoJSON 齐全
- `hanyang-block` — 次样本,只有 `intermediates` 产物,需先补跑一次 blender 阶段生成基线
## 分期
### P0 — 抽纯函数(行为零变化)
新建 `blender/osmassets/`,只搬运、不改逻辑:
| 目标文件 | 从 `generate_scene.py` 搬入 | 依赖 |
|---|---|---|
| `osm.py` | `tags` (94)、`parse_osm` (99)、`Projector` (140)、`parse_height` (506) | 无 bpy |
| `geom.py` | `geometry_rings` (406)、`feature_in_bounds` (418)、`clip_polygon` (426)、`sample_tree_row` (513)、`polygon_area` (688)、`point_in_polygon` (697)、`distance_to_ring` (712) | 无 bpy |
- `generate_scene.py` 顶部加 `sys.path` 引导(`--factory-startup` 下 `blender/` 不在 `sys.path`),改为 `from osmassets import ...`
- 新增 `blender/tests/test_geom.py`、`test_osm.py`,`unittest` 标准库,系统 `python3` 直接跑(本机 3.9,避免 3.10+ 语法)
- 验收:`python3 -m unittest discover blender/tests` 通过 + parity 全绿
### P1 — 单一定义源
新建 `blender/osmassets/catalog.py`:
- `ROAD_LAYERS`:`id` / `blender_z` / `material_name` / `color`,替换 `generate_scene.py:1017` 的 `road_mats` 与 `1122` 的 `layer_z` 两份副本
- `MATERIAL_SPECS`:目前散在 `build()` 里的全部 `make_material` / `make_textured_material` 调用参数
- 新增一致性检查:读输出目录里已存在的 `osm2streets_scene_style.json`,比对图层 id 集合与顺序,不一致则打 warning(**不**改颜色,改了就破坏 parity → 见 D2)
验收:parity 全绿;手动删一个图层 id 验证 warning 生效。
### P2 — 要素注册表
新建 `blender/osmassets/features/`,每种要素一个模块,导出 `SPEC`:
```
water.py natural=water / water=lake
grass.py landuse=grass(含 tuft 散布)
scrub.py natural=scrub
tree.py natural=tree 节点 + natural=tree_row + 两种树风格
building.py building=*(含 roof / windows)
fountain.py amenity=fountain
roads.py osm2streets GeoJSON 图层 + highway 折线回退
```
- `scene.py::assemble()` 遍历注册表;`build()` 收缩为「解析 → assemble → 灯光相机 → 存盘渲染」
- 计数器改由注册表汇总,但 `SCENE_DONE` 与 `scene[...]` 的键名、顺序保持逐字不变
- if/elif 的**匹配顺序**是语义的一部分(`building` 分支在最后),注册表必须保序
验收:parity 全绿 —— 这期风险最高,逐要素分次提交,每次单独跑 parity。
### P3 — 材质契约化
- `catalog.py` 的材质规格扩展出 cesium 段:`tint` / `metallic` / `base_color` / `emission`
- `generate_scene.py` 把规格写进材质自定义属性 `material["cesium_export"] = json.dumps(spec)`
- `export_cesium.py` 优先读自定义属性;读不到时回落到现有四张名字表(**原样保留,含 D1 死条目**),保证旧 `.blend` 仍能导出且 parity 成立
- `Tree Crown` 的程序化贴图特例保持不变
验收:parity 全绿;另外用重构前生成的旧 `.blend` 跑一次导出,确认回落路径可用。
## 不在本轮范围
- 输出目标可插拔(整场景 / 每要素单独 GLB)——原 P4
- `build-area.js` 里 390 行内联 HTML 与手写 glTF 的拆分——原 P4
- 上表 D1–D3 的修复
+21
View File
@@ -0,0 +1,21 @@
{
"name": "osm-asset-pipeline",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "osm-asset-pipeline",
"version": "0.3.0",
"dependencies": {
"osm2streets-js-node": "0.1.4"
}
},
"node_modules/osm2streets-js-node": {
"version": "0.1.4",
"resolved": "http://172.16.1.86:4873/osm2streets-js-node/-/osm2streets-js-node-0.1.4.tgz",
"integrity": "sha512-JjS6qJJjrrlEKEZxqV4s/N4qU0YfvdMUasdvfoyYCmZxEpNKAYjpuZeWJWeLEcGOqhu+YuV3YDIk9jgvMU0kKQ==",
"license": "Apache-2.0"
}
}
}
+8 -4
View File
@@ -1,10 +1,14 @@
{
"name": "@osm-asset/road-compiler",
"version": "0.1.0",
"name": "osm-asset-pipeline",
"version": "0.3.0",
"private": true,
"type": "commonjs",
"main": "src/index.js",
"scripts": {
"test": "node test/index.js"
"build": "node scripts/build-area.js",
"build:area": "node scripts/build-area.js",
"build:qgis": "node scripts/build-osm2streets-qgis.js"
},
"dependencies": {
"osm2streets-js-node": "0.1.4"
}
}
+774
View File
@@ -0,0 +1,774 @@
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");
const repoRoot = path.resolve(__dirname, "..");
const args = parseArgs(process.argv.slice(2));
const configPath = path.resolve(
args.config || path.join(repoRoot, "config", "areas", "nantaizi-lake-innovation-valley.json"),
);
const area = normalizeAreaConfig(readJson(configPath));
const requestedStages = args.stages
? splitList(args.stages)
: null;
const stages = resolveStages(area.stages, requestedStages);
// intermediates deletes and rebuilds the GeoPackage from OSM, which is exactly
// the manual work reimport exists to recover. Refuse the combination instead of
// silently letting one undo the other.
if (stages.intermediates && stages.reimport) {
throw new Error(
"Stages 'intermediates' and 'reimport' are mutually exclusive: " +
"intermediates rebuilds the GeoPackage from OSM and would discard the QGIS edits reimport reads back.",
);
}
console.log(`Area: ${area.id}`);
console.log(`Config: ${configPath}`);
console.log(`Output: ${area.outputs.areaDir}`);
if (stages.intermediates) {
buildIntermediates(area);
}
if (stages.reimport) {
reimportGpkg(area);
}
if (stages.blender) {
buildBlenderScene(area);
}
if (stages.cesium) {
exportCesium(area);
}
if (stages.preview) {
writeCesiumPreview(area);
}
console.log("Done.");
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("--")) continue;
const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
const next = argv[i + 1];
if (!next || next.startsWith("--")) {
out[key] = "true";
} else {
out[key] = next;
i += 1;
}
}
return out;
}
function readJson(file) {
if (!fs.existsSync(file)) {
throw new Error(`Config file not found: ${file}`);
}
return JSON.parse(fs.readFileSync(file, "utf8"));
}
function normalizeAreaConfig(raw) {
const id = requireText(raw.id, "id");
const input = path.resolve(requireText(raw.input, "input"));
if (!fs.existsSync(input)) {
throw new Error(`Input OSM XML not found: ${input}`);
}
const outputRoot = path.resolve(raw.outputRoot || path.join(repoRoot, "outputs"));
const outputOverrides = raw.outputs || {};
const areaDir = path.resolve(outputOverrides.areaDir || path.join(outputRoot, id));
const fileStem = outputOverrides.fileStem || id;
const outputs = {
areaDir,
geojsonDir: path.resolve(outputOverrides.geojsonDir || path.join(areaDir, "osm2streets_web_out")),
gpkg: path.resolve(outputOverrides.gpkg || path.join(areaDir, `${fileStem}.gpkg`)),
qgisProject: path.resolve(outputOverrides.qgisProject || path.join(areaDir, `${fileStem}.qgz`)),
qgisPreview: path.resolve(outputOverrides.qgisPreview || path.join(areaDir, `${fileStem}-preview.png`)),
blend: path.resolve(outputOverrides.blend || path.join(areaDir, `${fileStem}.blend`)),
render: path.resolve(outputOverrides.render || path.join(areaDir, `${fileStem}.png`)),
glb: path.resolve(outputOverrides.glb || path.join(areaDir, `${fileStem}.glb`)),
metadata: path.resolve(outputOverrides.metadata || path.join(areaDir, `${fileStem}.json`)),
cesiumPreview: path.resolve(
outputOverrides.cesiumPreview || path.join(areaDir, `${fileStem}-cesium-preview.html`),
),
vehicleRoute: path.resolve(outputOverrides.vehicleRoute || path.join(areaDir, `${fileStem}-vehicle-route.json`)),
vehicleModel: path.resolve(outputOverrides.vehicleModel || path.join(areaDir, `${fileStem}-vehicle-car.gltf`)),
pipelineDir: path.resolve(outputOverrides.pipelineDir || path.join(areaDir, "_pipeline")),
};
return {
id,
input,
outputRoot,
qgisApp: raw.qgisApp || "/Applications/QGIS.app",
blenderApp: raw.blenderApp || "/Applications/Blender.app",
stages: {
intermediates: raw.stages?.intermediates ?? raw.stages?.qgis ?? true,
blender: raw.stages?.blender ?? true,
cesium: raw.stages?.cesium ?? true,
reimport: false,
preview: false,
},
qgis: {
arrowScale: raw.qgis?.arrowScale ?? raw.arrowScale ?? 0.8,
arrowMergeTriangles: raw.qgis?.arrowMergeTriangles ?? raw.arrowMergeTriangles ?? true,
arrowOutlineSimplifyMeters: raw.qgis?.arrowOutlineSimplifyMeters ?? raw.arrowOutlineSimplifyMeters ?? 0.05,
intersectionCornerSourceMaxDimensionMeters: raw.qgis?.intersectionCornerSourceMaxDimensionMeters ?? raw.intersectionCornerSourceMaxDimensionMeters ?? 2.6,
clipPad: raw.qgis?.clipPad ?? raw.clipPad ?? 0.002,
canvasPad: raw.qgis?.canvasPad ?? raw.canvasPad ?? 0.001,
previewPad: raw.qgis?.previewPad ?? raw.previewPad ?? 0.0007,
canvasExtent: raw.qgis?.canvasExtent ?? raw.canvasExtent ?? null,
previewExtent: raw.qgis?.previewExtent ?? raw.previewExtent ?? null,
layerPrefix: raw.qgis?.layerPrefix ?? raw.layerPrefix ?? "osm2streets",
},
osm2streets: raw.osm2streets || {
debug_each_step: false,
dual_carriageway_experiment: false,
sidepath_zipping_experiment: false,
inferred_sidewalks: true,
osm2lanes: true,
},
blender: {
treeStyle: raw.blender?.treeStyle || "natural",
officeOverrides: raw.blender?.officeOverrides || raw.blender?.office_overrides || "",
},
outputs,
};
}
function requireText(value, key) {
if (typeof value !== "string" || value.trim() === "") {
throw new Error(`Missing config key: ${key}`);
}
return value;
}
function splitList(value) {
return String(value)
.split(",")
.map((item) => item.trim())
.filter(Boolean);
}
function resolveStages(defaults, requested) {
if (!requested) return defaults;
// 'reimport' is deliberately absent from 'all': it is a recovery step for
// hand-edited GeoPackages, never part of a full build.
const aliases = {
all: ["intermediates", "blender", "cesium"],
qgis: ["intermediates"],
osm2streets: ["intermediates"],
geojson: ["intermediates"],
intermediate: ["intermediates"],
intermediates: ["intermediates"],
reimport: ["reimport"],
gpkg: ["reimport"],
blender: ["blender"],
scene: ["blender"],
cesium: ["cesium"],
glb: ["cesium"],
preview: ["preview"],
html: ["preview"],
cesiumPreview: ["preview"],
};
const out = { intermediates: false, reimport: false, blender: false, cesium: false, preview: false };
for (const stage of requested) {
const mapped = aliases[stage];
if (!mapped) {
throw new Error(`Unknown stage '${stage}'. Use intermediates, reimport, blender, cesium, preview, or all.`);
}
for (const key of mapped) out[key] = true;
}
return out;
}
function writeDerivedConfig(area) {
fs.mkdirSync(area.outputs.pipelineDir, { recursive: true });
const derivedConfig = {
qgisApp: area.qgisApp,
input: area.input,
outDir: area.outputs.geojsonDir,
gpkg: area.outputs.gpkg,
project: area.outputs.qgisProject,
preview: area.outputs.qgisPreview,
arrowScale: area.qgis.arrowScale,
arrowMergeTriangles: area.qgis.arrowMergeTriangles,
arrowOutlineSimplifyMeters: area.qgis.arrowOutlineSimplifyMeters,
intersectionCornerSourceMaxDimensionMeters: area.qgis.intersectionCornerSourceMaxDimensionMeters,
clipPad: area.qgis.clipPad,
canvasPad: area.qgis.canvasPad,
previewPad: area.qgis.previewPad,
canvasExtent: area.qgis.canvasExtent,
previewExtent: area.qgis.previewExtent,
layerPrefix: area.qgis.layerPrefix,
osm2streets: area.osm2streets,
};
const derivedConfigPath = path.join(area.outputs.pipelineDir, "osm2streets-qgis.config.json");
fs.writeFileSync(derivedConfigPath, `${JSON.stringify(derivedConfig, null, 2)}\n`);
return derivedConfigPath;
}
function buildIntermediates(area) {
const derivedConfigPath = writeDerivedConfig(area);
console.log("Stage: intermediates (osm2streets GeoJSON + QGIS)");
runCommand(process.execPath, [
path.join(repoRoot, "scripts", "build-osm2streets-qgis.js"),
"--config",
derivedConfigPath,
], "intermediates");
}
function reimportGpkg(area) {
const derivedConfigPath = writeDerivedConfig(area);
console.log("Stage: reimport (GeoPackage -> GeoJSON)");
runCommand(process.execPath, [
path.join(repoRoot, "scripts", "reimport-gpkg.js"),
"--config",
derivedConfigPath,
], "reimport");
}
function buildBlenderScene(area) {
ensureFile(blenderExecutable(area), "Blender executable");
ensureFile(path.join(repoRoot, "blender", "generate_scene.py"), "Blender scene generator");
fs.mkdirSync(path.dirname(area.outputs.blend), { recursive: true });
fs.mkdirSync(path.dirname(area.outputs.render), { recursive: true });
const blenderArgs = [
"--background",
"--factory-startup",
"--python",
path.join(repoRoot, "blender", "generate_scene.py"),
"--",
"--osm",
area.input,
"--geojson",
area.outputs.geojsonDir,
"--output",
area.outputs.blend,
"--render",
area.outputs.render,
"--tree-style",
area.blender.treeStyle,
];
if (area.blender.officeOverrides) {
blenderArgs.push("--office-overrides", area.blender.officeOverrides);
}
console.log("Stage: blender");
runCommand(blenderExecutable(area), blenderArgs, "blender");
}
function exportCesium(area) {
ensureFile(blenderExecutable(area), "Blender executable");
ensureFile(area.outputs.blend, "Blend scene");
ensureFile(path.join(repoRoot, "blender", "export_cesium.py"), "Cesium exporter");
fs.mkdirSync(path.dirname(area.outputs.glb), { recursive: true });
fs.mkdirSync(path.dirname(area.outputs.metadata), { recursive: true });
console.log("Stage: cesium");
runCommand(blenderExecutable(area), [
"--background",
"--python",
path.join(repoRoot, "blender", "export_cesium.py"),
"--",
"--blend",
area.outputs.blend,
"--glb",
area.outputs.glb,
"--metadata",
area.outputs.metadata,
], "cesium");
writeCesiumPreview(area);
}
function blenderExecutable(area) {
return path.join(area.blenderApp, "Contents", "MacOS", "Blender");
}
function ensureFile(file, label) {
if (!fs.existsSync(file)) {
throw new Error(`${label} not found: ${file}`);
}
}
function runCommand(command, commandArgs, stage) {
const result = spawnSync(command, commandArgs, { stdio: "inherit" });
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const signal = result.signal ? ` signal=${result.signal}` : "";
throw new Error(`Stage '${stage}' failed with status=${result.status}${signal}`);
}
}
function writeCesiumPreview(area) {
ensureFile(area.outputs.glb, "Cesium GLB");
ensureFile(area.outputs.metadata, "Cesium metadata");
const htmlPath = area.outputs.cesiumPreview;
fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
writeVehicleRoute(area);
writeVehicleModel(area);
writeCesiumPreviewSupportFiles(path.dirname(htmlPath));
const glbName = path.basename(area.outputs.glb);
const metadataName = path.basename(area.outputs.metadata);
const routeName = path.basename(area.outputs.vehicleRoute);
const vehicleModelName = path.basename(area.outputs.vehicleModel);
fs.writeFileSync(htmlPath, cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, area.id));
console.log(`Cesium preview: ${htmlPath}`);
}
function writeCesiumPreviewSupportFiles(outDir) {
for (const file of ["cesium-preview.css", "cesium-preview.js"]) {
const source = path.join(repoRoot, "scripts", "lib", file);
ensureFile(source, `Cesium preview support file '${file}'`);
fs.copyFileSync(source, path.join(outDir, file));
}
}
function writeVehicleRoute(area) {
const route = buildVehicleRoute(area.input);
fs.mkdirSync(path.dirname(area.outputs.vehicleRoute), { recursive: true });
fs.writeFileSync(area.outputs.vehicleRoute, `${JSON.stringify(route, null, 2)}\n`);
console.log(`Vehicle route: ${area.outputs.vehicleRoute}`);
}
function writeVehicleModel(area) {
const gltf = makeVehicleGltf();
fs.mkdirSync(path.dirname(area.outputs.vehicleModel), { recursive: true });
fs.writeFileSync(area.outputs.vehicleModel, `${JSON.stringify(gltf, null, 2)}\n`);
console.log(`Vehicle model: ${area.outputs.vehicleModel}`);
}
function buildVehicleRoute(osmPath) {
const xml = fs.readFileSync(osmPath, "utf8");
const bounds = osmBounds(xml);
const nodes = new Map();
for (const match of xml.matchAll(/<node\b([^>]*)>/g)) {
const attrs = xmlAttrs(match[1]);
if (!attrs.id || attrs.lon === undefined || attrs.lat === undefined) continue;
nodes.set(attrs.id, [Number(attrs.lon), Number(attrs.lat)]);
}
const segments = [];
for (const match of xml.matchAll(/<way\b([^>]*)>([\s\S]*?)<\/way>/g)) {
const attrs = xmlAttrs(match[1]);
const body = match[2];
const tags = {};
for (const tagMatch of body.matchAll(/<tag\b([^>]*)\/?>/g)) {
const tag = xmlAttrs(tagMatch[1]);
if (tag.k) tags[tag.k] = tag.v || "";
}
if (!isCruiseHighway(tags)) continue;
const coords = [];
for (const ndMatch of body.matchAll(/<nd\b([^>]*)\/?>/g)) {
const nd = xmlAttrs(ndMatch[1]);
const coord = nodes.get(nd.ref);
if (coord) coords.push(coord);
}
const runs = splitInBounds(compactCoords(coords), bounds);
let runIndex = 0;
for (const run of runs) {
const lengthMeters = routeLength(run);
if (lengthMeters < 20) continue;
runIndex += 1;
const laneOffsetMeters = 1.3;
const shiftedRun = offsetPolylineRight(run, laneOffsetMeters);
segments.push({
id: runIndex === 1 ? (attrs.id || `way-${segments.length + 1}`) : `${attrs.id || "way"}-${runIndex}`,
name: tags.name || tags.highway || "road",
highway: tags.highway || "",
oneWay: tags.oneway || "",
lengthMeters,
laneOffsetMeters,
coordinates: shiftedRun,
centerlineCoordinates: run,
});
}
}
segments.sort((a, b) => b.lengthMeters - a.lengthMeters);
return {
source: osmPath,
bounds,
generatedAt: new Date().toISOString(),
speedMetersPerSecond: 8.0,
loop: true,
segments,
};
}
function osmBounds(xml) {
const match = xml.match(/<bounds\b([^>]*)\/?>/);
if (!match) return null;
const attrs = xmlAttrs(match[1]);
const bounds = {
minLon: Number(attrs.minlon),
minLat: Number(attrs.minlat),
maxLon: Number(attrs.maxlon),
maxLat: Number(attrs.maxlat),
};
return Object.values(bounds).every(Number.isFinite) ? bounds : null;
}
function xmlAttrs(text) {
const attrs = {};
for (const match of text.matchAll(/([:\w-]+)\s*=\s*("([^"]*)"|'([^']*)')/g)) {
attrs[match[1]] = match[3] !== undefined ? match[3] : match[4];
}
return attrs;
}
function isCruiseHighway(tags) {
const highway = tags.highway || "";
if (!highway) return false;
if (tags.area === "yes") return false;
const blocked = new Set([
"footway", "path", "pedestrian", "steps", "cycleway", "service", "track",
"bridleway", "corridor", "elevator", "platform", "construction",
]);
return !blocked.has(highway);
}
function compactCoords(coords) {
const out = [];
for (const coord of coords) {
const last = out[out.length - 1];
if (!last || last[0] !== coord[0] || last[1] !== coord[1]) {
out.push(coord);
}
}
return out;
}
function offsetPolylineRight(coords, offsetMeters) {
if (coords.length < 2 || offsetMeters === 0) return coords;
const refLat = coords.reduce((sum, coord) => sum + coord[1], 0) / coords.length;
const metersPerLat = 111320.0;
const metersPerLon = 111320.0 * Math.cos(degreesToRadians(refLat));
const points = coords.map((coord) => ({
x: coord[0] * metersPerLon,
y: coord[1] * metersPerLat,
lon: coord[0],
lat: coord[1],
}));
return points.map((point, index) => {
const prev = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
let dx = next.x - prev.x;
let dy = next.y - prev.y;
const length = Math.hypot(dx, dy);
if (length < 0.001) return [point.lon, point.lat];
dx /= length;
dy /= length;
const rightX = dy;
const rightY = -dx;
return [
(point.x + rightX * offsetMeters) / metersPerLon,
(point.y + rightY * offsetMeters) / metersPerLat,
];
});
}
function splitInBounds(coords, bounds) {
if (!bounds) return [coords];
const runs = [];
let current = [];
for (const coord of coords) {
if (insideBounds(coord, bounds)) {
current.push(coord);
} else if (current.length) {
if (current.length >= 2) runs.push(current);
current = [];
}
}
if (current.length >= 2) runs.push(current);
return runs;
}
function insideBounds(coord, bounds) {
const pad = 0.00002;
return (
coord[0] >= bounds.minLon - pad &&
coord[0] <= bounds.maxLon + pad &&
coord[1] >= bounds.minLat - pad &&
coord[1] <= bounds.maxLat + pad
);
}
function routeLength(coords) {
let total = 0;
for (let i = 1; i < coords.length; i += 1) {
total += haversineMeters(coords[i - 1], coords[i]);
}
return total;
}
function haversineMeters(a, b) {
const radius = 6371008.8;
const lat1 = degreesToRadians(a[1]);
const lat2 = degreesToRadians(b[1]);
const dLat = degreesToRadians(b[1] - a[1]);
const dLon = degreesToRadians(b[0] - a[0]);
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(lat1) * Math.cos(lat2) * sinLon * sinLon;
return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
}
function degreesToRadians(value) {
return value * Math.PI / 180;
}
function makeVehicleGltf() {
const meshes = [];
const nodes = [];
const bufferParts = [];
const bufferViews = [];
const accessors = [];
function align4(bytes) {
while (bytes.length % 4 !== 0) bytes.push(0);
}
function addBufferView(bytes, target) {
align4(bufferParts);
const offset = bufferParts.length;
bufferParts.push(...bytes);
const view = { buffer: 0, byteOffset: offset, byteLength: bytes.length };
if (target) view.target = target;
bufferViews.push(view);
return bufferViews.length - 1;
}
function floatBytes(values) {
const buffer = Buffer.alloc(values.length * 4);
values.forEach((value, index) => buffer.writeFloatLE(value, index * 4));
return Array.from(buffer);
}
function ushortBytes(values) {
const buffer = Buffer.alloc(values.length * 2);
values.forEach((value, index) => buffer.writeUInt16LE(value, index * 2));
return Array.from(buffer);
}
function addAccessor(bufferView, componentType, count, type, min, max) {
const accessor = { bufferView, componentType, count, type };
if (min) accessor.min = min;
if (max) accessor.max = max;
accessors.push(accessor);
return accessors.length - 1;
}
function addMesh(name, geometry, material) {
const positionView = addBufferView(floatBytes(geometry.positions), 34962);
const indexView = addBufferView(ushortBytes(geometry.indices), 34963);
const positionAccessor = addAccessor(
positionView,
5126,
geometry.positions.length / 3,
"VEC3",
geometry.min,
geometry.max,
);
const indexAccessor = addAccessor(indexView, 5123, geometry.indices.length, "SCALAR");
meshes.push({
name,
primitives: [{
attributes: { POSITION: positionAccessor },
indices: indexAccessor,
material,
}],
});
nodes.push({ name, mesh: meshes.length - 1 });
}
addMesh("body", cuboid(0, 0, 0.72, 4.6, 1.9, 0.9), 0);
addMesh("hood", cuboid(1.35, 0, 1.1, 1.25, 1.74, 0.38), 0);
addMesh("cabin", cuboid(-0.55, 0, 1.42, 1.75, 1.55, 0.82), 1);
addMesh("rear", cuboid(-1.65, 0, 1.08, 0.95, 1.78, 0.42), 0);
addMesh("front_windshield", cuboid(0.28, 0, 1.58, 0.12, 1.42, 0.58), 2);
addMesh("left_window", cuboid(-0.55, -0.82, 1.52, 1.25, 0.08, 0.48), 2);
addMesh("right_window", cuboid(-0.55, 0.82, 1.52, 1.25, 0.08, 0.48), 2);
for (const x of [-1.55, 1.45]) {
for (const y of [-1.02, 1.02]) {
addMesh(`wheel_${x}_${y}`, cylinderY(x, y, 0.46, 0.38, 0.32, 16), 3);
addMesh(`hub_${x}_${y}`, cylinderY(x, y, 0.46, 0.2, 0.34, 12), 4);
}
}
addMesh("left_headlight", cuboid(2.36, -0.48, 0.9, 0.08, 0.32, 0.16), 5);
addMesh("right_headlight", cuboid(2.36, 0.48, 0.9, 0.08, 0.32, 0.16), 5);
addMesh("left_tail", cuboid(-2.36, -0.55, 0.9, 0.08, 0.28, 0.16), 6);
addMesh("right_tail", cuboid(-2.36, 0.55, 0.9, 0.08, 0.28, 0.16), 6);
const buffer = Buffer.from(bufferParts);
return {
asset: { version: "2.0", generator: "osm-asset-pipeline vehicle preview" },
scene: 0,
scenes: [{ nodes: nodes.map((_, index) => index) }],
nodes,
meshes,
buffers: [{
byteLength: buffer.length,
uri: `data:application/octet-stream;base64,${buffer.toString("base64")}`,
}],
bufferViews,
accessors,
materials: [
material("paint red", [0.82, 0.05, 0.035, 1], 0.55, 0.25),
material("dark roof", [0.08, 0.08, 0.085, 1], 0.45, 0.35),
material("glass", [0.04, 0.12, 0.16, 0.82], 0.18, 0.08),
material("tire", [0.015, 0.014, 0.013, 1], 0.75, 0.65),
material("wheel hub", [0.72, 0.72, 0.68, 1], 0.35, 0.85),
material("headlight", [1.0, 0.92, 0.62, 1], 0.12, 0.0),
material("tail light", [0.95, 0.03, 0.03, 1], 0.25, 0.0),
],
};
}
function material(name, color, roughness, metallic) {
return {
name,
pbrMetallicRoughness: {
baseColorFactor: color,
roughnessFactor: roughness,
metallicFactor: metallic,
},
};
}
function cuboid(cx, lateral, up, sx, width, height) {
const x0 = cx - sx / 2;
const x1 = cx + sx / 2;
const y0 = up - height / 2;
const y1 = up + height / 2;
const z0 = lateral - width / 2;
const z1 = lateral + width / 2;
const positions = [
x0, y0, z0, x1, y0, z0, x1, y1, z0, x0, y1, z0,
x0, y0, z1, x1, y0, z1, x1, y1, z1, x0, y1, z1,
];
const indices = [
0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6,
0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0,
];
return { positions, indices, min: [x0, y0, z0], max: [x1, y1, z1] };
}
function cylinderY(cx, lateral, up, radius, width, segments) {
const positions = [];
const indices = [];
const z0 = lateral - width / 2;
const z1 = lateral + width / 2;
for (const z of [z0, z1]) {
positions.push(cx, up, z);
for (let i = 0; i < segments; i += 1) {
const angle = 2 * Math.PI * i / segments;
positions.push(cx + Math.cos(angle) * radius, up + Math.sin(angle) * radius, z);
}
}
const center0 = 0;
const center1 = segments + 1;
for (let i = 0; i < segments; i += 1) {
const a0 = center0 + 1 + i;
const b0 = center0 + 1 + ((i + 1) % segments);
const a1 = center1 + 1 + i;
const b1 = center1 + 1 + ((i + 1) % segments);
indices.push(center0, b0, a0);
indices.push(center1, a1, b1);
indices.push(a0, b0, b1, a0, b1, a1);
}
return {
positions,
indices,
min: [cx - radius, up - radius, z0],
max: [cx + radius, up + radius, z1],
};
}
function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId) {
const previewConfig = {
areaId,
glbName,
metadataName,
routeName,
vehicleModelName,
};
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(areaId)} Cesium Preview</title>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js"></script>
<link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
<link href="cesium-preview.css" rel="stylesheet">
</head>
<body>
<div id="cesiumContainer"></div>
<div id="controls">
<div class="control-group">
<button id="toggleCruise">Pause</button>
<button id="toggleFollow">Follow</button>
<label>Vehicle <select id="vehicleSelect"></select></label>
<label>Speed <input id="speedControl" type="range" min="2" max="22" step="1" value="8"></label>
<span id="speedLabel">8 m/s</span>
</div>
<div class="control-group">
<label><input id="toggleScene" type="checkbox" checked> Scene</label>
<span id="assetToggles" class="control-subgroup"></span>
<label><input id="toggleRoutes" type="checkbox" checked> Routes</label>
<label><input id="toggleVehicles" type="checkbox" checked> Vehicles</label>
<label><input id="toggleFps" type="checkbox"> FPS</label>
<label><input id="toggleDiagnostics" type="checkbox" checked> Info</label>
</div>
<div class="control-group">
<button data-camera="overview">Overview</button>
<button data-camera="oblique">Oblique</button>
<button data-camera="detail">Detail</button>
<button data-camera="route">Route</button>
</div>
</div>
<div id="diagnostics">Loading diagnostics...</div>
<div id="status">Loading ${escapeHtml(glbName)}...</div>
<div id="loadingOverlay">
<div class="loading-card">
<div class="loading-spinner" aria-hidden="true"></div>
<div class="loading-copy">
<strong>Loading scene</strong>
<span>${escapeHtml(areaId)}</span>
</div>
<div class="loading-bar" aria-hidden="true"><span></span></div>
</div>
</div>
<script>window.OSM_ASSET_PREVIEW_CONFIG = ${escapeScriptJson(JSON.stringify(previewConfig))};</script>
<script src="cesium-preview.js"></script>
</body>
</html>
`;
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function escapeScriptJson(value) {
return String(value)
.replaceAll("<", "\\u003c")
.replaceAll(">", "\\u003e")
.replaceAll("&", "\\u0026")
.replaceAll("\u2028", "\\u2028")
.replaceAll("\u2029", "\\u2029");
}
+1468
View File
File diff suppressed because it is too large. Load diff
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env node
"use strict";
// Structural digest of a GLB, for the osmassets refactor parity check.
//
// Byte-comparing the GLB is too strict: Blender packs images in hash-map order
// and the buffer padding shifts with it, so two runs of identical code can
// differ. This reads the glTF JSON chunk instead and reports the parts that
// carry meaning downstream in Cesium — node/mesh/material identity and PBR
// values — plus buffer lengths as a coarse size check.
//
// node scripts/glb-digest.js <file.glb> [--out digest.json]
const fs = require("fs");
const path = require("path");
function readGlbJson(file) {
const buffer = fs.readFileSync(file);
if (buffer.length < 12 || buffer.readUInt32LE(0) !== 0x46546c67) {
throw new Error(`Not a GLB (bad magic): ${file}`);
}
const total = buffer.readUInt32LE(8);
let offset = 12;
while (offset + 8 <= Math.min(total, buffer.length)) {
const chunkLength = buffer.readUInt32LE(offset);
const chunkType = buffer.readUInt32LE(offset + 4);
const start = offset + 8;
if (chunkType === 0x4e4f534a) {
return JSON.parse(buffer.slice(start, start + chunkLength).toString("utf8"));
}
offset = start + chunkLength;
}
throw new Error(`No JSON chunk found in ${file}`);
}
function round(value) {
if (typeof value === "number") return Number(value.toFixed(6));
if (Array.isArray(value)) return value.map(round);
return value;
}
function materialDigest(material) {
const pbr = material.pbrMetallicRoughness || {};
return {
name: material.name || null,
baseColorFactor: round(pbr.baseColorFactor || null),
metallicFactor: round(pbr.metallicFactor ?? null),
roughnessFactor: round(pbr.roughnessFactor ?? null),
hasBaseColorTexture: Boolean(pbr.baseColorTexture),
hasNormalTexture: Boolean(material.normalTexture),
emissiveFactor: round(material.emissiveFactor || null),
emissiveStrength: round(
material.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? null,
),
alphaMode: material.alphaMode || null,
doubleSided: material.doubleSided ?? null,
};
}
function digest(file) {
const gltf = readGlbJson(file);
const meshes = (gltf.meshes || []).map((mesh) => ({
name: mesh.name || null,
primitives: (mesh.primitives || []).map((primitive) => ({
material: primitive.material ?? null,
attributes: Object.keys(primitive.attributes || {}).sort(),
// Vertex/index counts live on the accessors; they are the real geometry
// fingerprint and stay stable regardless of buffer layout.
count: gltf.accessors?.[primitive.attributes?.POSITION]?.count ?? null,
indices: gltf.accessors?.[primitive.indices]?.count ?? null,
})),
}));
return {
file: path.basename(file),
fileBytes: fs.statSync(file).size,
counts: {
nodes: (gltf.nodes || []).length,
meshes: meshes.length,
materials: (gltf.materials || []).length,
images: (gltf.images || []).length,
accessors: (gltf.accessors || []).length,
},
extensionsUsed: (gltf.extensionsUsed || []).slice().sort(),
buffers: (gltf.buffers || []).map((buffer) => buffer.byteLength),
nodes: (gltf.nodes || [])
.map((node) => ({
name: node.name || null,
mesh: node.mesh ?? null,
translation: round(node.translation || null),
rotation: round(node.rotation || null),
scale: round(node.scale || null),
extras: node.extras ?? null,
}))
.sort((a, b) => String(a.name).localeCompare(String(b.name))),
meshes: meshes.sort((a, b) => String(a.name).localeCompare(String(b.name))),
materials: (gltf.materials || [])
.map(materialDigest)
.sort((a, b) => String(a.name).localeCompare(String(b.name))),
images: (gltf.images || [])
.map((image) => ({ name: image.name || null, mimeType: image.mimeType || null }))
.sort((a, b) => String(a.name).localeCompare(String(b.name))),
};
}
const argv = process.argv.slice(2);
const file = argv.find((arg) => !arg.startsWith("--"));
if (!file) {
console.error("usage: node scripts/glb-digest.js <file.glb> [--out digest.json]");
process.exit(1);
}
const outIndex = argv.indexOf("--out");
const result = digest(path.resolve(file));
const text = `${JSON.stringify(result, null, 2)}\n`;
if (outIndex >= 0 && argv[outIndex + 1]) {
const out = path.resolve(argv[outIndex + 1]);
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, text);
console.log(`GLB digest: ${out}`);
} else {
process.stdout.write(text);
}
+230
View File
@@ -0,0 +1,230 @@
html,
body,
#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #d9e0e2;
}
#cesiumContainer {
opacity: 0;
transition: opacity 180ms ease-out;
}
body.scene-ready #cesiumContainer {
opacity: 1;
}
#controls,
#diagnostics,
#status {
position: absolute;
z-index: 1;
border-radius: 4px;
background: rgba(20, 24, 28, 0.82);
color: #fff;
font-size: 12px;
line-height: 1.45;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
}
#loadingOverlay {
position: absolute;
inset: 0;
z-index: 3;
display: grid;
place-items: center;
background: #d9e0e2;
color: #1b2528;
font-size: 13px;
letter-spacing: 0;
transition: opacity 220ms ease-out, visibility 220ms ease-out;
}
.loading-card {
display: grid;
grid-template-columns: 32px minmax(180px, 260px);
gap: 12px;
align-items: center;
padding: 14px 16px;
border: 1px solid rgba(70, 86, 90, 0.16);
border-radius: 6px;
background: rgba(244, 248, 248, 0.88);
box-shadow: 0 12px 34px rgba(54, 68, 72, 0.20);
}
.loading-spinner {
width: 28px;
height: 28px;
border: 3px solid rgba(42, 67, 72, 0.18);
border-top-color: #147d8a;
border-radius: 50%;
animation: loading-spin 840ms linear infinite;
}
.loading-copy {
display: grid;
gap: 3px;
}
.loading-copy strong {
font-size: 13px;
font-weight: 650;
}
#loadingOverlay span {
color: #526064;
}
.loading-bar {
grid-column: 1 / -1;
position: relative;
height: 3px;
overflow: hidden;
border-radius: 999px;
background: rgba(42, 67, 72, 0.12);
}
.loading-bar span {
position: absolute;
inset: 0 auto 0 0;
width: 42%;
border-radius: inherit;
background: #147d8a;
animation: loading-bar 1.2s ease-in-out infinite;
}
@keyframes loading-spin {
to {
transform: rotate(360deg);
}
}
@keyframes loading-bar {
0% {
transform: translateX(-110%);
}
55% {
transform: translateX(70%);
}
100% {
transform: translateX(250%);
}
}
body.scene-ready #loadingOverlay {
visibility: hidden;
opacity: 0;
}
body.scene-error #loadingOverlay {
color: #5b1414;
}
body.scene-error .loading-spinner {
border-color: rgba(120, 30, 30, 0.18);
border-top-color: #9f2f2f;
animation-play-state: paused;
}
body.scene-error .loading-bar span {
background: #9f2f2f;
animation-play-state: paused;
}
#controls {
top: 12px;
left: 12px;
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
}
#status {
left: 12px;
bottom: 12px;
max-width: 560px;
padding: 8px 10px;
}
#diagnostics {
right: 12px;
top: 12px;
min-width: 280px;
max-width: 360px;
padding: 10px 12px;
white-space: pre-line;
}
#controls button,
#controls select {
height: 28px;
border: 0;
border-radius: 4px;
}
#controls button {
padding: 0 10px;
background: #f2f5f7;
color: #111;
cursor: pointer;
}
#controls button:active:not(:disabled) {
transform: translateY(1px);
}
#controls :disabled {
opacity: 0.45;
cursor: default;
}
#controls label:has(:disabled) {
opacity: 0.45;
}
#controls input[type="range"] {
width: 120px;
}
#controls label {
display: inline-flex;
gap: 5px;
align-items: center;
white-space: nowrap;
}
/* Playback / layers / camera each read as their own row of the panel. */
.control-group {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
}
.control-group + .control-group {
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.16);
}
/* Per-asset checkboxes hang off the master "Scene" toggle. */
.control-subgroup {
display: inline-flex;
flex-wrap: wrap;
gap: 8px 10px;
align-items: center;
padding-left: 10px;
border-left: 1px solid rgba(255, 255, 255, 0.16);
}
.control-subgroup:empty {
display: none;
}
.hidden {
display: none;
}
+672
View File
@@ -0,0 +1,672 @@
(function () {
"use strict";
const config = window.OSM_ASSET_PREVIEW_CONFIG || {};
const statusEl = document.getElementById("status");
const diagnosticsEl = document.getElementById("diagnostics");
const loadingOverlay = document.getElementById("loadingOverlay");
const toggleCruise = document.getElementById("toggleCruise");
const toggleFollow = document.getElementById("toggleFollow");
const toggleScene = document.getElementById("toggleScene");
const toggleRoutes = document.getElementById("toggleRoutes");
const toggleVehicles = document.getElementById("toggleVehicles");
const toggleFps = document.getElementById("toggleFps");
const toggleDiagnostics = document.getElementById("toggleDiagnostics");
const assetToggles = document.getElementById("assetToggles");
const vehicleSelect = document.getElementById("vehicleSelect");
const speedControl = document.getElementById("speedControl");
const speedLabel = document.getElementById("speedLabel");
const cameraButtons = Array.from(document.querySelectorAll("[data-camera]"));
// Status carries two kinds of message: the scene summary, which is what the
// panel should read whenever nothing else is going on, and transient notes
// from a control the user just touched. Keep the summary so the transient
// note can be replaced instead of destroying it.
let baseStatus = "";
const PREVIEW_BACKGROUND = "#d9e0e2";
Cesium.Ion.defaultAccessToken = "";
async function main() {
setLoadingMessage("Loading scene", config.areaId || "");
const metadata = await fetchJson(config.metadataName);
const routeData = await fetchOptionalJson(config.routeName);
const placement = scenePlacement(metadata);
const viewer = createViewer();
setLoadingMessage("Loading model", config.glbName || "");
const assets = await loadSceneAssets(viewer, metadata, placement);
const cruise = addVehicleCruises(viewer, routeData, config.vehicleModelName);
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
buildAssetToggles(assets);
bindRuntimeControls(viewer, assets, cruise, cameras);
startDiagnostics(viewer, metadata, assets, cruise, placement);
cameras.overview();
baseStatus = summaryText(metadata, assets, cruise);
setStatus(baseStatus);
setLoadingMessage("Preparing view", "finalizing materials");
await waitForStableFrames(viewer);
document.body.classList.add("scene-ready");
// Handle for the browser console and for headless checks: everything else
// in here is closed over by the IIFE and unreachable from outside.
window.osmPreview = { viewer, metadata, placement, assets, cruise, cameras };
}
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error("Could not load " + url + ": " + response.status);
}
return response.json();
}
// The route file is an extra on top of the scene, not a precondition for it.
// A missing or unreadable route costs the cruise controls, not the preview.
async function fetchOptionalJson(url) {
try {
return await fetchJson(url);
} catch (error) {
console.warn(error);
return null;
}
}
function createViewer() {
const viewer = new Cesium.Viewer("cesiumContainer", {
animation: false,
timeline: false,
baseLayerPicker: false,
geocoder: false,
navigationHelpButton: false,
sceneModePicker: false,
homeButton: true,
fullscreenButton: true,
infoBox: false,
selectionIndicator: false,
baseLayer: false
});
viewer.scene.globe.show = false;
viewer.scene.globe.depthTestAgainstTerrain = false;
viewer.scene.backgroundColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND);
viewer.scene.skyAtmosphere.show = false;
viewer.scene.skyBox.show = false;
viewer.scene.sun.show = false;
viewer.scene.moon.show = false;
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND);
return viewer;
}
function setLoadingMessage(title, detail) {
if (!loadingOverlay) return;
const titleEl = loadingOverlay.querySelector("strong");
const detailEl = loadingOverlay.querySelector("span");
if (titleEl) titleEl.textContent = title;
if (detailEl) detailEl.textContent = detail || "";
}
function waitForStableFrames(viewer) {
return new Promise((resolve) => {
const started = performance.now();
let frames = 0;
let done = false;
let remove = function () {};
function finish() {
if (done) return;
done = true;
remove();
resolve();
}
remove = viewer.scene.postRender.addEventListener(() => {
frames += 1;
const elapsed = performance.now() - started;
if ((frames >= 14 && elapsed >= 650) || elapsed >= 2800) {
finish();
}
});
window.setTimeout(finish, 3200);
viewer.scene.requestRender();
});
}
function scenePlacement(metadata) {
const anchor = metadata.anchor || {};
const longitude = Number(anchor.longitude || 0);
const latitude = Number(anchor.latitude || 0);
const height = Number(anchor.height || 0);
const heading = Number(metadata.heading_correction_degrees || 0);
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const correction = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(heading));
return {
longitude,
latitude,
height,
heading,
position,
modelMatrix: Cesium.Matrix4.multiplyByMatrix3(enu, correction, new Cesium.Matrix4())
};
}
function normalizedAssets(metadata) {
const assets = Array.isArray(metadata.assets) && metadata.assets.length
? metadata.assets
: [{
id: "main",
label: "Scene",
type: "model",
url: metadata.asset || config.glbName,
enabled: true
}];
return assets.filter((asset) => (asset.type || "model") === "model" && asset.url);
}
// One broken entry in metadata.assets should not blank the whole preview, so
// failures are collected and surfaced in the diagnostics panel instead.
async function loadSceneAssets(viewer, metadata, placement) {
const loaded = [];
for (const asset of normalizedAssets(metadata)) {
const id = asset.id || "asset-" + loaded.length;
const label = asset.label || asset.id || asset.url;
try {
const model = await Cesium.Model.fromGltfAsync({
url: asset.url,
modelMatrix: placement.modelMatrix,
scale: Number(asset.scale || 1.0)
});
model.show = asset.enabled !== false;
viewer.scene.primitives.add(model);
loaded.push({ id, label, url: asset.url, model, error: null });
} catch (error) {
console.error(error);
loaded.push({ id, label, url: asset.url, model: null, error });
}
}
if (!loaded.some((asset) => asset.model)) {
throw new Error("No scene model could be loaded (" + loaded.length + " declared)");
}
return loaded;
}
function liveAssets(assets) {
return assets.filter((asset) => asset.model);
}
// A single-asset scene keeps the plain "Scene" checkbox; a multi-asset one
// gets a child checkbox per model with "Scene" acting as the master.
function buildAssetToggles(assets) {
const live = liveAssets(assets);
if (live.length < 2) return;
for (const asset of live) {
const label = document.createElement("label");
const input = document.createElement("input");
input.type = "checkbox";
input.checked = asset.model.show;
input.dataset.assetId = asset.id;
input.addEventListener("change", () => {
asset.model.show = input.checked;
syncSceneMaster(assets);
setStatus(asset.label + (input.checked ? " visible" : " hidden"));
});
label.appendChild(input);
label.appendChild(document.createTextNode(" " + asset.label));
assetToggles.appendChild(label);
asset.toggle = input;
}
}
function syncSceneMaster(assets) {
const live = liveAssets(assets);
const shown = live.filter((asset) => asset.model.show).length;
toggleScene.checked = shown > 0;
toggleScene.indeterminate = shown > 0 && shown < live.length;
}
function bindRuntimeControls(viewer, assets, cruise, cameras) {
const hasVehicles = cruise.vehicles.length > 0;
toggleScene.addEventListener("change", () => {
for (const asset of liveAssets(assets)) {
asset.model.show = toggleScene.checked;
if (asset.toggle) asset.toggle.checked = toggleScene.checked;
}
toggleScene.indeterminate = false;
setStatus(toggleScene.checked ? "Scene visible" : "Scene hidden");
});
toggleRoutes.addEventListener("change", () => {
for (const vehicle of cruise.vehicles) vehicle.routeEntity.show = toggleRoutes.checked;
});
toggleVehicles.addEventListener("change", () => {
for (const vehicle of cruise.vehicles) vehicle.entity.show = toggleVehicles.checked;
});
toggleFps.addEventListener("change", () => {
viewer.scene.debugShowFramesPerSecond = toggleFps.checked;
});
toggleDiagnostics.addEventListener("change", () => {
diagnosticsEl.classList.toggle("hidden", !toggleDiagnostics.checked);
});
let stopFollow = function () {};
if (hasVehicles) {
stopFollow = bindCruiseControls(viewer, cruise);
} else {
// Nothing to drive: disable the cruise half of the panel rather than
// leaving controls that silently do nothing.
for (const el of [toggleCruise, toggleFollow, vehicleSelect, speedControl, toggleRoutes, toggleVehicles]) {
el.disabled = true;
}
toggleCruise.textContent = "Play";
}
for (const button of cameraButtons) {
const preset = cameras[button.dataset.camera];
if (!preset || (button.dataset.camera === "route" && !hasVehicles)) {
button.disabled = true;
continue;
}
button.addEventListener("click", () => {
// Chase-follow reclaims the camera on every clock tick, so a preset
// applied underneath it would be overwritten before the next frame.
stopFollow();
preset();
});
}
}
function bindCruiseControls(viewer, cruise) {
// The slider is authored with a static default; the route file decides the
// real cruise speed, so adopt it before the first input event.
speedControl.value = String(Cesium.Math.clamp(
Math.round(cruise.baseSpeed),
Number(speedControl.min),
Number(speedControl.max)
));
viewer.clock.multiplier = Number(speedControl.value) / cruise.baseSpeed;
speedLabel.textContent = speedControl.value + " m/s";
toggleCruise.addEventListener("click", () => {
viewer.clock.shouldAnimate = !viewer.clock.shouldAnimate;
toggleCruise.textContent = viewer.clock.shouldAnimate ? "Pause" : "Play";
});
speedControl.addEventListener("input", () => {
const value = Number(speedControl.value);
viewer.clock.multiplier = value / cruise.baseSpeed;
speedLabel.textContent = value + " m/s";
});
vehicleSelect.addEventListener("change", () => {
cruise.state.selectedIndex = Number(vehicleSelect.value || 0);
setStatus(selectedVehicle(cruise).label);
});
const follow = createChaseFollow(viewer, () => selectedVehicle(cruise).positions);
function stopFollow() {
if (!follow.enabled) return;
follow.stop();
toggleFollow.textContent = "Follow";
}
toggleFollow.addEventListener("click", () => {
if (follow.enabled) {
stopFollow();
setStatus(baseStatus);
} else {
follow.start();
toggleFollow.textContent = "Free";
setStatus("Following " + selectedVehicle(cruise).label);
}
});
return stopFollow;
}
function addVehicleCruises(viewer, routeData, vehicleModelName) {
const segments = ((routeData && routeData.segments) || [])
.filter((segment) => segment.coordinates && segment.coordinates.length >= 2)
.slice(0, 5);
const speed = Number((routeData && routeData.speedMetersPerSecond) || 8);
const start = Cesium.JulianDate.now();
viewer.clock.startTime = start.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
viewer.clock.multiplier = 1;
viewer.clock.shouldAnimate = segments.length > 0;
const vehicles = segments.map((segment, index) => {
const vehicle = addCruiseVehicle(viewer, segment, index, start, speed, vehicleModelName);
const option = document.createElement("option");
option.value = String(index);
option.textContent = "#" + (index + 1) + " " + segment.name + " " + Math.round(segment.lengthMeters) + "m";
vehicleSelect.appendChild(option);
return vehicle;
});
return {
vehicles,
baseSpeed: speed,
state: { selectedIndex: 0 }
};
}
function addCruiseVehicle(viewer, segment, index, start, speed, vehicleModelName) {
const route = prepareRoute(segment);
const positions = new Cesium.CallbackProperty((time, result) => {
return routePosition(route, start, time, speed, result);
}, false);
const flat = [];
for (const coord of segment.coordinates) {
flat.push(coord[0], coord[1], 1.05);
}
const routeColor = [
Cesium.Color.CYAN,
Cesium.Color.LIME,
Cesium.Color.YELLOW,
Cesium.Color.ORANGE,
Cesium.Color.DEEPSKYBLUE
][index % 5];
const routeEntity = viewer.entities.add({
name: "Cruise route " + (index + 1),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights(flat),
width: 2,
material: routeColor.withAlpha(0.75),
clampToGround: false
}
});
const vehicle = viewer.entities.add({
name: "Cruise vehicle " + (index + 1),
position: positions,
orientation: routeOrientation(route, start, speed, 0.0),
model: {
uri: vehicleModelName,
scale: 1.0,
minimumPixelSize: 24,
maximumScale: 80
}
});
return {
entity: vehicle,
routeEntity,
positions,
route,
segment,
label: "Vehicle #" + (index + 1) + " | route " + segment.id + " | " + Math.round(segment.lengthMeters) + "m"
};
}
function selectedVehicle(cruise) {
return cruise.vehicles[cruise.state.selectedIndex] || cruise.vehicles[0];
}
function prepareRoute(segment) {
const distances = [0.0];
for (let i = 1; i < segment.coordinates.length; i += 1) {
distances.push(distances[i - 1] + distanceMeters(segment.coordinates[i - 1], segment.coordinates[i]));
}
return {
coordinates: segment.coordinates,
distances,
length: Math.max(1.0, distances[distances.length - 1])
};
}
function routePosition(route, start, time, speed, result) {
const seconds = Math.max(0, Cesium.JulianDate.secondsDifference(time, start));
const distance = (seconds * speed) % route.length;
let index = 1;
while (index < route.distances.length - 1 && route.distances[index] < distance) {
index += 1;
}
const prevDist = route.distances[index - 1];
const nextDist = route.distances[index];
const t = nextDist > prevDist ? (distance - prevDist) / (nextDist - prevDist) : 0;
const a = route.coordinates[index - 1];
const b = route.coordinates[index];
const lon = a[0] + (b[0] - a[0]) * t;
const lat = a[1] + (b[1] - a[1]) * t;
return Cesium.Cartesian3.fromDegrees(lon, lat, 1.15, Cesium.Ellipsoid.WGS84, result);
}
function routeOrientation(route, start, speed, yawDegrees) {
const correction = Cesium.Quaternion.fromAxisAngle(
Cesium.Cartesian3.UNIT_Z,
Cesium.Math.toRadians(yawDegrees)
);
const current = new Cesium.Cartesian3();
const ahead = new Cesium.Cartesian3();
const direction = new Cesium.Cartesian3();
const up = new Cesium.Cartesian3();
const east = new Cesium.Cartesian3();
const north = new Cesium.Cartesian3();
return new Cesium.CallbackProperty((time, result) => {
routePosition(route, start, time, speed, current);
const aheadTime = Cesium.JulianDate.addSeconds(time, 0.8, new Cesium.JulianDate());
routePosition(route, start, aheadTime, speed, ahead);
Cesium.Cartesian3.subtract(ahead, current, direction);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 0.0001) {
return result;
}
Cesium.Cartesian3.normalize(direction, direction);
Cesium.Cartesian3.normalize(current, up);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, east);
if (Cesium.Cartesian3.magnitudeSquared(east) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, east);
} else {
Cesium.Cartesian3.normalize(east, east);
}
Cesium.Cartesian3.cross(up, east, north);
Cesium.Cartesian3.normalize(north, north);
const eastComponent = Cesium.Cartesian3.dot(direction, east);
const northComponent = Cesium.Cartesian3.dot(direction, north);
const heading = Math.atan2(eastComponent, northComponent);
const base = Cesium.Transforms.headingPitchRollQuaternion(
current,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
return Cesium.Quaternion.multiply(base, correction, result || new Cesium.Quaternion());
}, false);
}
function createChaseFollow(viewer, positionsProvider) {
const scratchPosition = new Cesium.Cartesian3();
const scratchPrevious = new Cesium.Cartesian3();
const scratchDirection = new Cesium.Cartesian3();
const scratchEast = new Cesium.Cartesian3();
const scratchNorth = new Cesium.Cartesian3();
const scratchUp = new Cesium.Cartesian3();
const offset = new Cesium.Cartesian3();
const state = { enabled: false, distance: 36.0, height: 18.0 };
function update(clock) {
const time = clock.currentTime;
const positions = positionsProvider();
const position = positions.getValue(time, scratchPosition);
if (!position) return;
const previousTime = Cesium.JulianDate.addSeconds(time, -0.8, new Cesium.JulianDate());
const previous = positions.getValue(previousTime, scratchPrevious);
if (previous) {
Cesium.Cartesian3.subtract(position, previous, scratchDirection);
} else {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
if (Cesium.Cartesian3.magnitudeSquared(scratchDirection) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
Cesium.Cartesian3.normalize(scratchDirection, scratchDirection);
Cesium.Cartesian3.normalize(position, scratchUp);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, scratchUp, scratchEast);
if (Cesium.Cartesian3.magnitudeSquared(scratchEast) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchEast);
} else {
Cesium.Cartesian3.normalize(scratchEast, scratchEast);
}
Cesium.Cartesian3.cross(scratchUp, scratchEast, scratchNorth);
Cesium.Cartesian3.normalize(scratchNorth, scratchNorth);
const eastComponent = Cesium.Cartesian3.dot(scratchDirection, scratchEast);
const northComponent = Cesium.Cartesian3.dot(scratchDirection, scratchNorth);
const heading = Math.atan2(eastComponent, northComponent);
Cesium.Cartesian3.fromElements(0.0, -state.distance, state.height, offset);
const transform = Cesium.Transforms.headingPitchRollToFixedFrame(
position,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
viewer.camera.lookAtTransform(transform, offset);
}
function onWheel(event) {
if (!state.enabled) return;
event.preventDefault();
const zoom = event.deltaY > 0 ? 1.12 : 0.88;
state.distance = Cesium.Math.clamp(state.distance * zoom, 12.0, 160.0);
state.height = Cesium.Math.clamp(state.height * zoom, 6.0, 90.0);
update(viewer.clock);
}
return {
get enabled() {
return state.enabled;
},
start() {
if (state.enabled) return;
state.enabled = true;
viewer.trackedEntity = undefined;
viewer.canvas.addEventListener("wheel", onWheel, { passive: false });
viewer.clock.onTick.addEventListener(update);
update(viewer.clock);
},
stop() {
if (!state.enabled) return;
state.enabled = false;
viewer.clock.onTick.removeEventListener(update);
viewer.canvas.removeEventListener("wheel", onWheel);
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
};
}
function createCameraPresets(viewer, metadata, placement, cruise) {
const radius = Math.max(220.0, boundsRadiusMeters(metadata.bounds) || 900.0);
const center = placement.position;
function lookAt(range, headingDegrees, pitchDegrees) {
viewer.camera.lookAt(
center,
new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(headingDegrees),
Cesium.Math.toRadians(pitchDegrees),
range
)
);
// lookAt locks the camera into the target's reference frame; release it
// so orbit and pan keep working from the new vantage point.
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
return {
overview() {
viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, radius), {
duration: 0.0
});
},
oblique() {
lookAt(radius * 0.92, 135.0, -28.0);
},
detail() {
lookAt(radius * 0.32, 115.0, -18.0);
},
route() {
if (!cruise.vehicles.length) return;
const vehicle = selectedVehicle(cruise);
const coord = vehicle.segment.coordinates[Math.floor(vehicle.segment.coordinates.length / 2)];
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(coord[0], coord[1], 90.0),
orientation: {
heading: Cesium.Math.toRadians(0.0),
pitch: Cesium.Math.toRadians(-62.0),
roll: 0.0
},
duration: 0.0
});
}
};
}
// Camera-dependent readouts have to track the camera, so refresh off the
// render loop rather than a fixed timer, throttled to stay off the hot path.
function startDiagnostics(viewer, metadata, assets, cruise, placement) {
const center = placement.position;
const stats = metadata.scene_stats || {};
const failed = assets.filter((asset) => asset.error);
let lastUpdate = 0;
function render() {
const cartographic = viewer.camera.positionCartographic;
const distance = Cesium.Cartesian3.distance(viewer.camera.positionWC, center);
const lines = [
"Area: " + (config.areaId || "(unknown)"),
"Anchor: " + placement.longitude.toFixed(7) + ", " + placement.latitude.toFixed(7),
"Camera height: " + Math.round(cartographic.height) + " m",
"Camera range: " + Math.round(distance) + " m",
"Assets: " + liveAssets(assets).length + " model(s)",
"Vehicles: " + cruise.vehicles.length,
"Buildings: " + Number(stats.buildings || 0),
"Trees: " + Number(stats.trees || 0),
"Road layer source: " + (metadata.source_geojson ? "osm2streets" : "OSM fallback")
];
if (failed.length) {
lines.push("Failed assets: " + failed.map((asset) => asset.url).join(", "));
}
diagnosticsEl.textContent = lines.join("\n");
}
viewer.scene.postRender.addEventListener(() => {
const now = performance.now();
if (now - lastUpdate < 250) return;
lastUpdate = now;
render();
});
render();
}
function summaryText(metadata, assets, cruise) {
const stats = metadata.scene_stats || {};
return [
config.areaId,
liveAssets(assets).map((asset) => asset.url).join(", "),
cruise.vehicles.length ? "vehicles " + cruise.vehicles.length : "no drivable route",
"buildings " + Number(stats.buildings || 0),
"trees " + Number(stats.trees || 0)
].filter(Boolean).join(" | ");
}
function boundsRadiusMeters(bounds) {
if (!bounds) return null;
const minLon = Number(bounds.min_lon);
const minLat = Number(bounds.min_lat);
const maxLon = Number(bounds.max_lon);
const maxLat = Number(bounds.max_lat);
if (![minLon, minLat, maxLon, maxLat].every(Number.isFinite)) return null;
return Math.max(
80.0,
distanceMeters([minLon, minLat], [maxLon, maxLat]) * 0.58
);
}
function distanceMeters(a, b) {
const radius = 6371008.8;
const lat1 = Cesium.Math.toRadians(a[1]);
const lat2 = Cesium.Math.toRadians(b[1]);
const dLat = Cesium.Math.toRadians(b[1] - a[1]);
const dLon = Cesium.Math.toRadians(b[0] - a[0]);
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(lat1) * Math.cos(lat2) * sinLon * sinLon;
return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
}
function setStatus(message) {
statusEl.textContent = message;
}
main().catch((error) => {
console.error(error);
setStatus("Failed to load Cesium preview: " + error.message);
document.body.classList.add("scene-error");
setLoadingMessage("Failed to load scene", error.message);
});
}());
+164
View File
@@ -0,0 +1,164 @@
"use strict";
// Single source of truth for the osm2streets render layers.
//
// The same nine layers, in the same order, previously appeared four times:
// the merged-scene z_index table, the scene style JSON, the generated QGIS
// project (layer dict + draw_order), and the README's manual rebuild snippet.
// Adding a layer or changing a z-index meant editing all of them in lockstep,
// and a missed copy produces a silently mis-stacked scene downstream in
// Blender/Cesium. Everything now derives from SCENE_LAYERS.
//
// zIndex doubles as draw order: lowest paints first (bottom of the stack).
// outline: null means "no stroke" (QGIS gets a fully transparent outline).
const SCENE_LAYERS = [
{
id: "road_surface",
splitKey: "roadSurface",
zIndex: 10,
title: "road surface",
fill: "#2b2b28",
outline: "#1e1e1c",
outlineWidth: 0.04,
},
{
id: "intersection_surface",
splitKey: "intersectionSurface",
zIndex: 20,
title: "intersection surface",
fill: "#2b2b28",
outline: "#1e1e1c",
outlineWidth: 0.04,
},
{
id: "sidewalks",
splitKey: "sidewalks",
zIndex: 30,
title: "sidewalks",
fill: "#bebeb6",
outline: "#9c9c94",
outlineWidth: 0.025,
},
{
id: "sidewalk_corners",
splitKey: "sidewalkCorners",
zIndex: 40,
title: "sidewalk corners",
fill: "#bebeb6",
outline: "#9c9c94",
outlineWidth: 0.025,
},
{
id: "lane_separators",
splitKey: "laneSeparators",
zIndex: 50,
title: "lane separators",
fill: "#eeeee6",
outline: null,
outlineWidth: 0,
},
{
id: "center_lines",
splitKey: "centerLines",
zIndex: 60,
title: "center lines",
fill: "#f5be2a",
outline: null,
outlineWidth: 0,
},
{
id: "crosswalks",
splitKey: "crosswalks",
zIndex: 70,
title: "crosswalks",
fill: "#fffff6",
outline: null,
outlineWidth: 0,
},
{
id: "vehicle_stop_lines",
splitKey: "vehicleStopLines",
zIndex: 80,
title: "vehicle stop lines",
fill: "#fffff6",
outline: null,
outlineWidth: 0,
},
{
id: "lane_arrows_webscale",
splitKey: "laneArrows",
zIndex: 90,
title: "lane arrows",
fill: "#fffff6",
outline: "#2b2b28",
outlineAlpha: 200,
outlineWidth: 0.015,
},
];
const SCENE_FILE = "osm2streets_scene.geojson";
const SCENE_STYLE_FILE = "osm2streets_scene_style.json";
function layerFile(layer) {
return `${layer.id}.geojson`;
}
// getCollection(layer) -> FeatureCollection, so callers can source layers from
// the in-memory split (build) or from disk (reimport) with the same merge.
function mergeScene(getCollection) {
return {
type: "FeatureCollection",
features: SCENE_LAYERS.flatMap((layer) => {
const collection = getCollection(layer) || {};
return (collection.features || []).map((feature) => ({
...feature,
properties: {
...(feature.properties || {}),
render_layer: layer.id,
z_index: layer.zIndex,
},
}));
}),
};
}
function sceneStyle() {
return {
version: 1,
geometry: "polygon",
sortProperty: "z_index",
layerProperty: "render_layer",
layers: SCENE_LAYERS.map((layer) => ({
id: layer.id,
zIndex: layer.zIndex,
fill: layer.fill,
outline: layer.outline,
outlineWidth: layer.outlineWidth,
})),
};
}
// QGIS symbol properties want "r,g,b,a" strings rather than hex.
function qgisRgba(hex, alpha = 255) {
if (!hex) return "0,0,0,0";
const match = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
if (!match) {
throw new Error(`Expected #rrggbb color, got: ${hex}`);
}
const value = parseInt(match[1], 16);
const r = (value >> 16) & 0xff;
const g = (value >> 8) & 0xff;
const b = value & 0xff;
return `${r},${g},${b},${alpha}`;
}
module.exports = {
SCENE_LAYERS,
SCENE_FILE,
SCENE_STYLE_FILE,
layerFile,
mergeScene,
sceneStyle,
qgisRgba,
};
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Normalize malformed lane-arrow meshes emitted by osm2streets."""
import argparse
import json
import math
from pathlib import Path
from osgeo import ogr
METERS_PER_DEGREE = 111320.0
ogr.UseExceptions()
def cli_args():
parser = argparse.ArgumentParser(
description="Normalize osm2streets triangulated lane-arrow polygons."
)
parser.add_argument("--input", required=True, type=Path)
parser.add_argument("--outline-simplify-meters", required=True, type=float)
return parser.parse_args()
def point_segment_distance(point, start, end, latitude):
meters_lon = METERS_PER_DEGREE * math.cos(math.radians(latitude))
px = (point[0] - start[0]) * meters_lon
py = (point[1] - start[1]) * METERS_PER_DEGREE
bx = (end[0] - start[0]) * meters_lon
by = (end[1] - start[1]) * METERS_PER_DEGREE
length_squared = bx * bx + by * by
if length_squared == 0:
return math.hypot(px, py)
projection = max(0.0, min(1.0, (px * bx + py * by) / length_squared))
return math.hypot(px - projection * bx, py - projection * by)
def simplify_ring(points, tolerance, latitude):
points = list(points)
changed = True
while changed and len(points) > 3:
changed = False
for index, point in enumerate(points):
previous = points[index - 1]
following = points[(index + 1) % len(points)]
if point_segment_distance(point, previous, following, latitude) <= tolerance:
points.pop(index)
changed = True
break
return points
def tail_edge_candidate(points):
best = None
for index in range(len(points)):
start = points[index]
end = points[(index + 1) % len(points)]
previous = points[index - 1]
following = points[(index + 2) % len(points)]
before = [start[0] - previous[0], start[1] - previous[1]]
after = [following[0] - end[0], following[1] - end[1]]
edge = [end[0] - start[0], end[1] - start[1]]
before_length = math.hypot(*before)
after_length = math.hypot(*after)
edge_length = math.hypot(*edge)
if min(before_length, after_length, edge_length) == 0:
continue
alignment = (
before[0] * after[0] + before[1] * after[1]
) / (before_length * after_length)
if before_length <= edge_length or after_length <= edge_length or alignment >= -0.9:
continue
score = -alignment * min(before_length, after_length) / edge_length
if best is None or score > best[0]:
best = (score, index, before, after, before_length, after_length)
return best
def square_arrow_tail(points, latitude):
# A normalized straight arrow has seven exterior vertices. Other arrow
# silhouettes are left untouched because their tail cannot be inferred safely.
if len(points) != 7:
return points
meters_lon = METERS_PER_DEGREE * math.cos(math.radians(latitude))
origin = points[0]
local = [
[
(point[0] - origin[0]) * meters_lon,
(point[1] - origin[1]) * METERS_PER_DEGREE,
]
for point in points
]
candidate = tail_edge_candidate(local)
if candidate is None:
return points
_, index, before, after, before_length, after_length = candidate
axis = [
before[0] / before_length - after[0] / after_length,
before[1] / before_length - after[1] / after_length,
]
axis_length = math.hypot(*axis)
if axis_length == 0:
return points
axis = [axis[0] / axis_length, axis[1] / axis_length]
end_index = (index + 1) % len(local)
midpoint = [
(local[index][0] + local[end_index][0]) / 2.0,
(local[index][1] + local[end_index][1]) / 2.0,
]
for point_index in (index, end_index):
offset = [
local[point_index][0] - midpoint[0],
local[point_index][1] - midpoint[1],
]
projection = offset[0] * axis[0] + offset[1] * axis[1]
local[point_index][0] -= projection * axis[0]
local[point_index][1] -= projection * axis[1]
points[point_index] = [
origin[0] + local[point_index][0] / meters_lon,
origin[1] + local[point_index][1] / METERS_PER_DEGREE,
]
return points
def normalize_polygon(geometry, tolerance):
if geometry.GetGeometryName() == "MULTIPOLYGON":
geometry = geometry.UnionCascaded()
if geometry is None or geometry.GetGeometryName() != "POLYGON":
raise ValueError("triangle merge did not produce a Polygon")
source_ring = geometry.GetGeometryRef(0)
points = [source_ring.GetPoint(i)[:2] for i in range(source_ring.GetPointCount() - 1)]
if len(points) <= 3:
raise ValueError("arrow exterior has too few points")
latitude = sum(point[1] for point in points) / len(points)
points = simplify_ring(points, tolerance, latitude)
points = square_arrow_tail(points, latitude)
normalized = ogr.Geometry(ogr.wkbPolygon)
outer = ogr.Geometry(ogr.wkbLinearRing)
for point in points + [points[0]]:
outer.AddPoint_2D(*point)
normalized.AddGeometry(outer)
for index in range(1, geometry.GetGeometryCount()):
normalized.AddGeometry(geometry.GetGeometryRef(index))
if normalized.IsEmpty() or not normalized.IsValid():
raise ValueError("normalized arrow geometry is invalid")
return normalized
def normalize_file(input_path, tolerance):
with input_path.open("r", encoding="utf-8") as handle:
collection = json.load(handle)
for index, feature in enumerate(collection.get("features", [])):
geometry = ogr.CreateGeometryFromJson(json.dumps(feature.get("geometry", {})))
if geometry is None or geometry.IsEmpty():
raise ValueError(f"feature {index} has no usable geometry")
try:
normalized = normalize_polygon(geometry, tolerance)
except ValueError as error:
raise ValueError(f"feature {index}: {error}") from error
feature["geometry"] = json.loads(
normalized.ExportToJson(options=["COORDINATE_PRECISION=15"])
)
temp_path = input_path.with_name(f".{input_path.name}.tmp")
with temp_path.open("w", encoding="utf-8") as handle:
json.dump(collection, handle, ensure_ascii=False, separators=(",", ":"))
handle.write("\n")
temp_path.replace(input_path)
def main():
args = cli_args()
if args.outline_simplify_meters < 0:
raise ValueError("--outline-simplify-meters must be non-negative")
normalize_file(args.input.resolve(), args.outline_simplify_meters)
if __name__ == "__main__":
main()
+270
View File
@@ -0,0 +1,270 @@
#!/usr/bin/env node
"use strict";
// Parity harness for the osmassets refactor (docs/refactor-plan.md).
//
// node scripts/parity.js capture <label> [--areas a,b] [--stages blender,cesium]
// node scripts/parity.js compare <labelA> <labelB>
//
// capture runs the pipeline and snapshots everything that must not change:
// the stage stdout markers, a structural digest of the .blend, a structural
// digest of the .glb, and a hash of the render PNG. compare diffs two
// snapshots field by field.
//
// Snapshots live under outputs/_refactor-baseline/<label>/, which is inside
// the gitignored outputs/ tree — baselines are local scratch, not artifacts.
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { spawnSync } = require("child_process");
const repoRoot = path.resolve(__dirname, "..");
const baselineRoot = path.join(repoRoot, "outputs", "_refactor-baseline");
const DEFAULT_AREAS = ["nantaizi-lake-innovation-valley", "hanyang-block"];
// Fields a control run (identical code, run twice) proved unstable. They are
// still recorded — a human reading a snapshot wants them — but comparing them
// would bury real regressions under noise.
//
// files.*.sha256 / .bytes for blend, glb, render
// .blend embeds absolute paths and packs images in hash-map order, so the
// file hash moves while the structural digest stays put. The EEVEE render
// is likewise not bit-reproducible.
// glbDigest.fileBytes / .buffers / .counts.accessors
// The glTF exporter deduplicates identical accessors. smart_project UVs
// carry float noise, so two runs can differ by one shared UV accessor
// (observed: 399 vs 398 accessors, 720 bytes) with identical nodes,
// meshes, primitives, materials and images.
//
// What remains compared is the real contract: the SCENE_DONE / CESIUM markers,
// the full .blend structural digest (objects, meshes, materials, custom
// properties), and the GLB node/mesh/material/image structure.
const IGNORED_PATHS = new Set([
"capturedAt",
"durationMs",
"label",
"files.blend.sha256",
"files.glb.sha256",
"files.glb.bytes",
"files.render.sha256",
"files.render.bytes",
"glbDigest.fileBytes",
"glbDigest.buffers",
"glbDigest.counts.accessors",
]);
function main() {
const [command, ...rest] = process.argv.slice(2);
if (command === "capture") return capture(rest);
if (command === "compare") return compare(rest);
console.error("usage: parity.js capture <label> [--areas a,b] [--stages s]");
console.error(" parity.js compare <labelA> <labelB>");
process.exit(1);
}
function parseFlags(argv) {
const flags = {};
const positional = [];
for (let i = 0; i < argv.length; i += 1) {
if (argv[i].startsWith("--") && i + 1 < argv.length) {
flags[argv[i].slice(2)] = argv[i + 1];
i += 1;
} else {
positional.push(argv[i]);
}
}
return { flags, positional };
}
function capture(argv) {
const { flags, positional } = parseFlags(argv);
const label = positional[0];
if (!label) throw new Error("capture needs a label");
const areas = (flags.areas ? flags.areas.split(",") : DEFAULT_AREAS)
.map((a) => a.trim())
.filter(Boolean);
const stages = flags.stages || "blender,cesium";
for (const area of areas) {
const configPath = path.join(repoRoot, "config", "areas", `${area}.json`);
if (!fs.existsSync(configPath)) throw new Error(`No config for area: ${area}`);
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
const areaDir = path.join(repoRoot, "outputs", area);
const stem = area;
const outDir = path.join(baselineRoot, label, area);
fs.mkdirSync(outDir, { recursive: true });
console.log(`\n=== parity capture [${label}] ${area} (stages: ${stages}) ===`);
const started = Date.now();
const run = spawnSync(process.execPath, [
path.join(repoRoot, "scripts", "build-area.js"),
"--config", configPath,
"--stages", stages,
], { cwd: repoRoot, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
const stdout = `${run.stdout || ""}`;
const stderr = `${run.stderr || ""}`;
process.stdout.write(stdout);
if (run.status !== 0) {
process.stderr.write(stderr);
throw new Error(`build-area failed for ${area} (exit ${run.status})`);
}
const snapshot = {
label,
area,
stages,
capturedAt: new Date().toISOString(),
durationMs: Date.now() - started,
markers: {
scene: parseMarker(stdout, "SCENE_DONE"),
cesium: parseMarker(stdout, "CESIUM_EXPORT_DONE"),
},
files: {},
};
const blend = path.join(areaDir, `${stem}.blend`);
if (fs.existsSync(blend)) {
snapshot.files.blend = fileStat(blend);
snapshot.blendDigest = blendDigest(config, blend, path.join(outDir, "blend-digest.json"));
}
const glb = path.join(areaDir, `${stem}.glb`);
if (fs.existsSync(glb)) {
snapshot.files.glb = fileStat(glb);
snapshot.glbDigest = glbDigest(glb, path.join(outDir, "glb-digest.json"));
}
for (const [key, file] of [
["render", path.join(areaDir, `${stem}.png`)],
["metadata", path.join(areaDir, `${stem}.json`)],
]) {
if (fs.existsSync(file)) snapshot.files[key] = fileStat(file);
}
if (fs.existsSync(path.join(areaDir, `${stem}.json`))) {
snapshot.metadata = JSON.parse(
fs.readFileSync(path.join(areaDir, `${stem}.json`), "utf8"),
);
}
writeJson(path.join(outDir, "snapshot.json"), snapshot);
console.log(`Snapshot: ${path.join(outDir, "snapshot.json")}`);
}
}
function parseMarker(stdout, marker) {
const line = stdout.split("\n").find((l) => l.startsWith(`${marker} `));
if (!line) return null;
try {
return JSON.parse(line.slice(marker.length + 1));
} catch (error) {
return { unparsed: line };
}
}
function fileStat(file) {
const buffer = fs.readFileSync(file);
return {
bytes: buffer.length,
sha256: crypto.createHash("sha256").update(buffer).digest("hex"),
};
}
function blendDigest(config, blend, outFile) {
const blenderApp = config.blenderApp || "/Applications/Blender.app";
const blender = path.join(blenderApp, "Contents", "MacOS", "Blender");
const run = spawnSync(blender, [
"--background", "--factory-startup",
"--python", path.join(repoRoot, "blender", "tools", "scene_digest.py"),
"--", "--blend", blend, "--out", outFile,
], { cwd: repoRoot, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
if (run.status !== 0) {
process.stderr.write(`${run.stdout || ""}${run.stderr || ""}`);
throw new Error(`scene_digest failed for ${blend}`);
}
return JSON.parse(fs.readFileSync(outFile, "utf8"));
}
function glbDigest(glb, outFile) {
const run = spawnSync(process.execPath, [
path.join(repoRoot, "scripts", "glb-digest.js"), glb, "--out", outFile,
], { cwd: repoRoot, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
if (run.status !== 0) {
process.stderr.write(`${run.stdout || ""}${run.stderr || ""}`);
throw new Error(`glb-digest failed for ${glb}`);
}
return JSON.parse(fs.readFileSync(outFile, "utf8"));
}
function writeJson(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
}
function compare(argv) {
const [a, b] = argv;
if (!a || !b) throw new Error("compare needs two labels");
const areas = fs.readdirSync(path.join(baselineRoot, a))
.filter((entry) => fs.existsSync(path.join(baselineRoot, a, entry, "snapshot.json")));
let differences = 0;
for (const area of areas) {
const left = readSnapshot(a, area);
const right = readSnapshot(b, area);
if (!right) {
console.log(`\n[${area}] missing in ${b} — skipped`);
continue;
}
const diffs = [];
diffValues("", left, right, diffs);
console.log(`\n=== ${area}: ${a} vs ${b} ===`);
if (!diffs.length) {
console.log("identical");
} else {
differences += diffs.length;
for (const line of diffs.slice(0, 200)) console.log(line);
if (diffs.length > 200) console.log(`… ${diffs.length - 200} more`);
}
}
console.log(`\n${differences === 0 ? "PARITY OK" : `PARITY DIFF (${differences})`}`);
process.exitCode = differences === 0 ? 0 : 2;
}
function readSnapshot(label, area) {
const file = path.join(baselineRoot, label, area, "snapshot.json");
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
}
function diffValues(pathKey, left, right, out) {
if (IGNORED_PATHS.has(pathKey)) return;
if (left === right) return;
const bothObjects = left && right && typeof left === "object" && typeof right === "object";
if (!bothObjects) {
out.push(` ${pathKey || "<root>"}: ${format(left)} -> ${format(right)}`);
return;
}
if (Array.isArray(left) !== Array.isArray(right)) {
out.push(` ${pathKey}: array/object mismatch`);
return;
}
if (Array.isArray(left)) {
if (left.length !== right.length) {
out.push(` ${pathKey}.length: ${left.length} -> ${right.length}`);
}
const limit = Math.min(left.length, right.length);
for (let i = 0; i < limit; i += 1) {
diffValues(`${pathKey}[${i}]`, left[i], right[i], out);
}
return;
}
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
for (const key of [...keys].sort()) {
diffValues(pathKey ? `${pathKey}.${key}` : key, left[key], right[key], out);
}
}
function format(value) {
if (value === undefined) return "<missing>";
const text = JSON.stringify(value);
return text && text.length > 120 ? `${text.slice(0, 117)}…` : text;
}
main();
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env node
"use strict";
// Reverse of the intermediates stage: pull manually-edited layers back out of
// <area>.gpkg into osm2streets_web_out/*.geojson and rebuild the merged scene.
//
// Use after hand-fixing geometry in QGIS. Re-running intermediates would
// regenerate the GeoPackage from OSM and throw those edits away.
//
// Every layer is exported to a staging directory and parsed before anything in
// outDir is touched: ogr2ogr exits non-zero on a missing layer but still leaves
// a zero-byte file behind, so a partial export must not reach the output tree.
const fs = require("fs");
const path = require("path");
const os = require("os");
const { execFileSync } = require("child_process");
const {
SCENE_LAYERS,
SCENE_FILE,
SCENE_STYLE_FILE,
layerFile,
mergeScene,
sceneStyle,
} = require("./lib/scene-layers");
const args = parseArgs(process.argv.slice(2));
const config = loadConfig(args);
const qgisApp = config.qgisApp || "/Applications/QGIS.app";
const qgisMacOS = path.join(qgisApp, "Contents", "MacOS");
const ogr2ogr = path.join(qgisMacOS, "ogr2ogr");
const ogrinfo = path.join(qgisMacOS, "ogrinfo");
const outDir = path.resolve(requireText(config.outDir, "outDir"));
const gpkgPath = path.resolve(requireText(config.gpkg, "gpkg"));
for (const exe of [ogr2ogr, ogrinfo]) {
if (!fs.existsSync(exe)) {
throw new Error(`QGIS executable not found: ${exe}`);
}
}
if (!fs.existsSync(gpkgPath)) {
throw new Error(`GeoPackage not found: ${gpkgPath}\nRun the intermediates stage first.`);
}
if (!fs.existsSync(outDir)) {
throw new Error(`GeoJSON output directory not found: ${outDir}`);
}
console.log(`Reimport: ${gpkgPath}`);
console.log(`Target: ${outDir}`);
const present = gpkgLayers();
const missing = SCENE_LAYERS.filter((layer) => !present.has(layer.id)).map((layer) => layer.id);
if (missing.length) {
throw new Error(
`GeoPackage is missing ${missing.length} layer(s): ${missing.join(", ")}\n` +
`Present: ${[...present].join(", ") || "(none)"}`,
);
}
const stagingDir = fs.mkdtempSync(path.join(os.tmpdir(), "osm2streets-reimport-"));
try {
const staged = SCENE_LAYERS.map((layer) => {
const stagedPath = path.join(stagingDir, layerFile(layer));
exportLayer(layer.id, stagedPath);
const collection = readCollection(stagedPath, layer.id);
console.log(`${layer.id}\tfeatures=${collection.features.length}`);
return { layer, stagedPath, collection };
});
for (const item of staged) {
// Copy rather than rename: the staging dir may be on another filesystem.
fs.copyFileSync(item.stagedPath, path.join(outDir, layerFile(item.layer)));
}
const byId = new Map(staged.map((item) => [item.layer.id, item.collection]));
const scene = mergeScene((layer) => byId.get(layer.id));
fs.writeFileSync(path.join(outDir, SCENE_FILE), JSON.stringify(scene));
fs.writeFileSync(
path.join(outDir, SCENE_STYLE_FILE),
JSON.stringify(sceneStyle(), null, 2),
);
console.log(`${path.join(outDir, SCENE_FILE)}\tfeatures=${scene.features.length}`);
const empty = staged.filter((item) => item.collection.features.length === 0);
if (empty.length) {
console.warn(`Warning: empty layer(s): ${empty.map((item) => item.layer.id).join(", ")}`);
}
} finally {
fs.rmSync(stagingDir, { recursive: true, force: true });
}
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("--")) continue;
const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
const next = argv[i + 1];
if (!next || next.startsWith("--")) {
out[key] = "true";
} else {
out[key] = next;
i += 1;
}
}
return out;
}
function loadConfig(cliArgs) {
const base = {};
if (cliArgs.config) {
const file = path.resolve(cliArgs.config);
if (!fs.existsSync(file)) {
throw new Error(`Config file not found: ${file}`);
}
Object.assign(base, JSON.parse(fs.readFileSync(file, "utf8")));
}
for (const key of ["qgisApp", "outDir", "gpkg"]) {
if (cliArgs[key] !== undefined) base[key] = cliArgs[key];
}
return base;
}
function requireText(value, key) {
if (typeof value !== "string" || value.trim() === "") {
throw new Error(`Missing config key: ${key}`);
}
return value;
}
function gdalEnv() {
return {
PROJ_LIB: path.join(qgisApp, "Contents", "Resources", "qgis", "proj"),
GDAL_DATA: path.join(qgisApp, "Contents", "Resources", "qgis", "gdal"),
};
}
function gpkgLayers() {
const output = execFileSync(ogrinfo, ["-q", gpkgPath], {
encoding: "utf8",
env: { ...process.env, ...gdalEnv() },
});
const names = new Set();
for (const line of output.split("\n")) {
const match = /^\s*\d+:\s+(\S+)/.exec(line);
if (match) names.add(match[1]);
}
return names;
}
function exportLayer(layerName, destination) {
// No COORDINATE_PRECISION here on purpose: the default already round-trips
// full double precision, and setting it explicitly makes GDAL run its
// precision-reduction pass, which drops vertices that collapse at the given
// resolution (measured: 28 points lost across 7 lane-arrow polygons).
execFileSync(ogr2ogr, [
"-f", "GeoJSON",
destination,
gpkgPath,
layerName,
], {
stdio: "inherit",
env: { ...process.env, ...gdalEnv() },
});
}
function readCollection(file, layerName) {
let parsed;
try {
parsed = JSON.parse(fs.readFileSync(file, "utf8"));
} catch (error) {
throw new Error(`Layer '${layerName}' did not export valid GeoJSON: ${error.message}`);
}
if (parsed.type !== "FeatureCollection" || !Array.isArray(parsed.features)) {
throw new Error(`Layer '${layerName}' did not export a FeatureCollection`);
}
return parsed;
}
-27
View File
@@ -1,27 +0,0 @@
"use strict";
const fs = require("fs");
const path = require("path");
function checkOutput({ areaId, outDir }) {
if (typeof areaId !== "string" || !areaId) throw new Error("RoadCompilerCheckInput.areaId must be a non-empty string");
if (typeof outDir !== "string" || !outDir) throw new Error("RoadCompilerCheckInput.outDir must be a non-empty string");
const compiledPath = path.join(outDir, "compiled.json");
if (!fs.existsSync(compiledPath)) throw new Error(`Native road output is missing: ${compiledPath}`);
const compiled = readJson(compiledPath);
const connectors = readJson(path.join(outDir, "layers", "connectors.geojson"));
const published = new Set(connectors.features.map((feature) => feature.properties.movement_id));
const failures = [];
for (const movement of compiled.movements || []) {
if (movement.geometryPublished && !published.has(movement.id)) failures.push(`Published movement has no connector: ${movement.id}`);
if (!movement.geometryPublished && published.has(movement.id)) failures.push(`Non-published movement has a connector: ${movement.id}`);
if (!movement.geometryStatus) failures.push(`Movement has no geometry status: ${movement.id}`);
}
const errors = (compiled.diagnostics || []).filter((item) => item.severity === "error");
const warnings = (compiled.diagnostics || []).filter((item) => item.severity === "warning");
return { schema: "native-road-check/v1", areaId, ok: failures.length === 0 && errors.length === 0, movementCount: (compiled.movements || []).length, connectorCount: connectors.features.length, errors: errors.map((item) => ({ id: item.id, rule: item.rule, message: item.message })), warningCount: warnings.length, failures };
}
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
module.exports = { checkOutput };
-141
View File
@@ -1,141 +0,0 @@
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const { compileRoadModel, compileGeometry, loadOverrides, validateOverrides, writeJsonAtomic } = require("./native-road");
const { loadOrGenerate, runtime } = require("../native-traffic-signals");
function compileInput(input) {
validateInput(input);
const area = {
id: input.areaId,
input: input.osmFile,
nativeRoad: input.options,
outputs: {
nativeRoadOverrides: input.overridesFile,
nativeTrafficSignals: input.trafficSignalsFile,
nativeRoadDir: input.outDir,
pipelineDir: input.stagingDir,
geojsonDir: input.comparisonDir || null,
},
};
const overrides = loadOverrides(area.outputs.nativeRoadOverrides);
const model = compileRoadModel(fs.readFileSync(area.input, "utf8"), overrides);
// Editing the source OSM retires the ids some overrides point at. Those
// entries can no longer match anything, so drop them with a diagnostic rather
// than aborting the whole compile — otherwise every OSM edit blocks the
// pipeline until the file is hand-pruned, one error message at a time.
const validated = validateOverrides(overrides, model, { skipStaleTargets: true });
for (const item of validated.stale) console.warn(`[warning] 忽略失效的 override(目标已不存在):${item.id} -> ${item.target}`);
fs.mkdirSync(area.outputs.pipelineDir, { recursive: true });
const compiled = compileGeometry(model, overrides, { edgeLines: area.nativeRoad.edgeLines, junctionTemplates: area.nativeRoad.junctionTemplates });
compiled.diagnostics.push(...validated.stale.map((item) => ({
id: `diagnostic:stale-override:${item.id}`,
severity: "warning",
subjectId: item.id,
sourceIds: [],
rule: "stale-override-target",
message: `该设置指向的 ${item.kind} 目标 ${item.target} 已不存在(OSM 改动后 id 失效),本次编译已忽略。可在工作台重新设置,或从 native-road-overrides.json 中删除。`,
geometry: null,
})));
const signalDocument = loadOrGenerate(area.outputs.nativeTrafficSignals, fs.readFileSync(area.input, "utf8"), compiled.vehicleStopLines, compiled.intersectionSurface);
const signalRuntime = runtime(signalDocument);
// Persist validation normalization, including one-time legacy heading migration.
writeJsonAtomic(area.outputs.nativeTrafficSignals, signalDocument);
const staging = fs.mkdtempSync(path.join(area.outputs.pipelineDir, "native-road-"));
try {
const result = {
schema: "native-road-compiled/v1",
areaId: area.id,
source: { osm: area.input, overrides: area.outputs.nativeRoadOverrides, trafficSignals: area.outputs.nativeTrafficSignals },
model: { roads: model.roads, endpoints: model.endpoints, connections: model.connections },
movements: compiled.movements,
trafficSignals: { assemblies: "traffic-signal-assemblies.json", runtime: "traffic-signals.json", count: signalRuntime.signals.length },
diagnostics: compiled.diagnostics,
layers: { roadSurface: "layers/road_surface.geojson", edgeLines: "layers/edge_lines.geojson", sidewalkSurface: "layers/sidewalk_surface.geojson", intersectionSurface: "layers/intersection_surface.geojson", laneCenterlines: "layers/lane_centerlines.geojson", laneSeparators: "layers/lane_separators.geojson", centerLines: "layers/center_lines.geojson", directionArrows: "layers/direction_arrows.geojson", turnArrows: "layers/turn_arrows.geojson", crosswalks: "layers/crosswalks.geojson", vehicleStopLines: "layers/vehicle_stop_lines.geojson", connectors: "layers/connectors.geojson" },
};
const comparison = compareOsm2Streets(area, result.model, compiled);
writeJsonAtomic(path.join(staging, "compiled.json"), result);
writeJsonAtomic(path.join(staging, "diagnostics.json"), { schema: "native-road-diagnostics/v1", diagnostics: compiled.diagnostics });
writeJsonAtomic(path.join(staging, "comparison.json"), comparison);
writeJsonAtomic(path.join(staging, "traffic-signal-assemblies.json"), signalDocument.assemblies);
writeJsonAtomic(path.join(staging, "traffic-signals.json"), signalRuntime);
writeJsonAtomic(path.join(staging, "layers", "road_surface.geojson"), compiled.roadSurface);
writeJsonAtomic(path.join(staging, "layers", "edge_lines.geojson"), compiled.edgeLines);
writeJsonAtomic(path.join(staging, "layers", "sidewalk_surface.geojson"), compiled.sidewalkSurface);
writeJsonAtomic(path.join(staging, "layers", "intersection_surface.geojson"), compiled.intersectionSurface);
writeJsonAtomic(path.join(staging, "layers", "lane_centerlines.geojson"), compiled.laneCenterlines);
writeJsonAtomic(path.join(staging, "layers", "lane_separators.geojson"), compiled.laneSeparators);
writeJsonAtomic(path.join(staging, "layers", "center_lines.geojson"), compiled.centerLines);
writeJsonAtomic(path.join(staging, "layers", "direction_arrows.geojson"), compiled.directionArrows);
writeJsonAtomic(path.join(staging, "layers", "turn_arrows.geojson"), compiled.turnArrows);
writeJsonAtomic(path.join(staging, "layers", "crosswalks.geojson"), compiled.crosswalks);
writeJsonAtomic(path.join(staging, "layers", "vehicle_stop_lines.geojson"), compiled.vehicleStopLines);
writeJsonAtomic(path.join(staging, "layers", "connectors.geojson"), compiled.connectors);
fs.rmSync(area.outputs.nativeRoadDir, { recursive: true, force: true });
fs.renameSync(staging, area.outputs.nativeRoadDir);
return { area, result, comparison };
} catch (error) {
fs.rmSync(staging, { recursive: true, force: true });
throw error;
}
}
function compareOsm2Streets(area, model, compiled) {
const source = area.outputs.geojsonDir ? path.join(area.outputs.geojsonDir, "road_surface.geojson") : null;
let featureCount = null;
if (source && fs.existsSync(source)) {
const collection = JSON.parse(fs.readFileSync(source, "utf8"));
featureCount = Array.isArray(collection.features) ? collection.features.length : null;
}
const diagnosticsBySeverity = {};
const diagnosticsByRule = {};
for (const item of compiled.diagnostics) {
diagnosticsBySeverity[item.severity] = (diagnosticsBySeverity[item.severity] || 0) + 1;
diagnosticsByRule[item.rule] = (diagnosticsByRule[item.rule] || 0) + 1;
}
const dangling = compiled.diagnostics.filter((item) => item.rule === "unconnected-interior-road-end");
const junctions = compiled.intersectionSurface.features;
const fallbackJunctions = junctions.filter((feature) => feature.properties.boundary_mode === "connector-convex-fallback");
return {
schema: "native-road-comparison/v2",
nativeRoadCount: model.roads.length,
nativeRoadSurfaceFeatures: compiled.roadSurface.features.length,
nativeSidewalkSurfaceFeatures: compiled.sidewalkSurface.features.length,
nativeJunctionSurfaceFeatures: compiled.intersectionSurface.features.length,
nativeApproachEnvelopeJunctions: junctions.length - fallbackJunctions.length,
nativeFallbackJunctions: fallbackJunctions.length,
nativeMaxJunctionExpansionRatio: junctions.reduce((maximum, feature) => Math.max(maximum, Number(feature.properties.expansion_ratio) || 0), 0),
nativeLaneCenterlineFeatures: compiled.laneCenterlines.features.length,
nativeLaneSeparatorFeatures: compiled.laneSeparators.features.length,
nativeCenterLineFeatures: compiled.centerLines.features.length,
nativeDirectionArrowFeatures: compiled.directionArrows.features.length,
nativeTurnArrowFeatures: compiled.turnArrows.features.length,
nativeCrosswalkFeatures: compiled.crosswalks.features.length,
nativeVehicleStopLineFeatures: compiled.vehicleStopLines.features.length,
nativeConnectorFeatures: compiled.connectors.features.length,
nativeMovementCount: compiled.movements.length,
nativePublishedMovementCount: compiled.movements.filter((movement) => movement.geometryPublished).length,
nativeConnectionCount: model.connections.length,
unconnectedInteriorRoadEnds: dangling.length,
unconnectedEndsWithManualCandidates: dangling.filter((item) => item.manualCandidates?.length).length,
diagnosticsBySeverity,
diagnosticsByRule,
osm2streetsRoadSurfaceFeatures: featureCount,
osm2streetsAvailable: featureCount !== null,
note: "Counts are coverage evidence only; geometry quality requires diagnostic and visual review.",
};
}
function validateInput(input) {
if (!input || typeof input !== "object") throw new Error("RoadCompilerInput must be an object");
for (const key of ["areaId", "osmFile", "outDir", "stagingDir", "overridesFile", "trafficSignalsFile"]) {
if (typeof input[key] !== "string" || input[key].trim() === "") throw new Error(`RoadCompilerInput.${key} must be a non-empty string`);
}
if (!input.options || typeof input.options !== "object") throw new Error("RoadCompilerInput.options must be an object");
if (typeof input.options.edgeLines !== "boolean") throw new Error("RoadCompilerInput.options.edgeLines must be a boolean");
if (!input.options.junctionTemplates || typeof input.options.junctionTemplates !== "object") throw new Error("RoadCompilerInput.options.junctionTemplates must be an object");
}
module.exports = { compileInput, validateInput };
-474
View File
@@ -1,474 +0,0 @@
"use strict";
const fs = require("fs");
const { convertGeoJson, boundsOf } = require("../reference/gaode");
const metricsCache = new WeakMap();
const CORNER_FILLET_SEGMENTS = 12;
// Must match DEFAULT_SIDEWALK_WIDTH_METERS in native-road.js so the corner band
// lines up with the straight strips it joins.
const SIDEWALK_WIDTH_METERS = 2;
// The straight strips are trimmed against the cluster boundary using the road
// centerline, so they stop a little beyond the carriageway end. Run the corner
// past that end and let the two overlap rather than chase an exact seam.
const SIDEWALK_CORNER_OVERRUN_METERS = 6;
function buildComplexJunctionGeometry(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = cluster.nodeIds.map((id) => helpers.junctionPlans.get(String(id))?.node).filter(Boolean);
if (nodes.length < 2) return { features: [], diagnostics: [helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-insufficient-nodes", "复合路口至少需要两个有效节点。", null)] };
const center = nodes.reduce((sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length], [0, 0]);
const approaches = [];
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches) {
const endpoint = approach.line.at(-1);
if (nodes.some((node) => node !== plan.node && helpers.distanceMeters(endpoint, node) < 4)) continue;
const heading = helpers.headingAtEndpoint(approach.line);
const length = helpers.lineLengthMeters(approach.line);
carriageways.push({ nodeId, approach, plan, heading, length });
if (approaches.some((item) => Math.abs(normalizeHeading(item.heading - heading)) < 20)) continue;
approaches.push({ nodeId, approach, plan, heading, length });
}
}
if (approaches.length < 3) return { features: [], diagnostics: [helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-insufficient-approaches", "复合路口无法识别足够的外部进口。", center)] };
const { calibration, coreRadius } = complexJunctionMetrics(cluster);
const sorted = [...approaches].sort((a, b) => a.heading - b.heading);
const arms = sorted.map((representative) => ({
representative,
heading: averageHeading(carriageways.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20).map((candidate) => candidate.heading)),
members: carriageways.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20),
}));
const outerRadius = complexJunctionMetrics(cluster).approachOuterRadius;
const boundaryParts = [];
const crosswalks = [];
const stopLines = [];
const islands = [];
const armCrosswalkRadius = coreRadius * .68;
for (const item of carriageways) {
const outer = pointOnCarriagewayRadius(item, center, outerRadius, helpers);
const inner = pointOnCarriagewayRadius(item, center, coreRadius * .7, helpers);
const outerHalf = item.approach.widthMeters / 2;
const innerHalf = outerHalf;
boundaryParts.push({ item, outer, inner, outerHalf, innerHalf });
const incomingRoad = item.approach.roadIds.map((roadId) => model.roads.find((road) => road.id === roadId)).find((road) => String(road?.sourceNodeIds.at(-1)) === String(item.nodeId));
if (incomingRoad) {
// Keep the stop bar just outside the road crosswalk. The previous fixed
// core-radius offset placed it nearly ten metres beyond the crossing.
const stopCenter = pointOnCarriagewayRadius(item, center, armCrosswalkRadius + 3, helpers);
const ring = [
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, -.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, outerHalf), item.heading, -.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, outerHalf), item.heading, .24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, .24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, -.24),
];
stopLines.push({ type: "Feature", properties: { native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`, cluster_id: cluster.id, kind: "complex-stop-line", road_id: incomingRoad.id, node_id: item.nodeId, direction: item.heading, provenance: "native-road-complex-junction-stop-line/v1" }, geometry: { type: "Polygon", coordinates: [ring] } });
}
}
// The four support lines provide a common corner frame, but each long
// crossing remains clipped to its OSM-derived road envelope. Corner islands
// fill the remaining frame gaps; crossings must never do that job.
for (const arm of arms) {
const envelope = armEnvelopeAtRadius(arm, armCrosswalkRadius, center, helpers);
if (!envelope) continue;
arm.crosswalkFrame = {
center: envelope.center,
groupDepth: 3.4,
supportHeading: normalizeHeading(arm.heading + 90),
envelopeWidthMeters: envelope.widthMeters,
};
}
const frameCorners = arms.map((arm, index) => {
const next = arms[(index + 1) % arms.length];
const delta = positiveHeadingDelta(arm.heading, next.heading);
if (delta < 45 || delta > 135 || !arm.crosswalkFrame || !next.crosswalkFrame) return null;
return supportLineIntersection(arm.crosswalkFrame, next.crosswalkFrame, center);
});
for (let index = 0; index < arms.length; index += 1) {
const arm = arms[index];
if (!arm.crosswalkFrame) continue;
const item = arm.representative;
const roadEdgeInset = .35;
const usableSpan = Math.max(.42, arm.crosswalkFrame.envelopeWidthMeters - roadEdgeInset * 2);
const endpoints = [
helpers.offsetCoordinate(arm.crosswalkFrame.center, arm.heading + 90, -usableSpan / 2),
helpers.offsetCoordinate(arm.crosswalkFrame.center, arm.heading + 90, usableSpan / 2),
];
const groupDepth = arm.crosswalkFrame.groupDepth;
const stripeWidth = .42;
const stripeCount = Math.max(6, Math.floor((usableSpan - stripeWidth) / .82) + 1);
const stripeSpacing = stripeCount > 1 ? (usableSpan - stripeWidth) / (stripeCount - 1) : 0;
arm.crosswalkFrame.center = midpoint(...endpoints);
arm.crosswalkFrame.endpoints = endpoints;
arm.crosswalkFrame.spanMeters = usableSpan;
arm.crosswalkFrame.roadEdgeInsetMeters = roadEdgeInset;
for (let stripe = 0; stripe < stripeCount; stripe += 1) {
const along = stripeWidth / 2 + stripe * stripeSpacing;
const centerPoint = helpers.offsetCoordinate(endpoints[0], bearing(...endpoints), along);
const ring = [
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, groupDepth / 2), arm.heading + 90, stripeWidth / 2),
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, stripeWidth / 2),
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
];
crosswalks.push({ type: "Feature", properties: { native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`, cluster_id: cluster.id, kind: "complex-crosswalk", crossing_node_id: item.nodeId, road_id: item.approach.roadIds[0], direction: arm.heading, radial_distance_m: armCrosswalkRadius, span_m: usableSpan, road_envelope_span_m: arm.crosswalkFrame.envelopeWidthMeters, road_edge_inset_m: roadEdgeInset, group_depth_m: groupDepth, stripe_width_m: stripeWidth, stripe_spacing_m: stripeSpacing, frame_center: arm.crosswalkFrame.center, frame_support_heading: arm.crosswalkFrame.supportHeading, provenance: "native-road-complex-junction-crosswalk/v6-road-clipped" }, geometry: { type: "Polygon", coordinates: [ring] } });
}
}
// The four arm groups are the sides of one pedestrian frame. Each diagonal
// group is anchored at the intersection of its adjacent side support lines,
// so all eight groups stay one composition when the OSM arms are skewed.
for (let index = 0; index < arms.length; index += 1) {
const first = arms[index];
const second = arms[(index + 1) % arms.length];
const delta = positiveHeadingDelta(first.heading, second.heading);
if (delta < 45 || delta > 135) continue;
if (!first.crosswalkFrame || !second.crosswalkFrame) continue;
const bisector = normalizeHeading(first.heading + delta / 2);
const frameCorner = frameCorners[index];
if (!frameCorner) continue;
const cornerStripeSpacing = .62;
const cornerStripeWidth = .4;
const cornerGroupHalfDepth = (5 * cornerStripeSpacing + cornerStripeWidth) / 2;
const endpointForCorner = (arm) => [...arm.crosswalkFrame.endpoints].sort((a, b) => helpers.distanceMeters(a, frameCorner) - helpers.distanceMeters(b, frameCorner))[0];
const outerEdgeAtCorner = (arm) => {
const endpoint = endpointForCorner(arm);
return [arm.heading, arm.heading + 180]
.map((heading) => helpers.offsetCoordinate(endpoint, heading, arm.crosswalkFrame.groupDepth / 2))
.sort((a, b) => directionalProjectionMeters(center, b, bisector) - directionalProjectionMeters(center, a, bisector))[0];
};
const islandBaseGap = .05;
const islandApexOffset = 1.5;
const islandBase = [outerEdgeAtCorner(first), outerEdgeAtCorner(second)].map((point) => helpers.offsetCoordinate(point, bisector, islandBaseGap));
const islandApex = helpers.offsetCoordinate(frameCorner, bisector, islandApexOffset);
const islandCrossingClearance = .2;
const cornerCrossingOffset = islandApexOffset + islandCrossingClearance + cornerGroupHalfDepth;
const islandInnerRadius = Math.min(...islandBase.map((point) => directionalProjectionMeters(center, point, bisector)));
const islandOuterRadius = directionalProjectionMeters(center, islandApex, bisector);
const cornerCrossingCenter = helpers.offsetCoordinate(frameCorner, bisector, cornerCrossingOffset);
const islandRing = roundedPolygonRing([islandBase[0], islandApex, islandBase[1]], .24);
islands.push({ type: "Feature", properties: { native_id: `complex-corner-island:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-corner-island", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, frame_corner: frameCorner, base_points: islandBase, apex_point: islandApex, inner_radius_m: islandInnerRadius, outer_radius_m: islandOuterRadius, base_width_m: helpers.distanceMeters(...islandBase), crossing_clearance_m: islandCrossingClearance, corner_rounding_ratio: .24, provenance: "native-road-complex-junction-corner/v7-road-gap-fill" }, geometry: { type: "Polygon", coordinates: [islandRing] } });
let cornerCrossingHalfSpan = .4;
for (let stripe = 0; stripe < 6; stripe += 1) {
const stripeOffset = (stripe - 2.5) * cornerStripeSpacing;
const stripeCenter = helpers.offsetCoordinate(cornerCrossingCenter, bisector, stripeOffset);
const stripeRadius = directionalProjectionMeters(center, stripeCenter, bisector);
const curbPair = limitedCornerPair(first, second, stripeRadius, bisector, center, 6.5, helpers);
if (!curbPair) continue;
const halfSpan = Math.max(.4, Math.min(6.5, helpers.distanceMeters(...curbPair)) / 2);
cornerCrossingHalfSpan = Math.max(cornerCrossingHalfSpan, halfSpan);
const stripePair = [
helpers.offsetCoordinate(stripeCenter, bisector - 90, halfSpan),
helpers.offsetCoordinate(stripeCenter, bisector + 90, halfSpan),
];
const ring = [
helpers.offsetCoordinate(stripePair[0], bisector, -cornerStripeWidth / 2),
helpers.offsetCoordinate(stripePair[1], bisector, -cornerStripeWidth / 2),
helpers.offsetCoordinate(stripePair[1], bisector, cornerStripeWidth / 2),
helpers.offsetCoordinate(stripePair[0], bisector, cornerStripeWidth / 2),
helpers.offsetCoordinate(stripePair[0], bisector, -cornerStripeWidth / 2),
];
crosswalks.push({ type: "Feature", properties: { native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`, cluster_id: cluster.id, kind: "complex-corner-crosswalk", corner_index: index + 1, direction: bisector, radial_distance_m: stripeRadius, frame_corner: frameCorner, from_heading: first.heading, to_heading: second.heading, provenance: "native-road-complex-junction-corner-crosswalk/v3" }, geometry: { type: "Polygon", coordinates: [ring] } });
}
}
// Each carriageway ends in its own rectangle, so adjacent arms meet at a
// sharp notch instead of a curb. A real corner is one tangent-continuous
// sweep between the two outermost road edges, so fit a fixed-radius fillet
// into the wedge those edges form and fill the sector behind it.
const cornerFills = [];
const sidewalkCorners = [];
const cornerDiagnostics = [];
const cornerRadius = Math.max(4, Math.min(25, Number(cluster.cornerRadiusMeters) || 12));
for (let index = 0; index < arms.length; index += 1) {
const first = arms[index];
const second = arms[(index + 1) % arms.length];
const delta = positiveHeadingDelta(first.heading, second.heading);
if (delta < 45 || delta > 135) continue;
const bisector = normalizeHeading(first.heading + delta / 2);
const edges = [first, second].map((arm) => cornerEdgeAt(arm, coreRadius + 6, bisector, center, helpers));
if (!edges.every(Boolean)) continue;
const apex = rayIntersection(edges[0], edges[1], center);
const apexReach = apex ? directionalProjectionMeters(center, apex, bisector) : null;
// The wedge apex has to sit ahead of the core and inside the arm handoff;
// outside that band the two edges are near parallel and any fillet fitted
// to them would sweep across the carriageways instead of the corner.
if (apexReach === null || apexReach < 1 || apexReach > outerRadius) {
cornerDiagnostics.push(helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-corner-fillet-fallback", "该夹角的道路边缘切线无法安全构造圆角,已保留直角过渡。", center));
continue;
}
// Tangent distance for a circle of `cornerRadius` inscribed in a wedge of
// opening `delta`, clamped so the tangent points stay on the built arms.
const tangentDistance = Math.min(cornerRadius / Math.tan(delta * Math.PI / 360), Math.max(2, outerRadius - apexReach));
const tangents = edges.map((edge) => helpers.offsetCoordinate(apex, edge.heading, tangentDistance));
const curve = quadraticCurve(tangents[0], apex, tangents[1], CORNER_FILLET_SEGMENTS);
const ring = [...curve, center, curve[0]];
if (!ring.every((point) => point.every(Number.isFinite))) continue;
cornerFills.push({ type: "Feature", properties: { native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-corner-fillet", complex_part: "corner-fillet", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, bisector_heading: bisector, corner_radius_m: cornerRadius, tangent_distance_m: Math.round(tangentDistance * 100) / 100, apex_reach_m: Math.round(apexReach * 100) / 100, provenance: "native-road-complex-junction-corner-fillet/v1" }, geometry: { type: "Polygon", coordinates: [ring] } });
// The straight pedestrian strips are trimmed at the cluster boundary, so
// two arms that both carry a footway still meet as two loose ends across
// an empty wedge. Bridge them along the curb the fillet already defines.
// The corner faces clockwise from `first` and counter-clockwise from
// `second`, so each arm must carry the footway on that facing side.
if (!armCarriesSidewalk(first, model, true) || !armCarriesSidewalk(second, model, false)) continue;
const curb = [
...edgeRunToRadius(apex, edges[0], tangentDistance, outerRadius + SIDEWALK_CORNER_OVERRUN_METERS, center, helpers).reverse(),
...curve.slice(1, -1),
...edgeRunToRadius(apex, edges[1], tangentDistance, outerRadius + SIDEWALK_CORNER_OVERRUN_METERS, center, helpers),
];
const outerEdge = offsetPolylineAwayFromCenter(curb, center, SIDEWALK_WIDTH_METERS, helpers);
const sidewalkRing = [...curb, ...outerEdge.slice().reverse(), curb[0]];
if (!sidewalkRing.every((point) => point.every(Number.isFinite)) || ringSelfIntersects(sidewalkRing)) {
cornerDiagnostics.push(helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-sidewalk-corner-fallback", "该夹角的人行道转角几何自交或无效,已跳过,两侧步行带保持断开。", center));
continue;
}
sidewalkCorners.push({ type: "Feature", properties: { native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-sidewalk-corner", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, bisector_heading: bisector, width_m: SIDEWALK_WIDTH_METERS, overrun_m: SIDEWALK_CORNER_OVERRUN_METERS, provenance: "native-road-complex-junction-sidewalk-corner/v1" }, geometry: { type: "Polygon", coordinates: [sidewalkRing] } });
}
const corePoints = boundaryParts.flatMap(({ item, inner, innerHalf }) => [helpers.offsetCoordinate(inner, item.heading + 90, innerHalf), helpers.offsetCoordinate(inner, item.heading - 90, innerHalf)]).sort((first, second) => angleAround(center, first) - angleAround(center, second));
const coreRing = roundedPolygonRing(corePoints, .16);
const features = [{ type: "Feature", properties: { native_id: `complex-junction:${cluster.id}:core`, cluster_id: cluster.id, kind: "complex-core", complex_part: "core", center, radius_m: coreRadius, configured_radius_m: cluster.coreRadiusMeters, approach_count: approaches.length, carriageway_count: carriageways.length, approach_headings: sorted.map((item) => Math.round(item.heading * 10) / 10), corner_rounding_ratio: .16, provenance: "native-road-complex-junction/v6-rounded-core" }, geometry: { type: "Polygon", coordinates: [coreRing] } }];
for (const { item, outer, inner, outerHalf, innerHalf } of boundaryParts) {
const ring = [helpers.offsetCoordinate(outer, item.heading + 90, outerHalf), helpers.offsetCoordinate(inner, item.heading + 90, innerHalf), helpers.offsetCoordinate(inner, item.heading - 90, innerHalf), helpers.offsetCoordinate(outer, item.heading - 90, outerHalf), helpers.offsetCoordinate(outer, item.heading + 90, outerHalf)];
features.push({ type: "Feature", properties: { native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`, cluster_id: cluster.id, kind: "complex-approach", complex_part: "carriageway", heading_deg: item.heading, lane_count: item.approach.roadIds.reduce((sum, roadId) => sum + (model.roads.find((road) => road.id === roadId)?.laneCount || 0), 0), width_m: item.approach.widthMeters, provenance: "native-road-complex-junction/v5" }, geometry: { type: "Polygon", coordinates: [ring] } });
}
// Corner fills come last so they overlay the rectangular carriageway ends
// they are smoothing; they never replace an OSM-derived road surface.
features.push(...cornerFills);
// `coreRadiusMeters` is only consulted when there is no reference geometry.
// Under calibration the radius comes from the reference span, so a configured
// value that silently does nothing has to be reported, not swallowed.
const configuredRadiusIgnored = calibration && Number.isFinite(cluster.coreRadiusMeters) && Math.abs(coreRadius - cluster.coreRadiusMeters) > .5;
const configurationDiagnostics = configuredRadiusIgnored
? [helpers.diagnostic("info", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-configured-radius-ignored", `已按参考几何校准核心半径为 ${Math.round(coreRadius * 10) / 10} 米,配置的 coreRadiusMeters=${cluster.coreRadiusMeters} 在有参考文件时不生效。`, center)]
: [];
return { features, islands: [...islands, ...sidewalkCorners], crosswalks, stopLines, center, approaches, diagnostics: [...cornerDiagnostics, ...configurationDiagnostics, helpers.diagnostic("info", `junction-cluster:${cluster.id}`, [...nodeIds], calibration ? "complex-junction-reference-calibrated" : "complex-junction-generated", calibration ? `已使用参考几何校准参数后,由 OSM/native 重新生成 ${approaches.length} 个进口、道路面、中央分隔带、斑马线和停止线。` : `已独立生成 ${approaches.length} 个进口、道路面、中央分隔带、斑马线和停止线。`, center)] };
}
function readReferenceCalibration(cluster) {
if (!cluster.referenceFile || !fs.existsSync(cluster.referenceFile)) return null;
try {
const converted = convertGeoJson(JSON.parse(fs.readFileSync(cluster.referenceFile, "utf8")));
const bounds = boundsOf({ features: converted.features.filter((feature) => [1, 2, 3, 4].includes(Number(feature.properties?.type))) });
const lonScale = 111320 * Math.cos(((bounds.minLat + bounds.maxLat) / 2) * Math.PI / 180);
return { longSpanMeters: (bounds.maxLon - bounds.minLon) * lonScale, shortSpanMeters: (bounds.maxLat - bounds.minLat) * 111320 };
} catch (_) {
return null;
}
}
function complexJunctionMetrics(cluster) {
if (metricsCache.has(cluster)) return metricsCache.get(cluster);
const calibration = readReferenceCalibration(cluster);
// Without a reference geometry `coreRadiusMeters` is the only size input the
// template has, so honour it literally within the schema's own 12..80 range.
// It used to be scaled by .52 and clamped to 17, which silently capped every
// unreferenced junction at a core far smaller than its own approach envelope
// — a 24 m dual-carriageway arm was being fitted into a 16.6 m core no matter
// what the config asked for. The calibrated branch is unchanged.
const coreRadius = calibration
? Math.max(12, Math.min(24, calibration.shortSpanMeters * .14))
: Math.max(12, Math.min(80, Number(cluster.coreRadiusMeters) || 28));
const metrics = { calibration, coreRadius, approachOuterRadius: coreRadius + (Number(cluster.outerRadiusExtraMeters) || 18) };
metricsCache.set(cluster, metrics);
return metrics;
}
function normalizeHeading(value) { return ((value + 180) % 360 + 360) % 360 - 180; }
// `arm.heading` points outward from the junction, so the corner clockwise from
// it sits at heading+90 and the one counter-clockwise at heading-90. A road's
// own sidewalk flags are relative to its digitisation direction, so flip them
// whenever the arm runs against that direction.
function armCarriesSidewalk(arm, model, cornerIsClockwise) {
return arm.members.some((member) => member.approach.roadIds
.map((roadId) => model.roads.find((road) => road.id === roadId))
.filter(Boolean)
.some((road) => {
const outwardIsForward = String(road.sourceNodeIds[0]) === String(member.nodeId);
const onClockwiseSide = outwardIsForward ? road.sidewalkRight : road.sidewalkLeft;
const onCounterClockwiseSide = outwardIsForward ? road.sidewalkLeft : road.sidewalkRight;
return Boolean(cornerIsClockwise ? onClockwiseSide : onCounterClockwiseSide);
}));
}
// Walk outward along a wedge edge from its tangent point until the curb reaches
// `targetRadius`, so the corner band overlaps the straight strip it joins.
function edgeRunToRadius(apex, edge, tangentDistance, targetRadius, center, helpers) {
const points = [];
for (let extra = 0; extra <= 40; extra += 2) {
const point = helpers.offsetCoordinate(apex, edge.heading, tangentDistance + extra);
points.push(point);
if (helpers.distanceMeters(point, center) >= targetRadius) break;
}
return points;
}
// Offset each vertex along the polyline normal that increases distance from the
// junction centre. The curb is star-shaped around that centre, so "farther from
// the centre" is a reliable stand-in for "on the pedestrian side".
function offsetPolylineAwayFromCenter(points, center, meters, helpers) {
return points.map((point, index) => {
const previous = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
const tangent = previous === next ? 0 : bearing(previous, next);
return [tangent + 90, tangent - 90]
.map((heading) => helpers.offsetCoordinate(point, heading, meters))
.sort((first, second) => helpers.distanceMeters(second, center) - helpers.distanceMeters(first, center))[0];
});
}
function ringSelfIntersects(ring) {
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const straddles = (p1, p2, p3, p4) => {
const d1 = cross(p3, p4, p1); const d2 = cross(p3, p4, p2);
const d3 = cross(p1, p2, p3); const d4 = cross(p1, p2, p4);
return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0));
};
for (let first = 0; first < ring.length - 1; first += 1) {
for (let second = first + 2; second < ring.length - 1; second += 1) {
if (first === 0 && second === ring.length - 2) continue;
if (straddles(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true;
}
}
return false;
}
function angleAround(center, point) { return Math.atan2(point[1] - center[1], point[0] - center[0]); }
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos(origin[1] * Math.PI / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = (heading + 90) * Math.PI / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function bearing(first, second) {
const east = (second[0] - first[0]) * Math.cos(first[1] * Math.PI / 180);
const north = second[1] - first[1];
return Math.atan2(east, north) * 180 / Math.PI;
}
function midpoint(first, second) { return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2]; }
function averageHeading(headings) {
const vector = headings.reduce((sum, heading) => {
const radians = heading * Math.PI / 180;
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
}, [0, 0]);
return Math.atan2(vector[0], vector[1]) * 180 / Math.PI;
}
function positiveHeadingDelta(first, second) { return ((second - first) % 360 + 360) % 360; }
function pointOnCarriagewayRadius(item, center, radius, helpers) {
const start = item.approach.line[0];
const startRadius = directionalProjectionMeters(center, start, item.heading);
return helpers.pointAlongLine(item.approach.line, Math.max(0, Math.min(item.length, radius - startRadius)));
}
function armEnvelopeAtRadius(arm, radius, center, helpers) {
if (!arm.members.length) return null;
const centers = arm.members.map((member) => pointOnCarriagewayRadius(member, center, radius, helpers));
const reference = centers[0];
let minimum = Infinity;
let maximum = -Infinity;
centers.forEach((point, index) => {
const lateral = signedLateralMeters(reference, point, arm.heading);
const halfWidth = arm.members[index].approach.widthMeters / 2;
minimum = Math.min(minimum, lateral - halfWidth);
maximum = Math.max(maximum, lateral + halfWidth);
});
if (!Number.isFinite(minimum) || maximum - minimum < 1) return null;
return { center: helpers.offsetCoordinate(reference, arm.heading + 90, (minimum + maximum) / 2), widthMeters: maximum - minimum };
}
function supportLineIntersection(first, second, origin) {
const lonScale = 111320 * Math.cos(origin[1] * Math.PI / 180);
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
const firstPoint = toLocal(first.center);
const secondPoint = toLocal(second.center);
const direction = (heading) => {
const radians = heading * Math.PI / 180;
return [Math.sin(radians), Math.cos(radians)];
};
const firstDirection = direction(first.supportHeading);
const secondDirection = direction(second.supportHeading);
const denominator = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
if (Math.abs(denominator) < 1e-6) return null;
const delta = [secondPoint[0] - firstPoint[0], secondPoint[1] - firstPoint[1]];
const distanceAlongFirst = (delta[0] * secondDirection[1] - delta[1] * secondDirection[0]) / denominator;
const intersection = [firstPoint[0] + firstDirection[0] * distanceAlongFirst, firstPoint[1] + firstDirection[1] * distanceAlongFirst];
return [origin[0] + intersection[0] / lonScale, origin[1] + intersection[1] / 111320];
}
function limitedCornerPair(first, second, radius, bisector, center, maxWidth, helpers) {
const pair = [cornerEdgeAtRadius(first, radius, bisector, center, helpers), cornerEdgeAtRadius(second, radius, bisector, center, helpers)];
if (!pair.every(Boolean)) return null;
const width = helpers.distanceMeters(pair[0], pair[1]);
const middle = midpoint(pair[0], pair[1]);
const halfWidth = Math.max(.4, Math.min(width, maxWidth) / 2);
const acrossHeading = width > .1 ? bearing(pair[0], pair[1]) : bisector + 90;
return [helpers.offsetCoordinate(middle, acrossHeading + 180, halfWidth), helpers.offsetCoordinate(middle, acrossHeading, halfWidth)];
}
function cornerEdgeAtRadius(arm, radius, bisector, center, helpers) {
return cornerEdgeAt(arm, radius, bisector, center, helpers)?.point || null;
}
function cornerEdgeAt(arm, radius, bisector, center, helpers) {
const candidates = arm.members.flatMap((member) => {
const point = pointOnCarriagewayRadius(member, center, radius, helpers);
const halfWidth = member.approach.widthMeters / 2;
return [90, -90].map((side) => ({ point: helpers.offsetCoordinate(point, member.heading + side, halfWidth), heading: member.heading }));
});
return candidates.sort((first, second) => directionalProjectionMeters(center, second.point, bisector) - directionalProjectionMeters(center, first.point, bisector))[0] || null;
}
function rayIntersection(first, second, origin) {
const lonScale = 111320 * Math.cos(origin[1] * Math.PI / 180);
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
const direction = (heading) => {
const radians = heading * Math.PI / 180;
return [Math.sin(radians), Math.cos(radians)];
};
const firstPoint = toLocal(first.point);
const secondPoint = toLocal(second.point);
const firstDirection = direction(first.heading);
const secondDirection = direction(second.heading);
const denominator = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
if (Math.abs(denominator) < 1e-4) return null;
const delta = [secondPoint[0] - firstPoint[0], secondPoint[1] - firstPoint[1]];
const distanceAlongFirst = (delta[0] * secondDirection[1] - delta[1] * secondDirection[0]) / denominator;
const local = [firstPoint[0] + firstDirection[0] * distanceAlongFirst, firstPoint[1] + firstDirection[1] * distanceAlongFirst];
if (!local.every(Number.isFinite)) return null;
return [origin[0] + local[0] / lonScale, origin[1] + local[1] / 111320];
}
function quadraticCurve(start, control, end, segments) {
const result = [];
for (let index = 0; index <= segments; index += 1) {
const t = index / segments;
const u = 1 - t;
result.push([u * u * start[0] + 2 * u * t * control[0] + t * t * end[0], u * u * start[1] + 2 * u * t * control[1] + t * t * end[1]]);
}
return result;
}
function directionalProjectionMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos(origin[1] * Math.PI / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = heading * Math.PI / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function smoothClosedRing(vertices) {
// Curb-edge candidates can arrive in opposite winding orders when an OSM
// carriageway bends slightly. Sort this local corner only around its own
// centroid before rounding, avoiding a self-crossing safety island while
// keeping the global junction boundary fully OSM-driven.
const centroid = vertices.reduce((sum, point) => [sum[0] + point[0] / vertices.length, sum[1] + point[1] / vertices.length], [0, 0]);
const ordered = [...vertices].sort((first, second) => Math.atan2(first[1] - centroid[1], first[0] - centroid[0]) - Math.atan2(second[1] - centroid[1], second[0] - centroid[0]));
const points = ordered.flatMap((point, index) => {
const next = ordered[(index + 1) % ordered.length];
return [interpolateCoordinate(point, next, .18), interpolateCoordinate(point, next, .82)];
});
return [...points, points[0]];
}
function roundedPolygonRing(vertices, ratio) {
const points = vertices.flatMap((point, index) => {
const previous = vertices[(index - 1 + vertices.length) % vertices.length];
const next = vertices[(index + 1) % vertices.length];
return [interpolateCoordinate(previous, point, 1 - ratio), interpolateCoordinate(point, next, ratio)];
});
return [...points, points[0]];
}
function interpolateCoordinate(first, second, ratio) { return [first[0] + (second[0] - first[0]) * ratio, first[1] + (second[1] - first[1]) * ratio]; }
module.exports = { buildComplexJunctionGeometry, complexJunctionMetrics };
File diff suppressed because it is too large. Load diff
-502
View File
@@ -1,502 +0,0 @@
"use strict";
const fs = require("fs");
const path = require("path");
const { laneCenterline } = require("../geometry/lane-geometry");
const ASSET_MANIFEST = path.resolve(__dirname, "..", "..", "..", "..", "assets", "lane-icons", "manifest.json");
const LANE_WIDTH_METERS = 3.2;
const PLACEMENT_DISTANCE_METERS = 9;
const SPATIAL_MATCH_MAX_DISTANCE_METERS = 18;
const SPATIAL_MATCH_MIN_ALIGNMENT = Math.cos(Math.PI / 6);
// Existing osm2streets lane arrows are approximately 1.4 m across. Keep the
// 25-unit upstream icon at the same on-road scale rather than at screen scale.
const SVG_METERS_PER_UNIT = 0.10;
function loadManifest(file = ASSET_MANIFEST) {
const manifest = JSON.parse(fs.readFileSync(file, "utf8"));
if (!Array.isArray(manifest.assets)) throw new Error("turn-lane asset manifest has no assets array");
return manifest;
}
function supportedAssets(manifest = loadManifest()) {
return new Map(manifest.assets
.filter((asset) => asset.supported === true && asset.tested === true)
.map((asset) => [asset.id, asset]));
}
function buildCustomTurnLaneArrows(osm, options = {}) {
const enabled = options.enabled === true;
const diagnostics = [];
if (!enabled) return { features: [], diagnostics: [{ reason: "disabled" }] };
const assets = supportedAssets(options.manifest);
const endpointRoadCounts = roadCountsByNode(osm);
const networkIntersectionNodes = new Set((options.network?.intersections || [])
.flatMap(([, intersection]) => intersection.osm_ids || []).map(Number));
const features = [];
const ways = [...osm.ways.values()].sort((a, b) => a.id - b.id);
for (const way of ways) {
for (const direction of ["forward", "backward"]) {
const tag = way.tags[`turn:lanes:${direction}`];
if (!tag) continue;
const laneCount = directionalLaneCount(way, direction);
if (!laneCount) {
diagnostics.push(skip(way, direction, "missing_lane_count"));
continue;
}
const endpoint = endpointGeometry(osm, way, direction, endpointRoadCounts, networkIntersectionNodes);
if (!endpoint) {
diagnostics.push(skip(way, direction, "indeterminate_intersection_endpoint"));
continue;
}
const maneuvers = String(tag).split("|").map((value) => normalizeManeuver(value));
for (let laneIndex = 0; laneIndex < maneuvers.length; laneIndex += 1) {
const maneuver = maneuvers[laneIndex];
const asset = assets.get(maneuver);
if (!asset) {
diagnostics.push(skip(way, direction, "unsupported_or_untested_maneuver", { lane_index: laneIndex, maneuver }));
continue;
}
if (laneIndex >= laneCount) {
diagnostics.push(skip(way, direction, "lane_index_exceeds_lane_count", { lane_index: laneIndex, maneuver }));
continue;
}
const resolvedPlacement = lanePlacement(way, direction, laneIndex, endpoint, options.lanePolygons, options.crosswalkStripes, options.stopLines);
if (resolvedPlacement?.blocked) {
diagnostics.push(skip(way, direction, "no_safe_turn_arrow_position", { lane_index: laneIndex, maneuver }));
continue;
}
const placement = resolvedPlacement || fallbackLanePlacement(endpoint, direction, laneIndex, options.crosswalkStripes, options.stopLines);
if (!placement) {
diagnostics.push(skip(way, direction, "no_safe_turn_arrow_position", { lane_index: laneIndex, maneuver }));
continue;
}
const parts = templateFor(asset.id, options.manifest);
for (let partIndex = 0; partIndex < parts.length; partIndex += 1) {
features.push(makeFeature(way, direction, laneIndex, maneuver, asset, partIndex, parts[partIndex], placement.center, placement));
}
}
}
}
return { features, diagnostics };
}
function normalizeManeuver(value) {
const parts = String(value || "").split(";").map((part) => part.trim()).filter(Boolean).sort();
const supported = new Map([
["through", "through"], ["left", "left"], ["right", "right"],
["left;through", "through;left"], ["right;through", "through;right"],
["left;right;through", "through;left;right"],
]);
return supported.get(parts.join(";")) || parts.join(";");
}
function directionalLaneCount(way, direction) {
const specific = Number(way.tags[`lanes:${direction}`]);
if (Number.isInteger(specific) && specific > 0) return specific;
const total = Number(way.tags.lanes);
if (Number.isInteger(total) && total > 0 && total % 2 === 0 && !isOneway(way)) return total / 2;
if (Number.isInteger(total) && total > 0 && isOneway(way)) return total;
return null;
}
function roadCountsByNode(osm) {
const out = new Map();
for (const way of osm.ways.values()) {
if (!way.tags.highway || way.tags.highway === "service") continue;
for (const ref of new Set(way.refs)) out.set(ref, (out.get(ref) || 0) + 1);
}
return out;
}
function endpointGeometry(osm, way, direction, roadCounts, networkIntersectionNodes) {
const forward = direction === "forward";
const endpointIndex = forward ? way.refs.length - 1 : 0;
const neighborIndex = forward ? endpointIndex - 1 : 1;
const node = osm.nodes.get(way.refs[endpointIndex]);
const neighbor = osm.nodes.get(way.refs[neighborIndex]);
if (!node || !neighbor) return null;
const networkSaysIntersection = networkIntersectionNodes && networkIntersectionNodes.size > 0 && networkIntersectionNodes.has(node.id);
if (!networkSaysIntersection && (roadCounts.get(node.id) || 0) < 3) return null;
const meters = metersForLat(node.lat);
// For both directions, point from the adjacent road node to the endpoint.
// At a forward endpoint this is the OSM-way direction; at a backward
// endpoint it is the reverse OSM-way direction, i.e. the actual travel
// direction used by turn:lanes:backward.
const raw = [node.lon - neighbor.lon, node.lat - neighbor.lat];
const axis = normalizeMetersVector(raw, meters);
if (!axis) return null;
return { node, axis, right: [axis[1], -axis[0]], meters };
}
function laneCenter(endpoint, direction, laneIndex, meters) {
const lateral = (laneIndex + 0.5) * LANE_WIDTH_METERS;
// The local axis always follows travel, so moving back from either endpoint
// places the marking on its approach lane before the intersection.
return addMeters([endpoint.node.lon, endpoint.node.lat], endpoint.axis, -PLACEMENT_DISTANCE_METERS, endpoint.right, lateral, meters);
}
function fallbackLanePlacement(endpoint, direction, laneIndex, crosswalkStripes, stopLines) {
const lateral = (laneIndex + 0.5) * LANE_WIDTH_METERS;
for (const distance of [PLACEMENT_DISTANCE_METERS, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]) {
const center = addMeters([endpoint.node.lon, endpoint.node.lat], endpoint.axis, -distance, endpoint.right, lateral, endpoint.meters);
if (!nearIntersectionMarking(center, endpoint.axis, crosswalkStripes, stopLines, endpoint.meters)) {
return { center, axis: endpoint.axis, right: endpoint.right, meters: endpoint.meters, placementDistance: distance, placementSource: "osm_way_fallback" };
}
}
return null;
}
function lanePlacement(way, direction, laneIndex, endpoint, lanePolygons, crosswalkStripes, stopLines) {
if (!Array.isArray(lanePolygons)) return null;
const expectedDirection = direction === "forward" ? "Fwd" : "Back";
const directionalCandidates = lanePolygons.filter((feature) =>
feature.properties?.type === "Driving" &&
feature.properties.direction === expectedDirection
);
let candidates = directionalCandidates.filter((feature) =>
(feature.properties.osm_way_ids || []).map(Number).includes(way.id)
);
let placementSource = "driving_lane_centerline";
let spatialAnchors = null;
if (!candidates.length) {
const ranked = directionalCandidates
.map((feature) => ({ feature, anchor: spatialLaneAnchor(feature, endpoint) }))
.filter(({ anchor }) => anchor)
.filter(({ anchor }) => anchor.alignment >= SPATIAL_MATCH_MIN_ALIGNMENT && anchor.distance <= SPATIAL_MATCH_MAX_DISTANCE_METERS)
.sort((a, b) => a.anchor.distance - b.anchor.distance || a.anchor.lateral - b.anchor.lateral || Number(a.feature.properties.index) - Number(b.feature.properties.index));
if (ranked.length) {
// JOSM may split a tagged OSM way into temporary negative IDs. Those IDs
// are absent from osm2streets' rendered polygons, so associate the full
// physical approach by endpoint proximity and road-axis alignment.
candidates = ranked.map(({ feature }) => feature);
placementSource = "spatial_driving_lane_centerline";
spatialAnchors = new Map(ranked.map(({ feature, anchor }) => [feature, anchor]));
}
}
candidates.sort((a, b) => {
const lateralA = spatialAnchors?.get(a)?.lateral;
const lateralB = spatialAnchors?.get(b)?.lateral;
if (Number.isFinite(lateralA) && Number.isFinite(lateralB) && lateralA !== lateralB) return lateralA - lateralB;
return Number(a.properties.index) - Number(b.properties.index);
});
const lane = candidates[laneIndex];
const spatialAnchor = spatialAnchors?.get(lane);
if (spatialAnchor) {
const sampled = placementDistances().map((distance) => ({
center: sampleCenterlineAwayFromEndpoint(spatialAnchor, distance, endpoint.meters),
distance,
})).find(({ center }) => center && !nearIntersectionMarking(center, spatialAnchor.axis, crosswalkStripes, stopLines, endpoint.meters));
if (!sampled) return { blocked: true };
return { center: sampled.center, axis: spatialAnchor.axis, right: [spatialAnchor.axis[1], -spatialAnchor.axis[0]], meters: endpoint.meters, placementDistance: sampled.distance, placementSource };
}
const centerline = laneCenterline(lane);
if (!centerline) return null;
const startsAtEndpoint = direction === "backward";
const ordered = startsAtEndpoint ? centerline : [...centerline].reverse();
const sampled = [PLACEMENT_DISTANCE_METERS, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
.map((distance) => ({ center: samplePolyline(ordered, distance, endpoint.meters), distance }))
.find(({ center }) => center && !nearIntersectionMarking(center, axisForLane(ordered, endpoint.meters), crosswalkStripes, stopLines, endpoint.meters));
if (!sampled) return { blocked: true };
const axis = axisForLane(ordered, endpoint.meters);
if (!axis) return null;
return { center: sampled.center, axis, right: [axis[1], -axis[0]], meters: endpoint.meters, placementDistance: sampled.distance, placementSource };
}
function spatialLaneAnchor(lane, endpoint) {
const centerline = laneCenterline(lane);
if (!centerline) return null;
let best = null;
for (let index = 0; index < centerline.length - 1; index += 1) {
const start = centerline[index];
const end = centerline[index + 1];
const point = closestPointOnSegment([endpoint.node.lon, endpoint.node.lat], start, end, endpoint.meters);
const distance = Math.hypot((point[0] - endpoint.node.lon) * endpoint.meters.lon, (point[1] - endpoint.node.lat) * endpoint.meters.lat);
const tangent = normalizeMetersVector(subtractPoint(end, start), endpoint.meters);
if (!tangent || (best && distance >= best.distance)) continue;
const dot = tangent[0] * endpoint.axis[0] + tangent[1] * endpoint.axis[1];
const axis = dot >= 0 ? tangent : [-tangent[0], -tangent[1]];
const offset = subtractPoint(point, [endpoint.node.lon, endpoint.node.lat]);
best = {
point,
distance,
axis,
alignment: Math.abs(dot),
lateral: offset[0] * endpoint.right[0] * endpoint.meters.lon + offset[1] * endpoint.right[1] * endpoint.meters.lat,
centerline,
segmentIndex: index,
};
}
return best;
}
function placementDistances() {
return [PLACEMENT_DISTANCE_METERS, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42];
}
function sampleCenterlineAwayFromEndpoint(anchor, distanceMeters, meters) {
const { centerline, segmentIndex } = anchor;
const start = centerline[segmentIndex];
const end = centerline[segmentIndex + 1];
const tangent = normalizeMetersVector(subtractPoint(end, start), meters);
if (!tangent) return null;
// Walk away from the junction along the rendered centerline. This preserves
// curved or split lane geometry instead of approximating it with a tangent.
const towardEnd = tangent[0] * anchor.axis[0] + tangent[1] * anchor.axis[1] < 0;
const points = [anchor.point];
if (towardEnd) {
for (let index = segmentIndex + 1; index < centerline.length; index += 1) points.push(centerline[index]);
} else {
for (let index = segmentIndex; index >= 0; index -= 1) points.push(centerline[index]);
}
return samplePolyline(points, distanceMeters, meters);
}
function closestPointOnSegment(point, start, end, meters) {
const dx = (end[0] - start[0]) * meters.lon;
const dy = (end[1] - start[1]) * meters.lat;
const px = (point[0] - start[0]) * meters.lon;
const py = (point[1] - start[1]) * meters.lat;
const lengthSquared = dx * dx + dy * dy;
const ratio = lengthSquared ? Math.max(0, Math.min(1, (px * dx + py * dy) / lengthSquared)) : 0;
return [start[0] + ratio * (end[0] - start[0]), start[1] + ratio * (end[1] - start[1])];
}
function axisForLane(ordered, meters) {
return normalizeMetersVector(subtractPoint(ordered[0], ordered[1]), meters);
}
function nearIntersectionMarking(center, axis, stripes, stopLines, meters) {
if (!axis) return true;
const right = [axis[1], -axis[0]];
const samples = [];
for (const forward of [-0.2, 0.5, 1.2, 1.9, 2.2]) {
for (const lateral of [-1.6, -0.8, 0, 0.8, 1.6]) {
samples.push(addMeters(center, axis, forward, right, lateral, meters));
}
}
return [...(stripes || []), ...(stopLines || [])].some((feature) => samples.some((point) => nearFeature(point, feature, meters)));
}
function nearFeature(point, feature, meters) {
const ring = feature.geometry?.type === "Polygon" ? feature.geometry.coordinates?.[0] : null;
if (!ring?.length) return false;
const xs = ring.map((coordinate) => coordinate[0]);
const ys = ring.map((coordinate) => coordinate[1]);
const clearance = 0.7;
const dx = Math.max((Math.min(...xs) - point[0]) * meters.lon, 0, (point[0] - Math.max(...xs)) * meters.lon);
const dy = Math.max((Math.min(...ys) - point[1]) * meters.lat, 0, (point[1] - Math.max(...ys)) * meters.lat);
return Math.hypot(dx, dy) < clearance;
}
function subtractPoint([lon, lat], [otherLon, otherLat]) {
return [lon - otherLon, lat - otherLat];
}
function samplePolyline(points, distanceMeters, meters) {
let remaining = distanceMeters;
for (let index = 0; index < points.length - 1; index += 1) {
const start = points[index];
const end = points[index + 1];
const vector = normalizeMetersVector(subtractPoint(end, start), meters);
const length = Math.hypot((end[0] - start[0]) * meters.lon, (end[1] - start[1]) * meters.lat);
if (!vector || !length) continue;
if (remaining <= length) return addMeters(start, vector, remaining, [0, 0], 0, meters);
remaining -= length;
}
return null;
}
function makeFeature(way, direction, laneIndex, maneuver, asset, partIndex, template, center, endpoint) {
const ring = template.map(([rightMeters, forwardMeters]) => addMeters(center, endpoint.axis, forwardMeters, endpoint.right, rightMeters, endpoint.meters));
return {
type: "Feature",
properties: {
type: "lane arrow",
source: "osm_turn_lanes",
osm_way_id: way.id,
direction,
lane_index: laneIndex,
maneuver,
source_asset: asset.id,
source_asset_path: asset.source,
arrow_part: partIndex,
// SVG strokes and fills are expanded separately for GeoJSON validity.
// This stable key lets the QGIS normalizer restore one rendered arrow.
custom_arrow_id: `${way.id}:${direction}:${laneIndex}:${maneuver}`,
placement_distance_meters: endpoint.placementDistance ?? PLACEMENT_DISTANCE_METERS,
placement_source: endpoint.placementSource ?? "osm_way_fallback",
},
geometry: { type: "Polygon", coordinates: [ring] },
};
}
function skip(way, direction, reason, extra = {}) {
return { source: "osm_turn_lanes", osm_way_id: way.id, direction, reason, ...extra };
}
function isOneway(way) {
return ["yes", "true", "1"].includes(String(way.tags.oneway || "").toLowerCase());
}
function metersForLat(lat) {
return { lon: 111320 * Math.cos((lat * Math.PI) / 180), lat: 110540 };
}
function normalizeMetersVector([dxLon, dyLat], meters) {
const x = dxLon * meters.lon;
const y = dyLat * meters.lat;
const length = Math.hypot(x, y);
return length ? [x / length, y / length] : null;
}
function addMeters(center, axis, axisDistance, right, rightDistance, meters) {
return [
center[0] + (axis[0] * axisDistance + right[0] * rightDistance) / meters.lon,
center[1] + (axis[1] * axisDistance + right[1] * rightDistance) / meters.lat,
];
}
function arrowRingsAt(maneuver, center, axis, manifest = loadManifest()) {
const normalized = normalizeManeuver(maneuver);
if (!supportedAssets(manifest).has(normalized) || !Array.isArray(center) || !Array.isArray(axis)) return [];
const meters = metersForLat(center[1]);
const length = Math.hypot(axis[0], axis[1]);
if (!Number.isFinite(length) || length < 0.001) return [];
const forward = [axis[0] / length, axis[1] / length];
const right = [forward[1], -forward[0]];
return templateFor(normalized, manifest).map((template) => template.map(([rightMeters, forwardMeters]) =>
addMeters(center, forward, forwardMeters, right, rightMeters, meters)));
}
function templateFor(assetId, manifest = loadManifest()) {
const asset = supportedAssets(manifest).get(assetId);
if (!asset) throw new Error(`Unsupported or untested turn-lane asset: ${assetId}`);
return angularTemplate(assetId);
}
function angularTemplate(assetId) {
const shaftWidth = 0.30;
const shaftHalf = shaftWidth / 2;
const straightBase = 1.18;
const straightTip = 1.92;
const rectangle = (minX, minY, maxX, maxY) => [
[minX, minY], [maxX, minY], [maxX, maxY], [minX, maxY], [minX, minY],
];
const throughHead = () => [[0, straightTip], [-0.42, straightBase], [-shaftHalf, straightBase], [-shaftHalf, 0], [shaftHalf, 0], [shaftHalf, straightBase], [0.42, straightBase], [0, straightTip]];
const diagonalShaft = (side) => {
const start = [0, 0.56];
const end = [side * 0.72, 0.96];
const length = Math.hypot(end[0] - start[0], end[1] - start[1]);
const normal = [-(end[1] - start[1]) / length * shaftHalf, (end[0] - start[0]) / length * shaftHalf];
return [[start[0] + normal[0], start[1] + normal[1]], [end[0] + normal[0], end[1] + normal[1]], [end[0] - normal[0], end[1] - normal[1]], [start[0] - normal[0], start[1] - normal[1]], [start[0] + normal[0], start[1] + normal[1]]];
};
const diagonalHead = (side) => {
const base = [side * 0.60, 0.89];
const tip = [side * 1.22, 1.24];
const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]);
const normal = [-(tip[1] - base[1]) / length * 0.36, (tip[0] - base[0]) / length * 0.36];
return [tip, [base[0] + normal[0], base[1] + normal[1]], [base[0] - normal[0], base[1] - normal[1]], tip];
};
const turnStem = (side) => {
const cutMidpoint = 0.73;
const cutRise = side * 0.084;
return [
[-shaftHalf, 0], [shaftHalf, 0],
[shaftHalf, cutMidpoint + cutRise], [-shaftHalf, cutMidpoint - cutRise],
[-shaftHalf, 0],
];
};
if (assetId === "through") return [throughHead()];
if (assetId === "right") return [turnStem(1), diagonalShaft(1), diagonalHead(1)];
if (assetId === "left") return [turnStem(-1), diagonalShaft(-1), diagonalHead(-1)];
if (assetId === "through;right") return [throughHead(), diagonalShaft(1), diagonalHead(1)];
if (assetId === "through;left") return [throughHead(), diagonalShaft(-1), diagonalHead(-1)];
if (assetId === "through;left;right") return [throughHead(), diagonalShaft(-1), diagonalHead(-1), diagonalShaft(1), diagonalHead(1)];
throw new Error(`No angular turn-lane template: ${assetId}`);
}
function sourceSvgTemplateFor(asset, assetId) {
const source = fs.readFileSync(path.resolve(__dirname, "..", "..", "assets", "lane-icons", asset.source), "utf8");
const mirrorX = asset.mirror_x === true;
const anchorX = Number(asset.anchor_x);
if (!Number.isFinite(anchorX)) throw new Error(`turn-lane asset has invalid anchor_x: ${assetId}`);
const shapes = [];
for (const match of source.matchAll(/<line\b([^>]*)\/>|<path\b([^>]*)\/>/g)) {
const attrs = parseSvgAttrs(match[1] || match[2]);
const strokeWidth = Number(attrs["stroke-width"] || 0);
if (match[1]) {
shapes.push(strokePolygon([[Number(attrs.x1), Number(attrs.y1)], [Number(attrs.x2), Number(attrs.y2)]], strokeWidth));
} else {
const points = parseSvgPath(attrs.d || "");
if (attrs.fill !== "none") shapes.push(points);
if (strokeWidth > 0) shapes.push(strokePolygon(points, strokeWidth));
}
}
return shapes.filter((ring) => ring.length >= 4).map((ring) => ring.map(([x, y]) => [
(mirrorX ? anchorX - x : x - anchorX) * SVG_METERS_PER_UNIT,
(23 - y) * SVG_METERS_PER_UNIT,
]));
}
function parseSvgAttrs(text) {
const attrs = {};
for (const match of text.matchAll(/([\w:-]+)=(['"])(.*?)\2/g)) attrs[match[1]] = match[3];
return attrs;
}
function parseSvgPath(value) {
const tokens = value.match(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g) || [];
let index = 0;
let command = "";
let point = [0, 0];
let start = null;
const points = [];
const number = () => Number(tokens[index++]);
const lineTo = (x, y) => { point = [x, y]; points.push(point); };
while (index < tokens.length) {
if (/^[a-zA-Z]$/.test(tokens[index])) command = tokens[index++];
const relative = command === command.toLowerCase();
const op = command.toUpperCase();
if (op === "Z") { if (start) points.push(start); command = ""; continue; }
if (op === "M" || op === "L") {
const x = number(); const y = number();
const next = relative ? [point[0] + x, point[1] + y] : [x, y];
if (op === "M" && !start) { start = next; point = next; points.push(point); command = relative ? "l" : "L"; } else lineTo(...next);
continue;
}
if (op === "H") { lineTo(relative ? point[0] + number() : number(), point[1]); continue; }
if (op === "V") { lineTo(point[0], relative ? point[1] + number() : number()); continue; }
if (op === "C") {
const values = [number(), number(), number(), number(), number(), number()];
const controls = relative ? values.map((n, i) => n + point[i % 2]) : values;
const origin = point;
for (let step = 1; step <= 8; step += 1) {
const t = step / 8; const u = 1 - t;
lineTo(u ** 3 * origin[0] + 3 * u ** 2 * t * controls[0] + 3 * u * t ** 2 * controls[2] + t ** 3 * controls[4], u ** 3 * origin[1] + 3 * u ** 2 * t * controls[1] + 3 * u * t ** 2 * controls[3] + t ** 3 * controls[5]);
}
continue;
}
if (op === "A") { number(); number(); number(); number(); number(); const x = number(); const y = number(); lineTo(relative ? point[0] + x : x, relative ? point[1] + y : y); continue; }
throw new Error(`Unsupported SVG path command: ${command}`);
}
return points;
}
function strokePolygon(points, width) {
if (points.length < 2) return [];
const half = width / 2;
const left = []; const right = [];
for (let index = 0; index < points.length; index += 1) {
const prev = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
const dx = next[0] - prev[0]; const dy = next[1] - prev[1]; const length = Math.hypot(dx, dy) || 1;
const nx = -dy / length * half; const ny = dx / length * half;
left.push([points[index][0] + nx, points[index][1] + ny]);
right.unshift([points[index][0] - nx, points[index][1] - ny]);
}
return [...left, ...right, left[0]];
}
module.exports = { arrowRingsAt, buildCustomTurnLaneArrows, loadManifest, normalizeManeuver, supportedAssets, templateFor };
-161
View File
@@ -1,161 +0,0 @@
"use strict";
const EARTH_RADIUS_METERS = 6371008.8;
function laneCenterline(lane) {
const ring = lane?.geometry?.type === "Polygon" ? lane.geometry.coordinates?.[0] : null;
if (!Array.isArray(ring) || ring.length < 5 || !sameCoordinate(ring[0], ring.at(-1))) return null;
const vertices = ring.slice(0, -1);
if (!vertices.every(validCoordinate)) return null;
const half = vertices.length / 2;
if (!Number.isInteger(half) || half < 2) return null;
const centerline = vertices.slice(0, half).map((point, index) => [
(point[0] + vertices[vertices.length - 1 - index][0]) / 2,
(point[1] + vertices[vertices.length - 1 - index][1]) / 2,
]);
return polylineLength(centerline) > 0.01 ? centerline : null;
}
function orientPolyline(polyline, reference) {
if (!polyline?.length || !reference?.length) return null;
const forward = projectedDistanceAlong(reference, polyline.at(-1)) - projectedDistanceAlong(reference, polyline[0]);
if (Math.abs(forward) < 0.01) return null;
return forward > 0 ? polyline.map(copyCoordinate) : [...polyline].reverse().map(copyCoordinate);
}
function stitchPolylines(polylines, maxGapMeters) {
if (!polylines.length) return null;
const result = [];
for (const polyline of polylines) {
if (!polyline?.length) return null;
if (result.length && haversineMeters(result.at(-1), polyline[0]) > maxGapMeters) return null;
appendCoordinates(result, polyline);
}
return result;
}
function projectedDistanceAlong(polyline, point) {
let traversed = 0;
let best = { distance: Infinity, along: 0, lateral: 0 };
for (let index = 1; index < polyline.length; index += 1) {
const start = polyline[index - 1];
const end = polyline[index];
const meters = metersAt((start[1] + end[1]) / 2);
const dx = (end[0] - start[0]) * meters.lon;
const dy = (end[1] - start[1]) * meters.lat;
const px = (point[0] - start[0]) * meters.lon;
const py = (point[1] - start[1]) * meters.lat;
const length = Math.hypot(dx, dy);
if (length < 0.001) continue;
const ratio = Math.max(0, Math.min(1, (px * dx + py * dy) / (length * length)));
const offsetX = px - dx * ratio;
const offsetY = py - dy * ratio;
const distance = Math.hypot(offsetX, offsetY);
if (distance < best.distance) {
const rightX = dy / length;
const rightY = -dx / length;
best = {
distance,
along: traversed + length * ratio,
lateral: offsetX * rightX + offsetY * rightY,
};
}
traversed += length;
}
return best.along;
}
function lateralOffsetFrom(polyline, point) {
let best = null;
for (let index = 1; index < polyline.length; index += 1) {
const start = polyline[index - 1];
const end = polyline[index];
const meters = metersAt((start[1] + end[1]) / 2);
const dx = (end[0] - start[0]) * meters.lon;
const dy = (end[1] - start[1]) * meters.lat;
const px = (point[0] - start[0]) * meters.lon;
const py = (point[1] - start[1]) * meters.lat;
const length = Math.hypot(dx, dy);
if (length < 0.001) continue;
const ratio = Math.max(0, Math.min(1, (px * dx + py * dy) / (length * length)));
const offsetX = px - dx * ratio;
const offsetY = py - dy * ratio;
const distance = Math.hypot(offsetX, offsetY);
if (!best || distance < best.distance) {
best = { distance, lateral: offsetX * dy / length - offsetY * dx / length };
}
}
return best;
}
function polylineMidpoint(polyline) {
const target = polylineLength(polyline) / 2;
let traversed = 0;
for (let index = 1; index < polyline.length; index += 1) {
const length = haversineMeters(polyline[index - 1], polyline[index]);
if (traversed + length >= target) {
const ratio = length ? (target - traversed) / length : 0;
return [
polyline[index - 1][0] + (polyline[index][0] - polyline[index - 1][0]) * ratio,
polyline[index - 1][1] + (polyline[index][1] - polyline[index - 1][1]) * ratio,
];
}
traversed += length;
}
return polyline.length ? copyCoordinate(polyline.at(-1)) : null;
}
function polylineLength(polyline) {
let total = 0;
for (let index = 1; index < (polyline?.length || 0); index += 1) {
total += haversineMeters(polyline[index - 1], polyline[index]);
}
return total;
}
function haversineMeters(a, b) {
const lat1 = degreesToRadians(a[1]);
const lat2 = degreesToRadians(b[1]);
const dLat = degreesToRadians(b[1] - a[1]);
const dLon = degreesToRadians(b[0] - a[0]);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
return 2 * EARTH_RADIUS_METERS * Math.asin(Math.min(1, Math.sqrt(h)));
}
function appendCoordinates(target, coordinates) {
for (const coordinate of coordinates) {
if (!sameCoordinate(target.at(-1), coordinate)) target.push(copyCoordinate(coordinate));
}
}
function validCoordinate(value) {
return Array.isArray(value) && value.length >= 2 && Number.isFinite(value[0]) && Number.isFinite(value[1]);
}
function sameCoordinate(a, b) {
return Boolean(a && b && a[0] === b[0] && a[1] === b[1]);
}
function copyCoordinate(coordinate) {
return [coordinate[0], coordinate[1]];
}
function metersAt(latitude) {
return { lon: 111320 * Math.cos(degreesToRadians(latitude)), lat: 111320 };
}
function degreesToRadians(value) {
return value * Math.PI / 180;
}
module.exports = {
appendCoordinates,
haversineMeters,
laneCenterline,
lateralOffsetFrom,
orientPolyline,
polylineLength,
polylineMidpoint,
projectedDistanceAlong,
stitchPolylines,
};
-14
View File
@@ -1,14 +0,0 @@
"use strict";
module.exports = {
laneGeometry: require("./geometry/lane-geometry"),
gaodeReference: require("./reference/gaode"),
turnLaneArrows: require("./compile/turn-lane-arrows"),
complexJunction: require("./compile/complex-junction"),
osm: require("./osm"),
trafficSignals: require("./traffic-signals"),
nativeTrafficSignals: require("./native-traffic-signals"),
nativeRoad: require("./compile/native-road"),
compiler: require("./compile/compiler"),
check: require("./check"),
};
-49
View File
@@ -1,49 +0,0 @@
"use strict";
const fs = require("fs");
const { parseOsm } = require("./osm");
const {
buildTrafficSignalFeatures,
buildTrafficSignalsFromFeatures,
validateTrafficSignalFeatures,
validateTrafficSignalSourceReferences,
} = require("./traffic-signals");
const SCHEMA = "native-traffic-signals/v1";
function loadOrGenerate(file, osmText, stopLines, intersections) {
if (fs.existsSync(file)) {
const document = JSON.parse(fs.readFileSync(file, "utf8"));
try {
return validateDocument(document, osmText);
} catch (error) {
// OSM edits can invalidate the stable identities in a document that was
// itself generated from OSM. User-authored documents must remain strict.
if (document?.provenance === "generated:osm-controls" && isStaleSourceReferenceError(error)) {
return generate(osmText, stopLines, intersections);
}
throw error;
}
}
return generate(osmText, stopLines, intersections);
}
function isStaleSourceReferenceError(error) {
return error instanceof Error && /^traffic signal feature \d+: (approach_id .* is not present on OSM control|control_id .* is not present in the current OSM)/.test(error.message);
}
function generate(osmText, stopLines, intersections) {
const controls = parseOsm(osmText).trafficSignalControls;
return { schema: SCHEMA, provenance: "generated:osm-controls", assemblies: buildTrafficSignalFeatures(stopLines, intersections, controls) };
}
function validateDocument(value, osmText) {
if (value?.schema !== SCHEMA) throw new Error(`Expected ${SCHEMA} signal document`);
const assemblies = validateTrafficSignalFeatures(value.assemblies);
if (osmText) validateTrafficSignalSourceReferences(assemblies, parseOsm(osmText).trafficSignalControls);
return { schema: SCHEMA, provenance: value.provenance || "native", assemblies };
}
function runtime(document) { return buildTrafficSignalsFromFeatures(document.assemblies); }
module.exports = { SCHEMA, generate, loadOrGenerate, validateDocument, runtime };
-102
View File
@@ -1,102 +0,0 @@
"use strict";
function parseOsm(xml) {
const boundsMatch = xml.match(/<bounds\b([^>]*)\/?\s*>/);
const boundsAttrs = boundsMatch ? xmlAttrs(boundsMatch[1]) : {};
const candidateBounds = {
minLon: Number(boundsAttrs.minlon), minLat: Number(boundsAttrs.minlat),
maxLon: Number(boundsAttrs.maxlon), maxLat: Number(boundsAttrs.maxlat),
};
const bounds = Object.values(candidateBounds).every(Number.isFinite) ? candidateBounds : null;
const nodes = new Map();
const trafficSignalControls = [];
const nodePattern = /<node\b([^>]*?)(?:\/>|>([\s\S]*?)<\/node>)/g;
for (const match of xml.matchAll(nodePattern)) {
const attrs = xmlAttrs(match[1]);
if (attrs.action === "delete" || !attrs.id || attrs.lon === undefined || attrs.lat === undefined) continue;
const coordinate = [Number(attrs.lon), Number(attrs.lat)];
if (!coordinate.every(Number.isFinite)) continue;
nodes.set(attrs.id, coordinate);
const tags = parseTags(match[2] || "");
if (tags.highway === "traffic_signals") {
trafficSignalControls.push({ id: attrs.id, longitude: coordinate[0], latitude: coordinate[1], tags });
}
}
const ways = [];
for (const match of xml.matchAll(/<way\b([^>]*)>([\s\S]*?)<\/way>/g)) {
const attrs = xmlAttrs(match[1]);
if (attrs.action === "delete") continue;
const body = match[2];
const refs = [];
for (const ndMatch of body.matchAll(/<nd\b([^>]*)\/?\s*>/g)) {
const ref = xmlAttrs(ndMatch[1]).ref;
if (ref && nodes.has(ref)) refs.push(ref);
}
if (refs.length >= 2) ways.push({ id: attrs.id || `way-${ways.length + 1}`, refs, tags: parseTags(body) });
}
for (const control of trafficSignalControls) {
const arms = [];
for (const way of ways) {
if (!isMotorRoad(way.tags)) continue;
for (let index = 0; index < way.refs.length; index += 1) {
if (way.refs[index] !== control.id) continue;
for (const neighborIndex of [index - 1, index + 1]) {
const neighbor = way.refs[neighborIndex];
if (!neighbor || !nodes.has(neighbor)) continue;
const neighborPoint = nodes.get(neighbor);
arms.push({
headingDegrees: headingBetween(control, neighborPoint),
wayId: String(way.id),
neighborNodeId: String(neighbor),
});
}
}
}
control.arms = dedupeHeadings(arms);
control.junctionType = control.arms.length === 3 ? "T" : control.arms.length === 4 ? "cross" : "other";
}
return { bounds, nodes, ways, trafficSignalControls };
}
function isMotorRoad(tags) {
const highway = tags.highway || "";
return highway && tags.area !== "yes" && !new Set([
"footway", "path", "pedestrian", "steps", "cycleway", "service", "track",
"bridleway", "corridor", "elevator", "platform", "construction",
]).has(highway);
}
function headingBetween(from, to) {
const latitude = (from.latitude + to[1]) / 2 * Math.PI / 180;
return Math.atan2((to[0] - from.longitude) * Math.cos(latitude), to[1] - from.latitude) * 180 / Math.PI;
}
function dedupeHeadings(arms) {
const normalized = (value) => ((value % 360) + 360) % 360;
const distance = (a, b) => Math.abs(((a - b + 540) % 360) - 180);
const result = [];
for (const arm of arms) {
arm.headingDegrees = normalized(arm.headingDegrees);
if (!result.some((other) => distance(other.headingDegrees, arm.headingDegrees) <= 25)) result.push(arm);
}
return result.sort((a, b) => a.headingDegrees - b.headingDegrees);
}
function xmlAttrs(text) {
const attrs = {};
for (const match of text.matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
attrs[match[1]] = match[2] !== undefined ? match[2] : match[3];
}
return attrs;
}
function parseTags(body) {
const tags = {};
for (const match of body.matchAll(/<tag\b([^>]*)\/?\s*>/g)) {
const tag = xmlAttrs(match[1]);
if (tag.k) tags[tag.k] = tag.v || "";
}
return tags;
}
module.exports = { parseOsm };
-231
View File
@@ -1,231 +0,0 @@
"use strict";
const fs = require("fs");
const PI = Math.PI;
const EARTH_A = 6378245.0;
const EARTH_EE = 0.00669342162296594323;
function transformLat(x, y) {
let value = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3;
value += (20 * Math.sin(y * PI) + 40 * Math.sin(y / 3 * PI)) * 2 / 3;
value += (160 * Math.sin(y / 12 * PI) + 320 * Math.sin(y * PI / 30)) * 2 / 3;
return value;
}
function transformLon(x, y) {
let value = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3;
value += (20 * Math.sin(x * PI) + 40 * Math.sin(x / 3 * PI)) * 2 / 3;
value += (150 * Math.sin(x / 12 * PI) + 300 * Math.sin(x / 30 * PI)) * 2 / 3;
return value;
}
// This is the standard local inverse approximation used for GCJ-02 reference
// data. It is intentionally kept separate from native road geometry, whose
// source coordinates remain WGS84.
function gcj02ToWgs84(coordinate) {
const [longitude, latitude] = coordinate;
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) throw new Error("Reference coordinate must be finite");
const dLat = transformLat(longitude - 105, latitude - 35);
const dLon = transformLon(longitude - 105, latitude - 35);
const radLat = latitude / 180 * PI;
const magic = 1 - EARTH_EE * Math.sin(radLat) ** 2;
const sqrtMagic = Math.sqrt(magic);
return [
longitude - dLon * 180 / (EARTH_A / sqrtMagic * Math.cos(radLat) * PI),
latitude - dLat * 180 / (EARTH_A * (1 - EARTH_EE) / (magic * sqrtMagic) * PI),
];
}
function mapCoordinates(coordinates, mapper) {
if (typeof coordinates[0] === "number") return mapper(coordinates);
return coordinates.map((value) => mapCoordinates(value, mapper));
}
function convertGeoJson(document) {
if (!document || document.type !== "FeatureCollection" || !Array.isArray(document.features)) {
throw new Error("Reference must be a GeoJSON FeatureCollection");
}
return {
...document,
crs: undefined,
features: document.features.map((feature) => {
if (!feature || !feature.geometry || !feature.geometry.coordinates) throw new Error("Reference feature is missing geometry");
return { ...feature, geometry: { ...feature.geometry, coordinates: mapCoordinates(feature.geometry.coordinates, gcj02ToWgs84) } };
}),
};
}
function coordinatesOf(document) {
const points = [];
for (const feature of document.features || []) walkCoordinates(feature.geometry?.coordinates, points);
return points;
}
function walkCoordinates(value, points) {
if (!Array.isArray(value) || !value.length) return;
if (typeof value[0] === "number") {
points.push(value);
return;
}
for (const child of value) walkCoordinates(child, points);
}
function boundsOf(document) {
const points = coordinatesOf(document);
if (!points.length) throw new Error("Reference contains no coordinates");
return {
minLon: Math.min(...points.map((point) => point[0])),
minLat: Math.min(...points.map((point) => point[1])),
maxLon: Math.max(...points.map((point) => point[0])),
maxLat: Math.max(...points.map((point) => point[1])),
};
}
function centerOf(bounds) {
return [(bounds.minLon + bounds.maxLon) / 2, (bounds.minLat + bounds.maxLat) / 2];
}
function distanceMeters(first, second) {
const lonScale = 111320 * Math.cos(first[1] * PI / 180);
return Math.hypot((second[0] - first[0]) * lonScale, (second[1] - first[1]) * 111320);
}
function parseOsmNodes(xml) {
const nodes = [];
for (const match of xml.matchAll(/<node\b([^>]*?)(?:\/>|>([\s\S]*?)<\/node>)/g)) {
const attrs = {};
for (const item of match[1].matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[item[1]] = item[2] ?? item[3];
if (!attrs.id || !Number.isFinite(Number(attrs.lon)) || !Number.isFinite(Number(attrs.lat))) continue;
const tags = {};
for (const item of (match[2] || "").matchAll(/<tag\b([^>]*)\/?\s*>/g)) {
const tag = {};
for (const attr of item[1].matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) tag[attr[1]] = attr[2] ?? attr[3];
if (tag.k) tags[tag.k] = tag.v || "";
}
nodes.push({ id: String(attrs.id), coordinate: [Number(attrs.lon), Number(attrs.lat)], tags });
}
return nodes;
}
function nearestNode(nodes, coordinate, nodeId) {
if (nodeId) {
const exact = nodes.find((node) => node.id === String(nodeId));
if (!exact) throw new Error(`OSM node not found: ${nodeId}`);
return { ...exact, distanceMeters: distanceMeters(exact.coordinate, coordinate), match: "node-id" };
}
const candidates = nodes.map((node) => ({ ...node, distanceMeters: distanceMeters(node.coordinate, coordinate) }));
candidates.sort((first, second) => first.distanceMeters - second.distanceMeters);
if (!candidates[0]) throw new Error("OSM contains no usable nodes");
return { ...candidates[0], match: "nearest-node" };
}
function bboxIntersectionRatio(first, second) {
const width = Math.max(0, Math.min(first.maxLon, second.maxLon) - Math.max(first.minLon, second.minLon));
const height = Math.max(0, Math.min(first.maxLat, second.maxLat) - Math.max(first.minLat, second.minLat));
const intersection = width * height;
const firstArea = Math.max(0, first.maxLon - first.minLon) * Math.max(0, first.maxLat - first.minLat);
const secondArea = Math.max(0, second.maxLon - second.minLon) * Math.max(0, second.maxLat - second.minLat);
return intersection / Math.max(firstArea + secondArea - intersection, Number.EPSILON);
}
// A complex junction is compiled as one cluster of `complex_part` polygons in
// road_surface.geojson, not as a per-node feature in intersection_surface.
// Match it by cluster id, or by whichever cluster core sits nearest the node.
function complexClusterSurface(nativeRoadSurfaceFile, node, clusterId) {
if (!nativeRoadSurfaceFile || !fs.existsSync(nativeRoadSurfaceFile)) return null;
const surface = JSON.parse(fs.readFileSync(nativeRoadSurfaceFile, "utf8"));
const parts = (surface.features || []).filter((item) => item.properties?.cluster_id && item.properties?.complex_part);
const cores = parts.filter((item) => item.properties.complex_part === "core" && Array.isArray(item.properties.center));
if (!cores.length) return null;
const core = clusterId
? cores.find((item) => String(item.properties.cluster_id) === String(clusterId))
: [...cores].sort((first, second) => distanceMeters(first.properties.center, node.coordinate) - distanceMeters(second.properties.center, node.coordinate))[0];
if (!core) return null;
const features = parts.filter((item) => item.properties.cluster_id === core.properties.cluster_id);
return { clusterId: core.properties.cluster_id, core, features };
}
function inspectReference({ referenceFile, osmFile, nativeIntersectionFile, nativeRoadSurfaceFile, nodeId, clusterId }) {
const source = JSON.parse(fs.readFileSync(referenceFile, "utf8"));
const converted = convertGeoJson(source);
const referenceBounds = boundsOf(converted);
const referenceCenter = centerOf(referenceBounds);
const nodes = parseOsmNodes(fs.readFileSync(osmFile, "utf8"));
const matchedNode = nearestNode(nodes, referenceCenter, nodeId);
const native = JSON.parse(fs.readFileSync(nativeIntersectionFile, "utf8"));
const feature = (native.features || []).find((item) => item.properties?.osm_node_id === matchedNode.id);
const cluster = feature ? null : complexClusterSurface(nativeRoadSurfaceFile, matchedNode, clusterId);
const matchedFeatures = feature ? [feature] : cluster?.features || null;
const nativeBounds = matchedFeatures ? boundsOf({ features: matchedFeatures }) : null;
const diagnostics = [];
if (!matchedFeatures) diagnostics.push(nativeRoadSurfaceFile ? "No native intersection surface or complex cluster matched the OSM node" : "No native intersection surface matched the OSM node; pass --native-road-surface to also search complex junction clusters");
return {
schema: "gaode-junction-reference-comparison/v2",
source: { file: referenceFile, coordinateSystem: "GCJ-02", featureCount: converted.features.length },
conversion: { target: "WGS84", method: "gcj02-inverse-approximation" },
reference: { bounds: referenceBounds, center: referenceCenter },
matchedOsmNode: { id: matchedNode.id, coordinate: matchedNode.coordinate, tags: matchedNode.tags, match: matchedNode.match, centerDistanceMeters: matchedNode.distanceMeters },
nativeIntersection: nativeBounds ? {
kind: feature ? "junction-node" : "complex-cluster",
clusterId: cluster?.clusterId || null,
featureCount: matchedFeatures.length,
bounds: nativeBounds,
bboxIoU: bboxIntersectionRatio(referenceBounds, nativeBounds),
centerOffsetMeters: distanceMeters(referenceCenter, centerOf(nativeBounds)),
featureProperties: feature ? feature.properties : cluster.core.properties,
} : null,
diagnostics,
converted,
matchedFeatures,
};
}
function localReferenceSvg({ converted, nativeIntersection, center, radiusMeters = 180 }) {
const width = 1000;
const height = 1000;
const lonScale = 111320 * Math.cos(center[1] * PI / 180);
const project = (point) => [
width / 2 + (point[0] - center[0]) * lonScale * width / (radiusMeters * 2),
height / 2 - (point[1] - center[1]) * 111320 * height / (radiusMeters * 2),
];
const pathFor = (coordinates) => {
const parts = [];
const appendLine = (line, close) => {
if (!line?.length) return;
const [firstX, firstY] = project(line[0]);
parts.push(`M ${firstX.toFixed(1)} ${firstY.toFixed(1)}`);
for (const point of line.slice(1)) {
const [x, y] = project(point);
parts.push(`L ${x.toFixed(1)} ${y.toFixed(1)}`);
}
if (close) parts.push("Z");
};
const visit = (value) => {
if (!Array.isArray(value) || !value.length) return;
if (typeof value[0] === "number") return;
if (typeof value[0][0] === "number") appendLine(value, value.length > 2);
else value.forEach(visit);
};
visit(coordinates);
return parts.join(" ");
};
const color = { 1: "#2563eb", 2: "#0f766e", 3: "#7c3aed", 4: "#ea580c", 5: "#64748b" };
const references = converted.features.map((feature) => {
const type = feature.properties?.type || "unknown";
return `<path d="${pathFor(feature.geometry.coordinates)}" fill="${feature.geometry.type.includes("Polygon") ? `${color[type] || "#334155"}18` : "none"}" stroke="${color[type] || "#334155"}" stroke-width="1.2"/>`;
}).join("\n");
const nativePaths = (nativeIntersection?.features || []).map((feature) => `<path d="${pathFor(feature.geometry.coordinates)}" fill="#dc262655" stroke="#dc2626" stroke-width="3"/>`).join("\n");
return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
<rect width="100%" height="100%" fill="#f8fafc"/>
${references}
${nativePaths}
<circle cx="${width / 2}" cy="${height / 2}" r="5" fill="#111827"/>
<text x="20" y="35" font-family="sans-serif" font-size="22" fill="#111827">Gaode reference (type colors) / native intersection (red)</text>
</svg>`;
}
module.exports = { gcj02ToWgs84, convertGeoJson, boundsOf, parseOsmNodes, nearestNode, inspectReference, localReferenceSvg };
-330
View File
@@ -1,330 +0,0 @@
"use strict";
const fs = require("fs");
const crypto = require("crypto");
const { parseOsm } = require("./osm");
const EARTH_RADIUS = 6371008.8;
const CURB_OFFSET_METERS = 5.2;
const MAST_REACH_METERS = 4.5;
const SIGNAL_LAYOUT = Object.freeze({
poleHeightMeters: 6.7, poleRadiusMeters: 0.13, armWidthMeters: 0.21,
mastHeightMeters: 6.25, headCenterHeightMeters: 6.25,
headWidthMeters: 0.68, headDepthMeters: 0.30, headBodyHeightMeters: 1.62,
lensRadiusMeters: 0.22, lensDepthMeters: 0.07, lensFaceOffsetMeters: 0.18,
lensVerticalOffsetsMeters: [0.49, -0.01, -0.51],
countdownLateralMeters: 1.15, countdownFaceOffsetMeters: 0.05,
countdownWidthMeters: 0.82, countdownDepthMeters: 0.14,
countdownHeightMeters: 0.56, countdownVerticalOffsetMeters: 0.0,
});
function buildTrafficSignalFeatures(stopLines, intersections, controls = []) {
const centers = (intersections.features || []).map((feature, index) => {
const point = polygonCenter(feature.geometry);
return { id: `intersection-${index + 1}`, point, radius: polygonRadius(feature.geometry, point) };
}).filter((entry) => entry.point);
const clusteredStops = new Map();
for (const feature of stopLines.features || []) {
const clusterId = feature.properties?.cluster_id;
const point = polygonCenter(feature.geometry);
if (!clusterId || !point) continue;
if (!clusteredStops.has(clusterId)) clusteredStops.set(clusterId, []);
clusteredStops.get(clusterId).push(point);
}
for (const [clusterId, points] of clusteredStops) {
if (points.length < 3) continue;
const point = points.reduce((sum, item) => [sum[0] + item[0] / points.length, sum[1] + item[1] / points.length], [0, 0]);
centers.push({ id: `cluster-${clusterId}`, clusterId, point, radius: Math.max(...points.map((item) => metersBetween(point, item))) });
}
const candidates = [];
for (const feature of stopLines.features || []) {
const center = polygonCenter(feature.geometry);
if (!center) continue;
const clusterId = feature.properties?.cluster_id;
const intersection = clusterId ? centers.find((entry) => entry.clusterId === clusterId) : nearestCenter(center, centers);
if (!intersection || metersBetween(center, intersection.point) > 32) continue;
const axis = roadAxis(feature.geometry, center, intersection.point);
if (!axis) continue;
const right = [axis[1], -axis[0]];
candidates.push({
intersectionId: intersection.id, center, axis,
point: intersection.clusterId
? moveMeters(center, right, CURB_OFFSET_METERS)
: moveMeters(moveMeters(intersection.point, axis, intersection.radius + 3.2), right, CURB_OFFSET_METERS),
headingDegrees: normalizeDegrees(Math.atan2(axis[0], axis[1]) * 180 / Math.PI),
matchHeadingDegrees: intersection.clusterId
? normalizeDegrees(Math.atan2(-axis[0], -axis[1]) * 180 / Math.PI)
: null,
});
}
const features = [];
for (const control of controls) {
const controlPoint = [Number(control.longitude), Number(control.latitude)];
if (!controlPoint.every(Number.isFinite) || !Array.isArray(control.arms) || control.arms.length < 3) continue;
const intersection = nearestCenter(controlPoint, centers);
if (!intersection || metersBetween(controlPoint, intersection.point) > 32) continue;
const arms = matchOsmArms(candidates.filter((item) => item.intersectionId === intersection.id), controlPoint, control.arms);
const groups = phaseGroups(arms);
arms.forEach((candidate, index) => {
const fallbackArmId = `heading-${Math.round(normalizeDegrees(candidate.osmArm?.headingDegrees || 0) * 1000)}`;
const sourceWayId = String(candidate.osmArm?.wayId || "legacy");
const neighborNodeId = String(candidate.osmArm?.neighborNodeId || fallbackArmId);
const approachId = `${sourceWayId}:${neighborNodeId}`;
const signalUid = `osm-${String(control.id)}-${sourceWayId}-${neighborNodeId}`;
features.push({
type: "Feature",
geometry: { type: "Point", coordinates: candidate.point.slice() },
properties: {
signal_uid: signalUid, display_id: signalUid, control_id: String(control.id),
approach_id: approachId, source_way_id: sourceWayId,
// These are independent assembly controls. heading_deg remains a
// migration hint for older native documents only.
mast_heading_deg: normalizeDegrees(candidate.headingDegrees - 90),
face_heading_deg: normalizeDegrees(candidate.headingDegrees + 180),
phase_group: groups[index],
mast_reach_m: MAST_REACH_METERS,
stop_lon: candidate.center[0], stop_lat: candidate.center[1],
enabled: true, z_offset_m: 0,
},
});
});
}
return validateTrafficSignalFeatures({ type: "FeatureCollection", features });
}
function validateTrafficSignalFeatures(collection) {
if (collection?.type !== "FeatureCollection" || !Array.isArray(collection.features)) {
throw new Error("Traffic signal assemblies must be a FeatureCollection");
}
const uids = new Set();
const displayIds = new Set();
const features = collection.features.map((feature, index) => {
const label = `traffic signal feature ${index + 1}`;
if (feature?.geometry?.type !== "Point" || !Array.isArray(feature.geometry.coordinates) ||
feature.geometry.coordinates.length < 2 || !feature.geometry.coordinates.slice(0, 2).every(Number.isFinite)) {
throw new Error(`${label}: geometry must be a finite Point`);
}
const input = feature.properties || {};
const text = (key, required = true) => {
const value = input[key] == null ? "" : String(input[key]).trim();
if (required && !value) throw new Error(`${label}: missing ${key}`);
return value;
};
const number = (key, options = {}) => {
if (input[key] === null || input[key] === undefined || input[key] === "") {
throw new Error(`${label}: missing ${key}`);
}
const value = Number(input[key]);
if (!Number.isFinite(value) || (options.min != null && value < options.min) || (options.max != null && value > options.max)) {
throw new Error(`${label}: invalid ${key} '${input[key]}'`);
}
return value;
};
const signalUid = text("signal_uid");
if (!/^osm-[A-Za-z0-9_.:-]+$/.test(signalUid)) throw new Error(`${label}: invalid signal_uid '${signalUid}'`);
if (uids.has(signalUid)) throw new Error(`Duplicate signal_uid '${signalUid}'`);
uids.add(signalUid);
const displayId = text("display_id", false);
if (displayId && displayIds.has(displayId)) throw new Error(`Duplicate display_id '${displayId}'`);
if (displayId) displayIds.add(displayId);
const phaseGroup = number("phase_group", { min: 0, max: 1 });
if (!Number.isInteger(phaseGroup)) throw new Error(`${label}: phase_group must be 0 or 1`);
const enabled = normalizeBoolean(input.enabled, label);
const controlId = text("control_id");
const approachId = text("approach_id");
const sourceWayId = text("source_way_id");
if (!approachId.startsWith(`${sourceWayId}:`)) throw new Error(`${label}: approach_id does not match source_way_id`);
const expectedUid = `osm-${controlId}-${approachId.replace(":", "-")}`;
if (signalUid !== expectedUid) throw new Error(`${label}: signal_uid does not match source identity (expected '${expectedUid}')`);
const legacyHeading = input.heading_deg == null || input.heading_deg === "" ? null : normalizeDegrees(number("heading_deg"));
if (legacyHeading == null && (input.mast_heading_deg == null || input.mast_heading_deg === "")) {
throw new Error(`${label}: missing mast_heading_deg`);
}
if (legacyHeading == null && (input.face_heading_deg == null || input.face_heading_deg === "")) {
throw new Error(`${label}: missing face_heading_deg`);
}
const mastHeading = input.mast_heading_deg == null || input.mast_heading_deg === ""
? normalizeDegrees((legacyHeading == null ? 0 : legacyHeading) - 90)
: normalizeDegrees(number("mast_heading_deg"));
const faceHeading = input.face_heading_deg == null || input.face_heading_deg === ""
? normalizeDegrees((legacyHeading == null ? 0 : legacyHeading) + 180)
: normalizeDegrees(number("face_heading_deg"));
return {
type: "Feature",
geometry: { type: "Point", coordinates: feature.geometry.coordinates.slice(0, 2).map(Number) },
properties: {
...input, signal_uid: signalUid, display_id: displayId,
control_id: controlId, approach_id: approachId,
source_way_id: sourceWayId,
// Retain the legacy value only for migration compatibility. Runtime
// geometry is entirely defined by mast_heading_deg and face_heading_deg.
heading_deg: legacyHeading,
mast_heading_deg: mastHeading, face_heading_deg: faceHeading,
phase_group: phaseGroup, mast_reach_m: number("mast_reach_m", { min: 0.1, max: 30 }),
stop_lon: number("stop_lon", { min: -180, max: 180 }),
stop_lat: number("stop_lat", { min: -90, max: 90 }),
enabled, z_offset_m: number("z_offset_m", { min: -20, max: 100 }),
},
};
});
return { type: "FeatureCollection", features };
}
function buildTrafficSignalsFromFeatures(collection) {
const normalized = validateTrafficSignalFeatures(collection);
const signals = normalized.features.filter((feature) => feature.properties.enabled).map((feature) => {
const p = feature.properties;
const point = feature.geometry.coordinates;
const mastAxis = headingVector(p.mast_heading_deg);
return {
id: p.signal_uid, signalUid: p.signal_uid, displayId: p.display_id,
nodeKey: signalNodeKey(p.signal_uid),
controlId: p.control_id, approachId: p.approach_id, sourceWayId: p.source_way_id,
phaseGroup: p.phase_group, longitude: point[0], latitude: point[1],
stopLongitude: p.stop_lon, stopLatitude: p.stop_lat,
// Existing Blender readers require headingDegrees. It is a compatibility
// alias only; the independent mast/face fields below define all geometry.
headingDegrees: p.heading_deg == null ? p.mast_heading_deg : p.heading_deg,
mastHeadingDegrees: p.mast_heading_deg,
faceHeadingDegrees: p.face_heading_deg, mastReachMeters: p.mast_reach_m,
zOffsetMeters: p.z_offset_m,
pose: buildSignalPose(point, mastAxis, p.face_heading_deg, p.mast_reach_m, p.z_offset_m),
};
});
return { version: 3, layout: SIGNAL_LAYOUT, signals };
}
function signalNodeKey(signalUid) {
return `ts_${crypto.createHash("sha256").update(signalUid).digest("hex").slice(0, 16)}`;
}
function reconcileTrafficSignalSourceReferences(collection, controls) {
const normalized = validateTrafficSignalFeatures(collection);
const approachesByControl = new Map((controls || []).map((control) => [
String(control.id),
new Set((control.arms || []).map((arm) => `${String(arm.wayId)}:${String(arm.neighborNodeId)}`)),
]));
const kept = [];
const dropped = [];
for (const [index, feature] of normalized.features.entries()) {
const { control_id: controlId, approach_id: approachId, signal_uid: signalUid } = feature.properties;
const approaches = approachesByControl.get(controlId);
if (!approaches) {
dropped.push({ index: index + 1, signalUid, controlId, approachId, reason: "missing-control", message: `control_id '${controlId}' is not present in the current OSM` });
continue;
}
if (!approaches.has(approachId)) {
dropped.push({ index: index + 1, signalUid, controlId, approachId, reason: "missing-approach", message: `approach_id '${approachId}' is not present on OSM control '${controlId}'` });
continue;
}
kept.push(feature);
}
return { collection: { ...normalized, features: kept }, dropped };
}
function validateTrafficSignalSourceReferences(collection, controls) {
const { collection: reconciled, dropped } = reconcileTrafficSignalSourceReferences(collection, controls);
if (dropped.length) throw new Error(`traffic signal feature ${dropped[0].index}: ${dropped[0].message}`);
return reconciled;
}
function buildTrafficSignals(stopLines, intersections, controls = []) {
return buildTrafficSignalsFromFeatures(buildTrafficSignalFeatures(stopLines, intersections, controls));
}
function readTrafficSignalFeatures(stopLinePath, intersectionPath, osmPath) {
const controls = parseOsm(fs.readFileSync(osmPath, "utf8")).trafficSignalControls;
return buildTrafficSignalFeatures(
JSON.parse(fs.readFileSync(stopLinePath, "utf8")),
JSON.parse(fs.readFileSync(intersectionPath, "utf8")), controls,
);
}
function readTrafficSignals(editablePath, osmPath = null) {
const collection = JSON.parse(fs.readFileSync(editablePath, "utf8"));
if (osmPath) {
const controls = parseOsm(fs.readFileSync(osmPath, "utf8")).trafficSignalControls;
validateTrafficSignalSourceReferences(collection, controls);
}
return buildTrafficSignalsFromFeatures(collection);
}
function normalizeBoolean(value, label) {
if (value === true || value === 1 || value === "1" || String(value).toLowerCase() === "true" || String(value).toLowerCase() === "yes") return true;
if (value === false || value === 0 || value === "0" || String(value).toLowerCase() === "false" || String(value).toLowerCase() === "no") return false;
throw new Error(`${label}: invalid enabled '${value}'`);
}
function uniqueApproachArms(candidates, controlPoint) {
const sorted = candidates.map((candidate) => ({ ...candidate, armHeading: normalizeDegrees(headingBetween(controlPoint, candidate.center)), controlDistance: metersBetween(controlPoint, candidate.center) }))
.sort((a, b) => a.armHeading - b.armHeading || a.controlDistance - b.controlDistance);
const arms = [];
for (const candidate of sorted) if (!arms.some((arm) => angularDistance(arm.armHeading, candidate.armHeading) <= 25)) arms.push(candidate);
return arms;
}
function matchOsmArms(candidates, controlPoint, osmArms) {
const remaining = candidates.map((candidate) => ({ ...candidate, armHeading: candidate.matchHeadingDegrees ?? normalizeDegrees(headingBetween(controlPoint, candidate.center)) }));
if (!osmArms.length) return uniqueApproachArms(remaining, controlPoint);
return osmArms.map((osmArm) => {
let bestIndex = -1; let bestDistance = Infinity;
remaining.forEach((item, index) => {
const directedDistance = angularDistance(item.armHeading, osmArm.headingDegrees);
const distance = item.matchHeadingDegrees == null
? directedDistance
: Math.min(
angularDistance(item.matchHeadingDegrees, osmArm.headingDegrees),
angularDistance(item.matchHeadingDegrees + 180, osmArm.headingDegrees),
);
if (distance < bestDistance) { bestDistance = distance; bestIndex = index; }
});
const candidate = bestIndex >= 0 && bestDistance <= 45 ? remaining.splice(bestIndex, 1)[0] : fallbackCandidate(controlPoint, osmArm);
return { ...candidate, osmArm };
});
}
function fallbackCandidate(controlPoint, osmArm) {
const outward = headingVector(osmArm.headingDegrees); const axis = [-outward[0], -outward[1]];
const center = moveMeters(controlPoint, outward, 8); const farSide = moveMeters(controlPoint, axis, 3.2);
return { center, axis, point: moveMeters(farSide, [axis[1], -axis[0]], CURB_OFFSET_METERS), armHeading: normalizeDegrees(osmArm.headingDegrees), headingDegrees: normalizeDegrees(Math.atan2(axis[0], axis[1]) * 180 / Math.PI), fallback: true };
}
function phaseGroups(arms) {
const groups = Array(arms.length).fill(1); if (arms.length < 2) return groups;
let main = [0, 1]; let best = -1;
for (let a = 0; a < arms.length; a += 1) for (let b = a + 1; b < arms.length; b += 1) { const opposition = angularDistance(arms[a].armHeading, arms[b].armHeading); if (opposition > best) { best = opposition; main = [a, b]; } }
groups[main[0]] = 0; groups[main[1]] = 0; return groups;
}
function buildSignalPose(pole, mastAxis, faceHeadingDegrees, mastReach, zOffset = 0) {
const face = headingVector(faceHeadingDegrees);
const head = moveMeters(pole, mastAxis, mastReach);
const position = (point, height) => ({ longitude: point[0], latitude: point[1], height: height + zOffset });
const lensPoint = moveMeters(head, face, SIGNAL_LAYOUT.lensFaceOffsetMeters);
const faceRight = [-face[1], face[0]];
const board = moveMeters(moveMeters(head, faceRight, SIGNAL_LAYOUT.countdownLateralMeters), face, SIGNAL_LAYOUT.countdownFaceOffsetMeters);
return { pole: position(pole, 0), arm: { from: position(pole, SIGNAL_LAYOUT.mastHeightMeters), to: position(head, SIGNAL_LAYOUT.mastHeightMeters) }, head: { ...position(head, SIGNAL_LAYOUT.headCenterHeightMeters), faceHeadingDegrees }, lenses: ["red", "yellow", "green"].map((state, index) => ({ state, ...position(lensPoint, SIGNAL_LAYOUT.headCenterHeightMeters + SIGNAL_LAYOUT.lensVerticalOffsetsMeters[index]) })), countdown: { ...position(board, SIGNAL_LAYOUT.mastHeightMeters), faceHeadingDegrees } };
}
function polygonCenter(geometry) { const ring = geometry?.type === "Polygon" ? geometry.coordinates?.[0] : null; if (!ring || ring.length < 4) return null; const points = ring.slice(0, -1); return [points.reduce((s, p) => s + p[0], 0) / points.length, points.reduce((s, p) => s + p[1], 0) / points.length]; }
function polygonRadius(geometry, center) { const ring = geometry?.type === "Polygon" ? geometry.coordinates?.[0] : null; return ring && center ? Math.max(...ring.slice(0, -1).map((point) => metersBetween(center, point)), 0) : 0; }
function roadAxis(geometry, center, target) { const ring = geometry?.coordinates?.[0]; if (!ring || ring.length < 3) return null; let longest; for (let i = 0; i < ring.length - 1; i += 1) { const dx = (ring[i + 1][0] - ring[i][0]) * Math.cos(center[1] * Math.PI / 180); const dy = ring[i + 1][1] - ring[i][1]; const length = Math.hypot(dx, dy); if (!longest || length > longest.length) longest = { dx, dy, length }; } if (!longest?.length) return null; let axis = [-longest.dy / longest.length, longest.dx / longest.length]; const toward = [(target[0] - center[0]) * Math.cos(center[1] * Math.PI / 180), target[1] - center[1]]; if (axis[0] * toward[0] + axis[1] * toward[1] < 0) axis = [-axis[0], -axis[1]]; return axis; }
function nearestCenter(point, centers) { return centers.map((entry) => ({ ...entry, distance: metersBetween(point, entry.point) })).sort((a, b) => a.distance - b.distance)[0] || null; }
function metersBetween(a, b) { const lat = (a[1] + b[1]) / 2 * Math.PI / 180; return Math.hypot((a[0] - b[0]) * Math.cos(lat), a[1] - b[1]) * Math.PI / 180 * EARTH_RADIUS; }
function moveMeters(point, vector, meters) { const scale = 180 / Math.PI / EARTH_RADIUS; return [point[0] + vector[0] * meters * scale / Math.cos(point[1] * Math.PI / 180), point[1] + vector[1] * meters * scale]; }
function headingBetween(from, to) { const latitude = (from[1] + to[1]) / 2 * Math.PI / 180; return Math.atan2((to[0] - from[0]) * Math.cos(latitude), to[1] - from[1]) * 180 / Math.PI; }
function headingVector(degrees) { const radians = degrees * Math.PI / 180; return [Math.sin(radians), Math.cos(radians)]; }
function normalizeDegrees(value) { return ((value % 360) + 360) % 360; }
function angularDistance(a, b) { return Math.abs(((a - b + 540) % 360) - 180); }
module.exports = {
SIGNAL_LAYOUT,
signalNodeKey,
buildTrafficSignalFeatures,
validateTrafficSignalFeatures,
validateTrafficSignalSourceReferences,
buildTrafficSignalsFromFeatures,
buildTrafficSignals,
readTrafficSignalFeatures,
readTrafficSignals,
};
-11091
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
{"type":"FeatureCollection","features":[{"type":"Feature","id":"10","properties":{"type":1},"geometry":{"type":"MultiPolygon","coordinates":[[[[114.12670642509887,30.459719866954526],[114.12672480418713,30.459728657730796],[114.12674493919597,30.459737997306732],[114.1267833123607,30.459756158076946],[114.12680436982367,30.45976593212108],[114.12685397313732,30.459789508849415],[114.12690012817846,30.45981125331352],[114.12696581650293,30.459842297256657],[114.12703599666129,30.459875724524046],[114.1270498805918,30.45988229362388],[114.12705936578135,30.459887101893713],[114.12713738017123,30.459929772755643],[114.1272371446353,30.459984098991324],[114.12732032068887,30.460029332274345],[114.12756802667649,30.460156811375963],[114.1276272681774,30.46018476753933],[114.12767330666927,30.460206334960937],[114.12774798860086,30.460241752793856],[114.12781876709889,30.460274913778548],[114.12793737942023,30.46033070051492],[114.12802476152558,30.460371550079984],[114.12803377753897,30.460375985604387],[114.12804110941299,30.460380028660342],[114.12805101374497,30.460386354257707],[114.12806883527543,30.460398025244622],[114.12808654794983,30.46041118828605],[114.12809933710143,30.46042164630667],[114.1281073950421,30.460428573291047],[114.12811395128384,30.460434620557336],[114.12811938213294,30.460440066689017],[114.12812926407065,30.460450347349173],[114.12813473454605,30.46045657462467],[114.12814164327082,30.460464424462735],[114.12814730374363,30.460471255615666],[114.12815294371121,30.460478077312562],[114.12815879253623,30.460486283596325],[114.1281645602278,30.460494776825477],[114.12816883816927,30.460501272024807],[114.12817349886402,30.460509245696944],[114.1281771352045,30.460517071410813],[114.12817986770692,30.460522406328934],[114.12818358105403,30.460530441147434],[114.12818686670175,30.46053817825591],[114.12819018776598,30.460545819342492],[114.12819418910176,30.46055564186251],[114.12820380410353,30.460582194804786],[114.12820842032188,30.46060375471472],[114.12821202983478,30.46062954010985],[114.1282137381741,30.46064526447438],[114.12821400817043,30.460653439918755],[114.12821393731382,30.46067277098964],[114.12821257637805,30.46069672891237],[114.12821098332131,30.460710299619304],[114.12820721720577,30.460726258836115],[114.12819314233184,30.460756750044617],[114.12817805241743,30.46078387834311],[114.1281664689422,30.460803920591136],[114.12815723705758,30.46081876175518],[114.12813556102246,30.46085392543641],[114.12786187058398,30.461286782141404],[114.12767310863411,30.461588040608625],[114.12749605673096,30.46186848121499],[114.12771556983981,30.46197223706339],[114.12829921553568,30.46103318454979],[114.12834745214138,30.460953266211526],[114.12837228716977,30.460914859036752],[114.1283903573218,30.460889225666122],[114.12840962380116,30.46086537779413],[114.12842658919257,30.46084461385105],[114.12844027647458,30.460830720633155],[114.12845700359827,30.460817290594896],[114.12846927807756,30.460807952031754],[114.1284793259837,30.46080120044445],[114.12848732126338,30.46079615416839],[114.12849824982679,30.460790108078196],[114.12851735673152,30.46078057113085],[114.12853428994015,30.460773234382117],[114.12854767478771,30.460768204092016],[114.12856867125925,30.460760493145365],[114.12858706934223,30.460754937340415],[114.12861834861083,30.46074820545063],[114.12862756243905,30.46074661029612],[114.12864869683986,30.46074212232996],[114.12865920934019,30.460740441110147],[114.12866868493343,30.460739396487128],[114.12868036248904,30.460738380348605],[114.12868990874968,30.460737761184348],[114.12870180719327,30.460737363112344],[114.12871667998598,30.460737392256405],[114.1287292771692,30.46073780823301],[114.1287499886682,30.46073912084974],[114.12876640653077,30.460741578573987],[114.12877789632182,30.460743427010925],[114.12878992723334,30.460745602599992],[114.12880068089633,30.46074775119988],[114.12881210760563,30.460750689795557],[114.12882252563773,30.460753300372676],[114.12882949358202,30.460755215632997],[114.12884206581988,30.460759486418695],[114.12884823128418,30.460761483949376],[114.12890089866964,30.460782505183808],[114.12891485544512,30.460788816797255],[114.12895540785316,30.460808048501978],[114.12902501127174,30.46084044145126],[114.12908466293443,30.460868698056956],[114.12910546198879,30.46087847390208],[114.1291300006723,30.460890007409656],[114.12917162969823,30.4609095887503],[114.12927120714293,30.460956547967346],[114.12935900625274,30.460997903663344],[114.12943766593234,30.461035023980024],[114.12945728539037,30.461044170004904],[114.12947426624748,30.461052231980972],[114.12948015380047,30.46105484591913],[114.12948639545796,30.4610574312437],[114.1294967439802,30.461061699880304],[114.12951325767341,30.461068326698438],[114.12953869523535,30.4610785199137],[114.12956431897612,30.461088970193117],[114.12959304786149,30.461100566489673],[114.1296316067205,30.461116134315017],[114.12965073525396,30.461123943783882],[114.1296767364358,30.46113443300Line truncated
-19
View File
@@ -1,19 +0,0 @@
"use strict";
const assert = require("assert/strict");
const fs = require("fs");
const path = require("path");
const compiler = require("../src");
assert.equal(typeof compiler.laneGeometry.laneCenterline, "function");
assert.equal(typeof compiler.gaodeReference.convertGeoJson, "function");
assert.equal(typeof compiler.turnLaneArrows.buildCustomTurnLaneArrows, "function");
assert.equal(typeof compiler.complexJunction.buildComplexJunctionGeometry, "function");
assert.equal(typeof compiler.nativeRoad.compileRoadModel, "function");
assert.equal(typeof compiler.check.checkOutput, "function");
const fixture = path.join(__dirname, "fixtures", "fengshu-er-road.osm");
assert.ok(fs.existsSync(fixture));
assert.throws(() => compiler.compiler.validateInput({ id: "area" }), /RoadCompilerInput/);
const model = compiler.nativeRoad.compileRoadModel(fs.readFileSync(fixture, "utf8"), { schema: "native-road-overrides/v1", overrides: [] });
assert.equal(model.roads.length, 24);
console.log("road compiler package tests passed");
-1
View File
@@ -1 +0,0 @@
*{box-sizing:border-box}body{margin:0;background:#eef1ef;color:#202523;font:14px system-ui,sans-serif}header{height:50px;display:flex;gap:12px;align-items:center;padding:0 16px;background:#183a32;color:#fff}header span{color:#c9d8d2}#dirty-state.dirty{color:#ffe08a;font-weight:700}button{border:1px solid #82988f;background:#fff;color:#1d392f;padding:7px 10px;border-radius:3px;cursor:pointer}button:disabled{cursor:default;opacity:.55}header button:first-of-type{margin-left:auto}main{display:grid;grid-template-columns:260px minmax(0,1fr) 320px;height:calc(100vh - 50px)}aside{overflow:auto;background:#fff;padding:16px}.issues{border-right:1px solid #d5dfda}.inspector{border-left:1px solid #d5dfda}.map{position:relative;background:#d7e2de;min-height:400px}canvas{width:100%;height:100%;display:block}.legend{position:absolute;bottom:12px;left:12px;background:#fff;padding:8px;box-shadow:0 1px 4px #0003}.legend i{display:inline-block;width:18px;height:7px;margin:0 4px -1px 10px}.reference{background:#a5b0b5}.native{background:#296654}.line{height:3px!important;background:#263630}.junction{width:10px!important;height:10px!important;background:#0e7860;border-radius:50%}.warning{width:10px!important;height:10px!important;background:#d49318;border-radius:50%}h1{font-size:16px;margin:0 0 8px}h2{font-size:14px;margin:12px 0 8px}.muted,output,pre{color:#52615b}.issues ul{list-style:none;padding:0;margin:0}.issues button{width:100%;text-align:left;margin:4px 0;background:#fff7e5;border-color:#e7c67b;color:#693c00}.issues button.error{background:#fff0ee;border-color:#e3a49b;color:#8d261a}.segmented{display:flex;margin:0 0 8px}.segmented button{flex:1;border-radius:0;padding:6px 4px;font-size:12px}.segmented button+button{border-left:0}.segmented button:first-child{border-radius:3px 0 0 3px}.segmented button:last-child{border-radius:0 3px 3px 0}.segmented button.active{background:#286956;border-color:#286956;color:#fff}label{display:block;margin:10px 0}input[type=number]{display:block;width:100%;padding:7px;border:1px solid #aab8b2;border-radius:2px}output,pre{display:block;white-space:pre-wrap;overflow-wrap:anywhere}form button{margin-top:8px;background:#286956;color:white;border:0}dl{display:grid;grid-template-columns:1fr auto;gap:5px 10px;margin:0}dt{color:#52615b}dd{margin:0;font-variant-numeric:tabular-nums}hr{border:0;border-top:1px solid #dde4e1;margin:16px 0}details{margin-top:16px}summary{cursor:pointer;font-weight:600}@media(max-width:900px){main{grid-template-columns:minmax(0,1fr)}.issues{display:none}.inspector{position:absolute;right:0;bottom:0;width:min(360px,100%);max-height:55vh;border-top:1px solid #d5dfda}}
-459
View File
@@ -1,459 +0,0 @@
import Map from "/vendor/ol/Map.js";
import View from "/vendor/ol/View.js";
import VectorLayer from "/vendor/ol/layer/Vector.js";
import VectorSource from "/vendor/ol/source/Vector.js";
import GeoJSON from "/vendor/ol/format/GeoJSON.js";
import Feature from "/vendor/ol/Feature.js";
import LineString from "/vendor/ol/geom/LineString.js";
import Point from "/vendor/ol/geom/Point.js";
import Style from "/vendor/ol/style/Style.js";
import Fill from "/vendor/ol/style/Fill.js";
import Stroke from "/vendor/ol/style/Stroke.js";
import CircleStyle from "/vendor/ol/style/Circle.js";
import Text from "/vendor/ol/style/Text.js";
import Polygon from "/vendor/ol/geom/Polygon.js";
import RegularShape from "/vendor/ol/style/RegularShape.js";
import Select from "/vendor/ol/interaction/Select.js";
import { click } from "/vendor/ol/events/condition.js";
import { fromLonLat } from "/vendor/ol/proj.js";
const geojson = new GeoJSON();
const areaLabel = document.querySelector("#area");
const status = document.querySelector("#status");
const form = document.querySelector("#road-form");
const hint = document.querySelector("#hint");
const roadName = document.querySelector("#road-name");
const movementSummary = document.querySelector("#movement-summary");
const laneConvention = document.querySelector("#lane-convention");
const selectedMovementPanel = document.querySelector("#selected-movement");
const movementDetail = document.querySelector("#movement-detail");
const directionSwitch = document.querySelector("#direction-switch");
const widthInput = document.querySelector("#width");
const lanesInput = document.querySelector("#lanes");
const leftInput = document.querySelector("#left");
const rightInput = document.querySelector("#right");
const centerLineForm = document.querySelector("#center-line-form");
const centerLineSegment = document.querySelector("#center-line-segment");
const markingStyleHeading = document.querySelector("#marking-style-heading");
const centerLineStyleInput = document.querySelector("#center-line-style");
const doubleYellowOption = document.createElement("option");
doubleYellowOption.value = "double-yellow-solid"; doubleYellowOption.textContent = "双黄实线"; centerLineStyleInput.append(doubleYellowOption);
const evidence = document.querySelector("#evidence");
const diagnostics = document.querySelector("#diagnostics");
const diagnosticFilters = document.querySelector("#diagnostic-filters");
const summary = document.querySelector("#summary");
const connectionsBox = document.querySelector("#connections");
const addConnectionButton = document.querySelector("#add-connection");
const saveButton = document.querySelector("#save");
const compileButton = document.querySelector("#compile");
const dirtyState = document.querySelector("#dirty-state");
const scenePreviewToggle = document.querySelector("#scene-preview");
const selectedJunctionPanel = document.querySelector("#selected-junction");
const junctionDetail = document.querySelector("#junction-detail");
const directionArrowsToggle = document.createElement("label");
directionArrowsToggle.innerHTML = '<input data-layer="directionArrows" type="checkbox" checked> 道路方向箭头';
const markingsToggle = document.createElement("label");
markingsToggle.innerHTML = '<input data-layer="markings" type="checkbox" checked> 车道分隔线与路口转向箭头';
const centerLinesToggle = document.createElement("label");
centerLinesToggle.innerHTML = '<input data-layer="centerLines" type="checkbox" checked> 道路中心线';
const edgeLinesToggle = document.createElement("label");
edgeLinesToggle.innerHTML = '<input data-layer="edgeLines" type="checkbox"> 道路外缘线';
const controlsToggle = document.createElement("label");
controlsToggle.innerHTML = '<input data-layer="controls" type="checkbox" checked> 斑马线与停止线';
const signalsToggle = document.createElement("label");
signalsToggle.innerHTML = '<input data-layer="signals" type="checkbox" checked> 红绿灯设施';
document.querySelector('[data-layer="lanes"]').closest("label").after(directionArrowsToggle, markingsToggle, centerLinesToggle, edgeLinesToggle, controlsToggle, signalsToggle);
// Only offered when the server was started with --debug; without it the state
// carries no candidates and an empty toggle would just be confusing.
const candidateAction = document.createElement("section");
document.querySelector(".inspector").insertBefore(candidateAction, document.querySelector(".inspector details"));
const candidatesToggle = document.createElement("label");
candidatesToggle.hidden = true;
candidatesToggle.innerHTML = '<input data-layer="junctionCandidates" type="checkbox" checked> 复杂路口候选(debug)';
signalsToggle.after(candidatesToggle);
const gaodeReferenceColors = { 1: "#2563eb", 2: "#0f766e", 3: "#7c3aed", 4: "#ea580c", 5: "#64748b" };
let state;
let selectedRoad = null;
let selectedMovement = null;
let selectedJunction = null;
let staged = [];
let manualFromEndpoint = null;
let diagnosticFilter = "all";
let scenePreview = false;
let selectedCenterLineSegment = null;
let selectedLaneSeparator = null;
let selectedEdgeLine = null;
let selectedSignal = null;
const signalPanel = document.createElement("section");
signalPanel.innerHTML = '<hr><h2>原生红绿灯</h2><button type="button" data-signal="generate">从 OSM 生成缺失信号灯</button><label>检查信号灯<select name="signal-picker"><option value="">选择设施</option></select></label><form hidden><output></output><label>灯杆经度<input name="lon" type="number" min="-180" max="180" step="0.000001"></label><label>灯杆纬度<input name="lat" type="number" min="-90" max="90" step="0.000001"></label><label>横杆方向(度)<input name="mastHeading" type="number" min="0" max="360" step="1"></label><label>横杆长度(米)<input name="mastReach" type="number" min="0.1" max="30" step="0.1"></label><label>灯面朝向(度)<input name="faceHeading" type="number" min="0" max="360" step="1"></label><label>相位组<input name="phase" type="number" min="0" max="1" step="1"></label><label><input name="enabled" type="checkbox"> 启用</label><button type="submit">保存信号灯</button><button type="button" data-signal="delete">删除信号灯</button></form>';
document.querySelector(".inspector").insertBefore(signalPanel, document.querySelector(".inspector details"));
const signalForm = signalPanel.querySelector("form");
const signalOutput = signalForm.querySelector("output");
const signalPicker = signalPanel.querySelector('[name="signal-picker"]');
const source = () => new VectorSource();
const layers = {
reference: new VectorLayer({ source: source(), visible: false, style: new Style({ fill: new Fill({ color: "rgba(123, 140, 148, .28)" }), stroke: new Stroke({ color: "#8999a0", width: 1 }) }) }),
gaodeReference: new VectorLayer({ source: source(), visible: true, zIndex: 1, style: (feature) => { const color = gaodeReferenceColors[feature.get("type")] || "#475569"; return new Style({ fill: new Fill({ color: `${color}26` }), stroke: new Stroke({ color, width: 1.5 }) }); } }),
native: new VectorLayer({ source: source(), style: nativeSurfaceStyle }),
edgeLines: new VectorLayer({ source: source(), visible: false, style: markingStyle }),
sidewalks: new VectorLayer({ source: source(), style: sidewalkSurfaceStyle }),
osm: new VectorLayer({ source: source(), style: (feature) => new Style({ stroke: new Stroke({ color: feature.get("road_id") === selectedRoad?.id ? "#006e91" : "#263630", width: feature.get("road_id") === selectedRoad?.id ? 5 : 2 }) }) }),
lanes: new VectorLayer({ source: source(), style: laneStyle }),
directionArrows: new VectorLayer({ source: source(), style: markingStyle }),
markings: new VectorLayer({ source: source(), style: markingStyle }),
centerLines: new VectorLayer({ source: source(), style: centerLineStyle }),
controls: new VectorLayer({ source: source(), style: markingStyle }),
signals: new VectorLayer({ source: source(), style: signalAssemblyStyle, zIndex: 30 }),
osmDirection: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new RegularShape({ points: 3, radius: 9, rotation: feature.get("rotation"), fill: new Fill({ color: "#006e91" }), stroke: new Stroke({ color: "#fff", width: 1.5 }) }) }), zIndex: 11 }),
connectors: new VectorLayer({ source: source(), style: (feature) => effectiveConnectorEnabled(feature.getProperties()) ? new Style({ stroke: new Stroke({ color: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? "#d1226f" : "#ad3a76", width: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? 4 : 2, lineDash: [7, 5] }) }) : null }),
junctionCandidates: new VectorLayer({ source: source(), visible: true, zIndex: 25, style: (feature) => [
new Style({ fill: new Fill({ color: "rgba(219, 39, 119, .12)" }), stroke: new Stroke({ color: "#db2777", width: 2, lineDash: [8, 5] }) }),
new Style({ text: new Text({ text: `#${feature.get("index")} ${feature.get("nodeCount")}节点`, font: "bold 13px system-ui, sans-serif", fill: new Fill({ color: "#831843" }), stroke: new Stroke({ color: "#fff", width: 3 }), offsetY: -14 }) }),
] }),
diagnostics: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new CircleStyle({ radius: 6, fill: new Fill({ color: feature.get("severity") === "error" ? "#bf3b2e" : "#d49318" }), stroke: new Stroke({ color: "#fff", width: 1 }) }) }) }),
selectedRoad: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#00a5cf", width: 8 }) }), zIndex: 10 }),
selectedMovement: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#f0b323", width: 6 }) }), zIndex: 12 }),
};
const map = new Map({ target: "map", layers: [layers.gaodeReference, layers.reference, layers.native, layers.edgeLines, layers.sidewalks, layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.controls, layers.signals, layers.connectors, layers.junctionCandidates, layers.diagnostics, layers.selectedRoad, layers.osmDirection, layers.selectedMovement], view: new View({ center: [0, 0], zoom: 2 }) });
const select = new Select({ condition: click, layers: (layer) => manualFromEndpoint ? layer === layers.osm : [layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.edgeLines, layers.controls, layers.signals, layers.connectors, layers.native, layers.junctionCandidates, layers.diagnostics].includes(layer), hitTolerance: 12, style: null });
map.addInteraction(select);
select.on("select", ({ selected }) => {
const feature = selected[0];
if (!feature) return;
if (feature.get("candidate_index")) return selectJunctionCandidate(feature);
if (feature.get("signal_uid")) return selectSignal(poleFeatureForSignal(feature.get("signal_uid")) || feature);
if (manualFromEndpoint) return chooseManualTarget(roadForFeature(feature));
const junction = junctionForFeature(feature);
if (junction) return selectJunction(junction);
const provenance = feature.get("provenance");
if (provenance?.startsWith("native-road-")) {
const road = roadForFeature(feature);
const directionArrow = provenance === "native-road-direction-arrow/v1";
const turnArrow = provenance === "native-road-turn-arrow/v1";
const centerLine = provenance === "native-road-center-line/v1";
const edgeLine = provenance === "native-road-edge-line/v1";
const crosswalk = provenance === "native-road-crosswalk/v1";
const stopLine = provenance === "native-road-stop-line/v1";
const markingType = centerLine ? "道路中心线" : edgeLine ? "道路外缘线" : crosswalk ? "斑马线" : stopLine ? "停止线" : directionArrow ? "道路方向箭头" : turnArrow ? "路口转向箭头" : "车道分隔线";
selectRoad(road);
if (centerLine) selectCenterLine(feature); else if (edgeLine) selectEdgeLine(feature); else if (provenance === "native-road-lane-separator/v1") selectLaneSeparator(feature); else clearCenterLineSelection();
evidence.textContent = JSON.stringify({
标线类型: markingType,
人行横道节点: crosswalk || stopLine ? feature.get("crossing_node_id") : null,
OSM道路: feature.get("osm_way_ids"),
原生道路: feature.get("road_id"),
道路段: centerLine ? feature.get("segment_id") : null,
方向: feature.get("direction"),
车道: feature.get("lane_id") || feature.get("lane_index") || `${feature.get("left_lane_index")} 与 ${feature.get("right_lane_index")} 之间`,
转向: turnArrow ? feature.get("maneuver") : null,
样式: centerLine || edgeLine || provenance === "native-road-lane-separator/v1" ? feature.get("effective_style") : null,
放置方法: feature.get("placement_method") || null,
道路内距离米: feature.get("distance_along_lane_meters") || null,
路口前距离米: feature.get("placement_distance_meters") || null,
来源: provenance,
}, null, 2);
return message(`已选中${markingType}`);
}
const movement = state.compiled.movements?.find((item) => item.id === feature.get("movement_id")) || null;
selectRoad(roadForFeature(feature), undefined, movement);
});
map.on("pointermove", (event) => { map.getTargetElement().style.cursor = map.hasFeatureAtPixel(event.pixel, { hitTolerance: 8 }) ? "pointer" : ""; });
function message(text) { status.textContent = text; }
function updateDirtyState() {
const count = staged.length;
dirtyState.textContent = count ? `未保存修改 ${count} 项` : "所有修改已保存";
dirtyState.classList.toggle("dirty", count > 0);
saveButton.disabled = count === 0;
}
function roadLabel(road) { return road.tags.name || `${road.highway}(OSM ${road.osmWayIds.join(", ")})`; }
function osmDirectionLabel(road) { return road?.direction === "forward" ? "沿 OSM 方向" : "逆 OSM 方向"; }
function roadIdFromLane(laneId) { return typeof laneId === "string" ? laneId.slice(5, laneId.lastIndexOf(":")) : ""; }
function laneIndex(laneId) { return Number(String(laneId).split(":").at(-1)); }
function lanePositionLabel(road, index) { return road?.laneCount === 1 ? "唯一车道" : `左起第 ${index} 车道`; }
function laneStyle(feature) { const roadId = feature.get("road_id"); const selected = Boolean(roadId && selectedRoad && roadId === selectedRoad.id); const composite = feature.get("cluster_preview"); return new Style({ stroke: new Stroke({ color: selected ? "#006e91" : "#f5f6ee", width: selected ? 3 : composite ? 1.6 : 1.3, lineDash: composite ? [7, 5] : [5, 4] }) }); }
function markingStyle(feature) { const yellow = feature?.get("color") === "yellow"; return new Style({ fill: new Fill({ color: yellow ? "#f5be2a" : "#f5f6ee" }), stroke: new Stroke({ color: yellow ? "#d29d16" : "#d9dacf", width: 1 }) }); }
function signalAssemblyStyle(feature) { const component = feature.get("signal_component"); if (component === "mast") return [new Style({ stroke: new Stroke({ color: "#fff", width: 9 }) }), new Style({ stroke: new Stroke({ color: "#007f99", width: 5 }) })]; if (component === "face") return [new Style({ stroke: new Stroke({ color: "#fff", width: 7 }) }), new Style({ stroke: new Stroke({ color: "#df2435", width: 3 }) })]; if (component === "head") { const heading = Number(feature.get("face_heading_deg")) || 0; return new Style({ image: new RegularShape({ points: 3, radius: 8, rotation: heading * Math.PI / 180, fill: new Fill({ color: "#df2435" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); } return new Style({ image: new RegularShape({ points: 4, radius: 6, angle: Math.PI / 4, fill: new Fill({ color: "#263630" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); }
function centerLineStyle(feature) { const white = feature.get("color") === "white"; const color = white ? "#faf9ee" : "#f5be2a"; return new Style({ fill: new Fill({ color }), stroke: new Stroke({ color: feature.get("pattern") === "solid" ? color : white ? "#aeb0aa" : "#d29d16", width: feature.get("pattern") === "solid" ? .25 : .8 }) }); }
function nativeSurfaceStyle(feature) {
// Split road features meet at OSM junction nodes. Their per-feature outlines
// are editing aids, not physical seams, so scene mode must render fills only.
if (scenePreview) return new Style({ fill: new Fill({ color: "#3f4b50" }) });
if (feature.get("cluster_id") && feature.get("complex_part")) return new Style({ fill: new Fill({ color: "#6f948a" }) });
if (feature.get("kind") === "cluster") return new Style({ fill: new Fill({ color: "rgba(20, 132, 112, .5)" }), stroke: new Stroke({ color: "#075e4f", width: 4, lineDash: [10, 5] }) });
if (feature.get("template")) return new Style({ fill: new Fill({ color: "rgba(20, 132, 112, .46)" }), stroke: new Stroke({ color: "#087c67", width: 3, lineDash: [7, 4] }) });
return feature.get("native_id")?.startsWith("junction:")
? new Style({ fill: new Fill({ color: "rgba(12, 116, 91, .38)" }), stroke: new Stroke({ color: "#0e785f", width: 1.5 }) })
: new Style({ fill: new Fill({ color: "rgba(40, 105, 86, .35)" }), stroke: new Stroke({ color: "#296956", width: 1 }) });
}
function sidewalkSurfaceStyle() {
return scenePreview
? new Style({ fill: new Fill({ color: "#b7b9ad" }) })
: new Style({ fill: new Fill({ color: "rgba(218, 191, 137, .6)" }), stroke: new Stroke({ color: "#9b7c40", width: 1 }) });
}
function directionArrowFeature(geometry) { const middle = geometry.getCoordinateAt(.5); const before = geometry.getCoordinateAt(.48); const after = geometry.getCoordinateAt(.52); const length = Math.hypot(after[0] - before[0], after[1] - before[1]); if (length < .01) return null; return new Feature({ geometry: new Point(middle), rotation: Math.atan2(after[1] - before[1], after[0] - before[0]) }); }
function refreshOsmDirection() { const directionSource = layers.osmDirection.getSource(); directionSource.clear(); if (!selectedRoad) return; const centerline = new LineString(selectedRoad.centerline).transform("EPSG:4326", "EPSG:3857"); const arrow = directionArrowFeature(centerline); if (arrow) directionSource.addFeature(arrow); }
function refreshSelectedMovement() { const movementSource = layers.selectedMovement.getSource(); movementSource.clear(); if (!selectedMovement?.geometryPublished || !effectiveConnectorEnabled({ connection_id: selectedMovement.connectionId, fromLaneId: selectedMovement.fromLaneId, toLaneId: selectedMovement.toLaneId })) return; const feature = layers.connectors.getSource().getFeatures().find((candidate) => candidate.get("movement_id") === selectedMovement.id); if (feature) movementSource.addFeature(new Feature({ geometry: feature.getGeometry().clone() })); }
function roadForFeature(feature) {
const properties = feature.getProperties();
const roadId = properties.road_id || properties.subjectId || roadIdFromLane(properties.from_lane_id) || properties.directional_road_ids?.split(",")[0];
return state.compiled.model.roads.find((road) => road.id === roadId) || null;
}
function junctionForFeature(feature) { const id = feature.get("native_id"); return id?.startsWith("junction:") || id?.startsWith("junction-cluster:") ? layers.native.getSource().getFeatures().find((item) => item.get("native_id") === id) : null; }
function endpointFor(road, side) { return state.compiled.model.endpoints.find((endpoint) => endpoint.roadId === road?.id && endpoint.side === side) || null; }
function endpointsCompatible(from, to) { if (!from || !to || from.roadId === to.roadId || from.side !== "end" || to.side !== "start") return false; if (from.nodeId === to.nodeId) return true; const dx = (from.coordinate[0] - to.coordinate[0]) * 111320 * Math.cos(from.coordinate[1] * Math.PI / 180); const dy = (from.coordinate[1] - to.coordinate[1]) * 111320; return Math.hypot(dx, dy) <= 35; }
function readFeatures(collection, predicate = null) { const source = collection || { type: "FeatureCollection", features: [] }; const filtered = predicate ? { ...source, features: (source.features || []).filter(predicate) } : source; return geojson.readFeatures(filtered, { dataProjection: "EPSG:4326", featureProjection: "EPSG:3857" }); }
function rawRoadFeatures() { return state.compiled.model.roads.map((road) => new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857"), road_id: road.id })); }
function updateSources() {
layers.reference.getSource().clear(); layers.reference.getSource().addFeatures(readFeatures(state.layers.osm2streetsRoadSurface));
layers.gaodeReference.getSource().clear(); layers.gaodeReference.getSource().addFeatures(readFeatures(state.junctionReference?.converted));
layers.native.getSource().clear(); layers.native.getSource().addFeatures([...readFeatures(state.layers.nativeRoadSurface), ...readFeatures(state.layers.nativeIntersectionSurface)]);
layers.sidewalks.getSource().clear(); layers.sidewalks.getSource().addFeatures(readFeatures(state.layers.nativeSidewalkSurface));
layers.osm.getSource().clear(); layers.osm.getSource().addFeatures(rawRoadFeatures());
layers.lanes.getSource().clear(); layers.lanes.getSource().addFeatures(readFeatures(state.layers.laneCenterlines, (feature) => !feature.properties?.cluster_internal && !feature.properties?.cluster_preview_hidden));
layers.edgeLines.getSource().clear(); layers.edgeLines.getSource().addFeatures(readFeatures(state.layers.edgeLines));
layers.directionArrows.getSource().clear(); layers.directionArrows.getSource().addFeatures(readFeatures(state.layers.directionArrows, (feature) => !feature.properties?.cluster_preview_hidden));
layers.markings.getSource().clear(); layers.markings.getSource().addFeatures([...readFeatures(state.layers.laneSeparators, (feature) => !feature.properties?.cluster_preview_hidden), ...readFeatures(state.layers.turnArrows, (feature) => !feature.properties?.cluster_preview_hidden)]);
layers.centerLines.getSource().clear(); layers.centerLines.getSource().addFeatures(readFeatures(state.layers.centerLines, (feature) => !feature.properties?.cluster_preview_hidden));
layers.controls.getSource().clear(); layers.controls.getSource().addFeatures([...readFeatures(state.layers.crosswalks), ...readFeatures(state.layers.vehicleStopLines)]);
const signalFeatures = readFeatures(state.trafficSignals?.assemblies || { type: "FeatureCollection", features: [] }); const armFeatures = []; const faceFeatures = []; const headFeatures = []; for (const signal of state.trafficRuntime?.signals || []) { const arm = signal.pose?.arm; const head = signal.pose?.head; if (!arm || !head) continue; const properties = { signal_uid: signal.id }; const headPoint = fromLonLat([head.longitude, head.latitude]); const radians = Number(head.faceHeadingDegrees) * Math.PI / 180; const faceEnd = [headPoint[0] + Math.sin(radians) * 2.5, headPoint[1] + Math.cos(radians) * 2.5]; armFeatures.push(new Feature({ geometry: new LineString([fromLonLat([arm.from.longitude, arm.from.latitude]), fromLonLat([arm.to.longitude, arm.to.latitude])]), signal_component: "mast", ...properties })); faceFeatures.push(new Feature({ geometry: new LineString([headPoint, faceEnd]), signal_component: "face", ...properties })); headFeatures.push(new Feature({ geometry: new Point(faceEnd), signal_component: "head", face_heading_deg: head.faceHeadingDegrees, ...properties })); } layers.signals.getSource().clear(); layers.signals.getSource().addFeatures([...armFeatures, ...faceFeatures, ...signalFeatures, ...headFeatures]); const pickerValue = signalPicker.value; signalPicker.replaceChildren(new Option("选择设施", "")); signalFeatures.forEach((feature) => signalPicker.add(new Option(feature.get("display_id") || feature.get("signal_uid"), feature.get("signal_uid")))); signalPicker.value = pickerValue;
layers.connectors.getSource().clear(); layers.connectors.getSource().addFeatures(readFeatures(state.layers.connectors, (feature) => !feature.properties?.cluster_internal));
candidatesToggle.hidden = !(state.debug?.junctionCandidates || []).length;
renderJunctionCandidates();
layers.diagnostics.getSource().clear(); layers.diagnostics.getSource().addFeatures(readFeatures({ type: "FeatureCollection", features: state.compiled.diagnostics.filter((item) => item.geometry).map(({ geometry, ...properties }) => ({ type: "Feature", properties, geometry })) }));
const extent = layers.osm.getSource().getExtent(); if (Number.isFinite(extent[0])) map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 });
}
// Draw one convex-ish hull per candidate cluster so the whole intersection is
// outlined, not just its centre, and label it with the same index the inspector
// and the console listing use.
function renderJunctionCandidates() {
const source = layers.junctionCandidates.getSource();
source.clear();
const list = state.debug?.junctionCandidates || [];
if (!list.length) return;
for (const candidate of list) {
const nodes = candidate.nodeIds.map((nodeId) => nodeCoordinate(nodeId)).filter(Boolean);
if (!nodes.length) continue;
const ring = candidateRing(nodes, Math.max(12, candidate.coreRadiusMeters * .6));
source.addFeature(new Feature({ geometry: new Polygon([ring]), candidate_index: candidate.index, index: candidate.index, nodeCount: candidate.nodeCount, candidate_id: candidate.id }));
}
}
function nodeCoordinate(nodeId) {
for (const road of state.compiled.model.roads) {
const at = road.sourceNodeIds.findIndex((item) => String(item) === String(nodeId));
if (at === 0) return road.centerline[0];
if (at === road.sourceNodeIds.length - 1) return road.centerline.at(-1);
}
return null;
}
// A rounded envelope around the member nodes: sample a circle of `padMeters`
// around each node and take the outer boundary by angle from the centroid.
function candidateRing(nodes, padMeters) {
const centre = nodes.reduce((sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length], [0, 0]);
const metresPerLon = 111320 * Math.cos(centre[1] * Math.PI / 180);
const points = [];
for (let degrees = 0; degrees < 360; degrees += 12) {
const radians = degrees * Math.PI / 180;
let best = null;
for (const node of nodes) {
const point = [node[0] + Math.sin(radians) * padMeters / metresPerLon, node[1] + Math.cos(radians) * padMeters / 111320];
const reach = (point[0] - centre[0]) * metresPerLon * Math.sin(radians) + (point[1] - centre[1]) * 111320 * Math.cos(radians);
if (!best || reach > best.reach) best = { point, reach };
}
points.push(fromLonLat(best.point));
}
return [...points, points[0]];
}
function selectJunctionCandidate(feature) {
const candidate = (state.debug?.junctionCandidates || []).find((item) => item.index === feature.get("candidate_index"));
if (!candidate) return;
selectedRoad = null; selectedMovement = null; selectedJunction = null;
form.hidden = true; hint.hidden = false; selectedJunctionPanel.hidden = true;
hint.textContent = `复杂路口候选 #${candidate.index}:${candidate.nodeCount} 个节点,直径 ${candidate.diameterMeters} 米。下方是可直接粘贴到 config 的片段。`;
evidence.textContent = JSON.stringify({
说明: "复制到区域配置文件的 nativeRoad.junctionTemplates.clusters 数组,然后重新编译",
片段: {
id: `cluster-${candidate.nodeIds[0]}`,
template: candidate.template,
nodeIds: candidate.nodeIds,
coreRadiusMeters: candidate.coreRadiusMeters,
cornerRadiusMeters: 12,
outerRadiusExtraMeters: 18,
},
实测: { 节点数: candidate.nodeCount, 直径米: candidate.diameterMeters, 最长内部连接米: candidate.longestLinkMeters, 最宽进口米: candidate.widestApproachMeters },
提示: "coreRadiusMeters 是按节点跨度估的起点,配好后按实际效果调整;有高德参考几何时它会被校准值覆盖。",
}, null, 2);
renderCandidateAction(candidate);
message(`已选中复杂路口候选 #${candidate.index}`);
}
// The accept button lives beside the snippet so the manual path stays available
// if the write is refused; both describe the same cluster.
function renderCandidateAction(candidate) {
candidateAction.replaceChildren();
const button = document.createElement("button");
button.type = "button";
button.textContent = `把候选 #${candidate.index} 加入配置并重新编译`;
button.onclick = async () => {
button.disabled = true;
message(`正在把候选 #${candidate.index} 写入区域配置...`);
try {
const response = await fetch("/api/junction-clusters", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index: candidate.index }), cache: "no-store" });
const result = await response.json();
if (!response.ok || result.ok === false) throw new Error(result.error || `HTTP ${response.status}`);
state = result;
staged = [];
updateDirtyState(); updateSources(); renderDiagnostics(); renderSummary();
candidateAction.replaceChildren();
hint.textContent = `已加入复杂路口 ${result.added.id}(${result.added.nodeIds.length} 个节点),配置已更新并重新编译。`;
message(`已加入 ${result.added.id};如需撤销可 git checkout 区域配置`);
} catch (error) {
button.disabled = false;
message(`加入失败:${error.message}`);
}
};
candidateAction.append(button);
}
function laneId(connection, side) { return connection[side === "from" ? "fromLaneId" : "toLaneId"] || connection[side === "from" ? "from_lane_id" : "to_lane_id"]; }
function effectiveLaneEnabled(connector) { const id = `车道连接:${laneId(connector, "from")}->${laneId(connector, "to")}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connector.enabled !== false; }
function effectiveConnectionEnabled(connection) { const id = `连接:${connection.id}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connection.enabled; }
function effectiveConnectorEnabled(connector) { const connection = state?.compiled.model.connections.find((item) => item.id === connector.connection_id); return effectiveLaneEnabled(connector) && (!connection || effectiveConnectionEnabled(connection)); }
function selectRoad(road, note, movement = null) {
candidateAction.replaceChildren();
selectedRoad = road; selectedMovement = movement; selectedJunction = null; selectedJunctionPanel.hidden = true; layers.osm.changed(); layers.lanes.changed(); layers.connectors.changed(); refreshOsmDirection(); refreshSelectedMovement();
layers.selectedRoad.getSource().clear(); if (road) layers.selectedRoad.getSource().addFeature(new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857") }));
form.hidden = !road; hint.hidden = Boolean(road); if (!road) return;
roadName.textContent = `${roadLabel(road)}(${osmDirectionLabel(road)})`;
widthInput.value = road.widthMeters; lanesInput.value = road.laneCount; leftInput.checked = road.sidewalkLeft; rightInput.checked = road.sidewalkRight;
evidence.textContent = JSON.stringify({ OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 参数来源: road.provenance, 已应用修改: road.appliedOverrideIds, 原始标签: road.tags }, null, 2);
laneConvention.textContent = road.laneCount === 1 ? "蓝色箭头在 OSM 原始中心线上,表示当前方向;“沿 OSM 方向”即节点顺序。本方向只有一条车道。" : "蓝色箭头在 OSM 原始中心线上,表示当前方向;“沿 OSM 方向”即节点顺序。车道按行驶方向从左向右编号。";
renderDirectionSwitch(road); renderMovementSummary(road); renderSelectedMovement(); renderConnections(road); message(note || (selectedMovement ? `已选中行驶动作:${turnLabel(selectedMovement.turn)}` : `已选中:${roadLabel(road)}`));
}
function selectJunction(feature) {
candidateAction.replaceChildren();
selectedJunction = feature; selectedRoad = null; selectedMovement = null; form.hidden = true; hint.hidden = true; selectedJunctionPanel.hidden = false;
const properties = feature.getProperties(); const roadIds = String(properties.source_road_ids || "").split(",").filter(Boolean);
const roads = roadIds.map((id) => state.compiled.model.roads.find((road) => road.id === id)).filter(Boolean);
junctionDetail.textContent = JSON.stringify({ OSM节点: properties.osm_node_id || properties.osm_node_ids, 类型: properties.kind === "cluster" ? "复合路口簇" : properties.kind === "t" ? "T字路口" : "十字路口", 参与方向道路: roads.map((road) => ({ 道路: roadLabel(road), OSM道路: road.osmWayIds, 节点顺序: road.sourceNodeIds })), 构面规则: properties.rule, 模板: properties.template, 边界策略: properties.boundary_mode, 基础截面面积平方米: properties.approach_area_m2, 最终路口面积平方米: properties.surface_area_m2, 外缘扩张倍率: properties.expansion_ratio, 路口退让距离米: properties.cutback_m, 行驶动作数: properties.movement_count, 已绘制连接数: properties.connector_count }, null, 2);
message(`已选中路口:OSM 节点 ${properties.osm_node_id || properties.osm_node_ids}`);
}
function selectSignal(feature) {
selectedSignal = feature.get("signal_uid"); const p = feature.getProperties(); signalPicker.value = selectedSignal;
const [x, y] = feature.getGeometry().getCoordinates();
map.getView().fit([x - 25, y - 25, x + 25, y + 25], { padding: [80, 80, 80, 360], maxZoom: 22, duration: 250 });
signalForm.hidden = false; signalOutput.textContent = `${p.display_id || p.signal_uid}(${p.signal_uid})`;
signalForm.lon.value = feature.getGeometry().clone().transform("EPSG:3857", "EPSG:4326").getCoordinates()[0];
signalForm.lat.value = feature.getGeometry().clone().transform("EPSG:3857", "EPSG:4326").getCoordinates()[1];
signalForm.mastHeading.value = p.mast_heading_deg; signalForm.mastReach.value = p.mast_reach_m; signalForm.faceHeading.value = p.face_heading_deg; signalForm.phase.value = p.phase_group; signalForm.enabled.checked = p.enabled;
evidence.textContent = JSON.stringify({ 信号灯: p.signal_uid, 控制节点: p.control_id, 路口方向: p.approach_id, 来源: state.trafficSignals.provenance }, null, 2); message("已选中原生红绿灯");
}
function poleFeatureForSignal(signalUid) { return layers.signals.getSource().getFeatures().find((item) => item.get("signal_uid") === signalUid && !item.get("signal_component")); }
async function saveSignals(document) { const response = await fetch("/api/traffic-signals", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(document) }); const result = await response.json(); if (!result.ok) throw new Error(result.error); state.trafficSignals = result.trafficSignals; state.trafficRuntime = result.runtime; updateSources(); renderSummary(); }
function signalDocumentWithChange(change) { const document = structuredClone(state.trafficSignals); document.assemblies.features = change(document.assemblies.features); return document; }
signalForm.onsubmit = async (event) => { event.preventDefault(); try { await saveSignals(signalDocumentWithChange((features) => features.map((feature) => feature.properties.signal_uid !== selectedSignal ? feature : { ...feature, geometry: { type: "Point", coordinates: [Number(signalForm.lon.value), Number(signalForm.lat.value)] }, properties: { ...feature.properties, mast_heading_deg: Number(signalForm.mastHeading.value), mast_reach_m: Number(signalForm.mastReach.value), face_heading_deg: Number(signalForm.faceHeading.value), phase_group: Number(signalForm.phase.value), enabled: signalForm.enabled.checked } }))); message("红绿灯已保存"); } catch (error) { message(error.message); } };
signalPanel.querySelector('[data-signal="delete"]').onclick = async () => { try { await saveSignals(signalDocumentWithChange((features) => features.filter((feature) => feature.properties.signal_uid !== selectedSignal))); signalForm.hidden = true; selectedSignal = null; message("红绿灯已删除"); } catch (error) { message(error.message); } };
signalPanel.querySelector('[data-signal="generate"]').onclick = async () => { try { const response = await fetch("/api/traffic-signals/generate", { method: "POST" }); const result = await response.json(); if (!result.ok) throw new Error(result.error); state.trafficSignals = result.trafficSignals; state.trafficRuntime = result.runtime; updateSources(); message("已补充 OSM 信号灯"); } catch (error) { message(error.message); } };
signalPicker.onchange = () => { const feature = poleFeatureForSignal(signalPicker.value); if (feature) selectSignal(feature); };
function turnLabel(turn) { return { left: "左转", through: "直行", right: "右转", uturn: "掉头" }[turn] || turn; }
function renderSelectedMovement() { selectedMovementPanel.hidden = !selectedMovement; if (!selectedMovement) return; const targetRoad = state.compiled.model.roads.find((road) => road.id === selectedMovement.toRoadId); const geometry = selectedMovement.geometryStatus === "connector" ? "已绘制路径" : selectedMovement.geometryStatus === "continuous" ? "节点连续" : "路径过长未绘制"; movementDetail.textContent = `${turnLabel(selectedMovement.turn)}:${lanePositionLabel(selectedRoad, laneIndex(selectedMovement.fromLaneId))} → ${lanePositionLabel(targetRoad, laneIndex(selectedMovement.toLaneId))}\n目标:${roadLabel(targetRoad)}(${osmDirectionLabel(targetRoad)})\n来源端点:${selectedRoad.sourceNodeIds.at(-1)};目标端点:${targetRoad.sourceNodeIds[0]}\n路口节点:${selectedMovement.nodeId}\n状态:${geometry}\n来源:${selectedMovement.provenance}`; }
function renderDirectionSwitch(road) {
directionSwitch.innerHTML = ""; const alternatives = state.compiled.model.roads.filter((item) => item.osmWayIds.join(",") === road.osmWayIds.join(","));
if (alternatives.length < 2) { directionSwitch.textContent = "单向道路"; return; }
for (const item of alternatives) { const button = document.createElement("button"); button.type = "button"; button.textContent = osmDirectionLabel(item); button.disabled = item.id === road.id; button.onclick = () => selectRoad(item); directionSwitch.append(button); }
}
function renderMovementSummary(road) { const movements = state.compiled.movements?.filter((movement) => movement.fromRoadId === road.id && effectiveConnectorEnabled({ connection_id: movement.connectionId, fromLaneId: movement.fromLaneId, toLaneId: movement.toLaneId })) || []; const turns = movements.reduce((result, item) => { result[item.turn] = (result[item.turn] || 0) + 1; return result; }, {}); const labels = { left: "左转", through: "直行", right: "右转", uturn: "掉头" }; const published = movements.filter((movement) => movement.geometryPublished).length; movementSummary.textContent = movements.length ? `已识别 ${movements.length} 个行驶动作,${published} 条已绘制路径:${Object.entries(turns).map(([key, value]) => `${labels[key] || key} ${value}`).join(",")}` : "当前方向没有已识别的行驶动作"; }
function renderConnections(road) {
connectionsBox.innerHTML = ""; const endpoint = state.compiled.model.endpoints.find((item) => item.roadId === road.id && item.side === "end"); addConnectionButton.hidden = !endpoint; const rows = state.compiled.model.connections.filter((connection) => connection.fromEndpointId === endpoint?.id);
if (!rows.length) connectionsBox.textContent = "当前方向到达终点后没有已识别的驶出道路。";
for (const connection of rows) { const target = state.compiled.model.roads.find((item) => item.id === state.compiled.model.endpoints.find((endpointItem) => endpointItem.id === connection.toEndpointId)?.roadId); if (!target) continue; const label = document.createElement("label"); const input = document.createElement("input"); input.type = "checkbox"; input.checked = effectiveConnectionEnabled(connection); input.onchange = () => { stageConnection(connection, input.checked); selectRoad(road, "有未保存修改:转向路径已即时更新"); }; label.append(input, ` ${turnName(road, target)}:${roadLabel(target)}(${osmDirectionLabel(target)})`); connectionsBox.append(label); renderLaneControls(connection); }
renderManualCandidates(endpoint, road);
}
function renderManualCandidates(endpoint, road) { const candidates = state.compiled.diagnostics.find((item) => item.endpointId === endpoint?.id)?.manualCandidates || []; if (!candidates.length) return; const title = document.createElement("p"); title.textContent = "附近可手工连接的驶出方向"; connectionsBox.append(title); for (const candidate of candidates) { const target = state.compiled.model.roads.find((item) => item.id === candidate.roadId); if (!target) continue; const button = document.createElement("button"); button.type = "button"; button.textContent = `${roadLabel(target)}(${candidate.distanceMeters} 米)`; button.onclick = () => { stageConnection({ id: `connection:${endpoint.id}:${candidate.toEndpointId}`, fromEndpointId: endpoint.id, toEndpointId: candidate.toEndpointId }, true); selectRoad(road, "有未保存修改:手工连接已暂存;保存并重新生成后会出现转向路径"); }; connectionsBox.append(button); } }
function renderLaneControls(connection) { const rows = state.compiled.movements?.filter((movement) => movement.connectionId === connection.id) || []; for (const row of rows) { const targetRoad = state.compiled.model.roads.find((road) => road.id === row.toRoadId); const label = document.createElement("label"); const input = document.createElement("input"); input.type = "checkbox"; input.checked = effectiveLaneEnabled(row); input.onchange = () => { stageLaneConnection(row, input.checked); selectRoad(selectedRoad, "有未保存修改:转向路径已即时更新"); }; const geometryNote = row.geometryStatus === "continuous" ? ",节点连续" : row.geometryStatus === "deferred-too-long" ? ",路径过长未绘制" : ""; label.append(input, ` ${lanePositionLabel(selectedRoad, laneIndex(row.fromLaneId))} → ${lanePositionLabel(targetRoad, laneIndex(row.toLaneId))}(${osmDirectionLabel(targetRoad)}${geometryNote})`); connectionsBox.append(label); } }
function turnName(from, to) { const heading = (a, b) => Math.atan2(b[0] - a[0], b[1] - a[1]) * 180 / Math.PI; const delta = ((heading(to.centerline[0], to.centerline[1]) - heading(from.centerline.at(-2), from.centerline.at(-1)) + 540) % 360) - 180; return Math.abs(delta) >= 150 ? "掉头" : Math.abs(delta) <= 30 ? "直行" : delta > 0 ? "右转" : "左转"; }
function stageConnection(connection, enabled) { const id = `连接:${connection.id}`; staged = staged.filter((item) => item.id !== id); staged.push({ id, kind: "junction-connection", fromEndpointId: connection.fromEndpointId, toEndpointId: connection.toEndpointId, enabled }); layers.connectors.changed(); updateDirtyState(); }
function stageLaneConnection(connector, enabled) { const fromLaneId = laneId(connector, "from"); const toLaneId = laneId(connector, "to"); const id = `车道连接:${fromLaneId}->${toLaneId}`; staged = staged.filter((item) => item.id !== id); staged.push({ id, kind: "lane-connection", fromLaneId, toLaneId, enabled }); layers.connectors.changed(); updateDirtyState(); }
function chooseManualTarget(targetRoad) { const toEndpoint = endpointFor(targetRoad, "start"); if (!endpointsCompatible(manualFromEndpoint, toEndpoint)) return message("该方向的起点与当前道路终点不兼容:必须是同一路口,或相距不超过 35 米。"); const connection = { id: `connection:${manualFromEndpoint.id}:${toEndpoint.id}`, fromEndpointId: manualFromEndpoint.id, toEndpointId: toEndpoint.id }; manualFromEndpoint = null; stageConnection(connection, true); selectRoad(selectedRoad, "有未保存修改:手工连接已暂存;保存并重新生成后会出现转向路径"); }
addConnectionButton.onclick = () => { const endpoint = endpointFor(selectedRoad, "end"); if (!endpoint) return; manualFromEndpoint = endpoint; select.getFeatures().clear(); message("请在地图上点击目标方向的 OSM 中心线;仅同一路口或 35 米内的驶出方向可连接。"); };
function focusDiagnostic(item) { const feature = layers.diagnostics.getSource().getFeatures().find((candidate) => candidate.get("id") === item.id); if (feature) map.getView().fit(feature.getGeometry().getExtent(), { padding: [80, 80, 80, 360], maxZoom: 18, duration: 250 }); const junction = layers.native.getSource().getFeatures().find((candidate) => candidate.get("native_id") === item.subjectId); if (junction) return selectJunction(junction); selectRoad(state.compiled.model.roads.find((road) => road.id === item.subjectId), `已定位:${item.message}`); }
function diagnosticLabel(item) { const road = state.compiled.model.roads.find((candidate) => candidate.id === item.subjectId); if (item.rule !== "unconnected-interior-road-end" || !road) return item.message; const candidateCount = item.manualCandidates?.length || 0; return `${roadLabel(road)}(${osmDirectionLabel(road)},节点 ${item.sourceIds[0]}):内部端点未连接${candidateCount ? `,附近有 ${candidateCount} 个可手工连接候选` : ""}`; }
function renderDiagnostics() { const all = state.compiled.diagnostics.filter((diagnostic) => diagnostic.rule !== "ordinary-junction-surface"); const counts = { all: all.length, candidates: all.filter((item) => item.manualCandidates?.length).length, other: all.filter((item) => !item.manualCandidates?.length).length }; for (const button of diagnosticFilters.querySelectorAll("button")) { const filter = button.dataset.diagnosticFilter; button.classList.toggle("active", filter === diagnosticFilter); button.textContent = `${filter === "all" ? "全部" : filter === "candidates" ? "可连接" : "其他"}(${counts[filter]})`; } const visible = all.filter((item) => diagnosticFilter === "all" || diagnosticFilter === "candidates" ? Boolean(item.manualCandidates?.length) : !item.manualCandidates?.length).sort((a, b) => (b.manualCandidates?.length || 0) - (a.manualCandidates?.length || 0)); diagnostics.innerHTML = ""; for (const item of visible) { const button = document.createElement("button"); button.textContent = diagnosticLabel(item); button.onclick = () => focusDiagnostic(item); diagnostics.append(button); } }
function renderSummary() {
const comparison = state.comparison;
const rows = [
["方向道路", comparison.nativeRoadCount],
["路缘与步行带", comparison.nativeSidewalkSurfaceFeatures],
["路口面", comparison.nativeJunctionSurfaceFeatures],
["普通构面路口", comparison.nativeApproachEnvelopeJunctions],
["兜底构面路口", comparison.nativeFallbackJunctions],
["最大外缘扩张", comparison.nativeMaxJunctionExpansionRatio],
["道路中心虚线", comparison.nativeCenterLineFeatures],
["道路方向箭头", comparison.nativeDirectionArrowFeatures],
["路口转向箭头", comparison.nativeTurnArrowFeatures],
["斑马线条带", comparison.nativeCrosswalkFeatures],
["停止线", comparison.nativeVehicleStopLineFeatures],
["红绿灯设施", state.trafficSignals?.assemblies?.features?.length || 0],
["行驶动作", comparison.nativeMovementCount],
["已绘制路径", comparison.nativePublishedMovementCount],
["可手工复核", comparison.unconnectedEndsWithManualCandidates],
["内部断头", comparison.unconnectedInteriorRoadEnds],
["osm2streets 参考", comparison.osm2streetsAvailable ? comparison.osm2streetsRoadSurfaceFeatures : "无"],
];
summary.innerHTML = "";
for (const [label, value] of rows) {
const term = document.createElement("dt"); const detail = document.createElement("dd");
term.textContent = label; detail.textContent = value; summary.append(term, detail);
}
}
function stageRoadOverride(road, changes) { const id = `道路:${road.id}`; const existing = staged.find((item) => item.id === id) || state.overrides.overrides.find((item) => item.id === id); staged = staged.filter((item) => item.id !== id); staged.push({ ...existing, id, kind: "road", roadId: road.id, ...changes }); }
function setMarkingStyleForm(title, target, style, allowsDouble) { centerLineForm.hidden = false; markingStyleHeading.textContent = title; centerLineSegment.textContent = target; doubleYellowOption.hidden = !allowsDouble; centerLineStyleInput.value = style || "yellow-dashed"; }
function selectCenterLine(feature) { selectedCenterLineSegment = feature.get("segment_id"); selectedLaneSeparator = null; setMarkingStyleForm("道路中心线样式", `道路段:${selectedCenterLineSegment}`, feature.get("effective_style"), true); }
function selectLaneSeparator(feature) { selectedCenterLineSegment = null; selectedLaneSeparator = feature.getProperties(); setMarkingStyleForm("车道分隔线样式", `第 ${selectedLaneSeparator.left_lane_index} 与第 ${selectedLaneSeparator.right_lane_index} 车道之间`, selectedLaneSeparator.effective_style || "white-dashed", false); }
function selectEdgeLine(feature) { selectedCenterLineSegment = null; selectedLaneSeparator = null; selectedEdgeLine = feature.getProperties(); setMarkingStyleForm("道路外缘线样式", `${selectedEdgeLine.side === "left" ? "左" : "右"}侧外缘`, selectedEdgeLine.effective_style || "white-solid", false); }
function clearCenterLineSelection() { selectedCenterLineSegment = null; selectedLaneSeparator = null; selectedEdgeLine = null; centerLineForm.hidden = true; }
function stageCenterLineStyle(segmentId, style) { const parts = style.split("-"); const double = parts[0] === "double"; const [color, pattern] = double ? parts.slice(1) : parts; const id = `道路中心线:${segmentId}`; const existing = staged.find((item) => item.id === id) || state.overrides.overrides.find((item) => item.id === id); staged = staged.filter((item) => item.id !== id); staged.push({ ...existing, id, kind: "center-line-style", segmentId, color, pattern, double }); }
form.onsubmit = (event) => { event.preventDefault(); const roadChanges = { widthMeters: Number(widthInput.value), laneCount: Number(lanesInput.value), sidewalkLeft: leftInput.checked, sidewalkRight: rightInput.checked }; stageRoadOverride(selectedRoad, roadChanges); const opposite = state.compiled.model.roads.find((road) => road.id !== selectedRoad.id && road.segmentId === selectedRoad.segmentId); if (opposite) stageRoadOverride(opposite, { sidewalkLeft: rightInput.checked, sidewalkRight: leftInput.checked }); updateDirtyState(); message(opposite ? "有未保存修改:双向道路的路缘与步行带已按实际侧边同步" : "有未保存修改"); };
function stageSelectedCenterLineStyle() { if (!selectedCenterLineSegment && !selectedLaneSeparator && !selectedEdgeLine) return; if (selectedCenterLineSegment) stageCenterLineStyle(selectedCenterLineSegment, centerLineStyleInput.value); else { const [color, pattern] = centerLineStyleInput.value.split("-"); const item = selectedLaneSeparator || selectedEdgeLine; const id = selectedLaneSeparator ? `车道分隔线:${item.road_id}:${item.left_lane_index}-${item.right_lane_index}` : `道路外缘线:${item.road_id}:${item.side}`; staged = staged.filter((change) => change.id !== id); staged.push(selectedLaneSeparator ? { id, kind: "lane-separator-style", roadId: item.road_id, leftLaneIndex: item.left_lane_index, rightLaneIndex: item.right_lane_index, color, pattern } : { id, kind: "edge-line-style", roadId: item.road_id, side: item.side, color, pattern }); } updateDirtyState(); message("有未保存修改:线样式"); }
centerLineForm.onsubmit = (event) => { event.preventDefault(); stageSelectedCenterLineStyle(); };
centerLineStyleInput.onchange = stageSelectedCenterLineStyle;
async function saveStagedChanges() { if (!staged.length) return true; const existing = state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)); const response = await fetch("/api/overrides", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ schema: "native-road-overrides/v1", overrides: [...existing, ...staged] }) }); const result = await response.json(); if (!result.ok) { message(result.error); return false; } state.overrides = result.overrides; staged = []; updateDirtyState(); return true; }
saveButton.onclick = async () => { if (await saveStagedChanges()) message("已保存,点击“保存并重新生成”写入几何"); };
compileButton.onclick = async () => {
if (!await saveStagedChanges()) return;
message("正在保存修改并重新生成...");
const response = await fetch("/api/compile", { method: "POST", cache: "no-store" });
const nextState = await response.json();
if (!response.ok || nextState.ok === false || !nextState.compiled?.model || !nextState.layers) {
message(`重新生成失败:${nextState.error || `HTTP ${response.status}`}`);
return;
}
state = nextState;
staged = [];
updateDirtyState();
updateSources();
renderDiagnostics();
renderSummary();
selectRoad(selectedRoad ? state.compiled.model.roads.find((road) => road.id === selectedRoad.id) : null);
message("已保存并重新生成");
};
for (const input of document.querySelectorAll("[data-layer]")) input.onchange = () => { const visible = input.checked; layers[input.dataset.layer].setVisible(visible); if (input.dataset.layer === "osm") layers.osmDirection.setVisible(visible); };
scenePreviewToggle.onchange = () => {
scenePreview = scenePreviewToggle.checked;
for (const input of document.querySelectorAll("[data-layer]")) {
const layer = input.dataset.layer;
if (["osm", "lanes", "reference", "gaodeReference"].includes(layer)) layers[layer].setVisible(!scenePreview && input.checked);
}
layers.osmDirection.setVisible(!scenePreview && document.querySelector('[data-layer="osm"]').checked);
layers.connectors.setVisible(!scenePreview && document.querySelector('[data-layer="lanes"]').checked);
layers.sidewalks.setVisible(document.querySelector('[data-layer="sidewalks"]').checked);
layers.centerLines.setVisible(document.querySelector('[data-layer="centerLines"]').checked);
layers.controls.setVisible(document.querySelector('[data-layer="controls"]').checked);
const signalsVisible = document.querySelector('[data-layer="signals"]').checked;
layers.signals.setVisible(signalsVisible);
layers.diagnostics.setVisible(!scenePreview);
layers.native.changed(); layers.sidewalks.changed();
message(scenePreview ? "场景效果预览:当前编译面" : "编辑图层预览");
};
for (const button of diagnosticFilters.querySelectorAll("button")) button.onclick = () => { diagnosticFilter = button.dataset.diagnosticFilter; renderDiagnostics(); };
fetch("/api/state").then((response) => response.json()).then((value) => { state = value; updateDirtyState(); updateSources(); renderDiagnostics(); renderSummary(); areaLabel.textContent = state.areaId; const signalUid = new URLSearchParams(location.search).get("signal"); const signal = signalUid && poleFeatureForSignal(signalUid); if (signal) selectSignal(signal); message(`已加载 ${state.compiled.model.roads.length} 条方向道路`); }).catch((error) => message(error.message));
-4
View File
@@ -1,4 +0,0 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>道路编译工作台</title><link rel="stylesheet" href="/vendor/ol/ol.css"><link rel="stylesheet" href="/app.css"></head>
<body><header><strong>道路编译工作台</strong><span id="area"></span><span id="status"></span><span id="dirty-state" aria-live="polite"></span><label style="display:inline;margin:0 0 0 auto;white-space:nowrap"><input id="scene-preview" type="checkbox"> 场景效果</label><button id="save">保存修改</button><button id="compile">保存并重新生成</button></header>
<main><aside class="issues"><h1>图层</h1><label><input data-layer="osm" type="checkbox" checked> OSM 道路中心线</label><label><input data-layer="native" type="checkbox" checked> 自研道路与路口面</label><label><input data-layer="sidewalks" type="checkbox" checked> 路缘与步行带</label><label><input data-layer="lanes" type="checkbox" checked> 车道与转向路径</label><label><input data-layer="gaodeReference" type="checkbox" checked> 高德规整路口参考</label><label><input data-layer="reference" type="checkbox"> osm2streets 参考面</label><hr><h1>当前编译概览</h1><dl id="summary"></dl><hr><h1>待检查问题</h1><div id="diagnostic-filters" class="segmented"><button data-diagnostic-filter="all" type="button">全部</button><button data-diagnostic-filter="candidates" type="button">可连接</button><button data-diagnostic-filter="other" type="button">其他</button></div><ul id="diagnostics"></ul></aside><section id="map" class="map"></section><aside class="inspector"><h1>当前道路设置</h1><p id="hint">点击道路、车道、转向路径或路口面以查看详情。</p><section id="selected-junction" hidden><h2>当前路口</h2><output id="junction-detail"></output></section><form id="road-form" hidden><label>道路</label><output id="road-name"></output><output id="movement-summary"></output><output id="lane-convention"></output><section id="selected-movement" hidden><h2>当前行驶动作</h2><output id="movement-detail"></output></section><div id="direction-switch"></div><label>本方向道路宽度(米)<input id="width" type="number" min="1" step="0.01"></label><label>本方向车道数<input id="lanes" type="number" min="1" step="1"></label><label><input id="left" type="checkbox"> 左侧有路缘与步行带</label><label><input id="right" type="checkbox"> 右侧有路缘与步行带</label><button type="submit">暂存本道路修改</button></form><form id="center-line-form" hidden><h2 id="marking-style-heading">道路中心线样式</h2><output id="center-line-segment"></output><label>样式<select id="center-line-style"><option value="yellow-dashed">黄色虚线(默认)</option><option value="white-dashed">白色虚线</option><option value="yellow-solid">黄色实线</option><option value="white-solid">白色实线</option></select></label><button type="submit">暂存标线样式</button></form><hr><h2>路口连接</h2><div id="connections">请选择一条道路。</div><button id="add-connection" type="button" hidden>手工新增驶出连接</button><details><summary>技术详情与来源</summary><pre id="evidence">无</pre></details></aside></main><script type="importmap">{"imports":{"rbush":"/vendor/rbush/index.js","quickselect":"/vendor/quickselect/index.js"}}</script><script type="module" src="/app.js"></script></body></html>
-152
View File
@@ -1,152 +0,0 @@
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const http = require("http");
const path = require("path");
const { loadOverrides, validateOverrides, writeJsonAtomic } = require("../src/compile/native-road");
const { generate, validateDocument, runtime } = require("../src/native-traffic-signals");
const { convertGeoJson } = require("../src/reference/gaode");
function startWorkbench({ area, configPath, repoRoot, compileFresh, readAreaConfig, junctionReference = null, debug = false, port = 8787 }) {
if (typeof junctionReference === "string") junctionReference = readJunctionReference(junctionReference);
// `--debug` surfaces advisory compiler findings that have no geometry layer of
// their own — currently the complex-junction candidates. Off by default so the
// normal editing view stays uncluttered.
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("--port must be an integer in [1024, 65535].");
const context = { repoRoot, configPath, compileFresh, readAreaConfig };
const server = http.createServer((request, response) => handle(request, response, area, context, junctionReference, debug));
server.on("error", (error) => {
console.error(`Road Workbench failed to listen: ${error.message}`);
process.exitCode = 1;
});
server.listen(port, "127.0.0.1", () => console.log(`Road Workbench: http://127.0.0.1:${port}/${debug ? " (debug: 复杂路口候选已开启)" : ""}`));
return server;
}
function handle(request, response, area, context, junctionReference, debug = false) {
const url = new URL(request.url, "http://127.0.0.1");
if (request.method === "GET" && url.pathname === "/") return sendFile(response, path.join(__dirname, "client", "index.html"), "text/html; charset=utf-8");
if (request.method === "GET" && url.pathname === "/app.js") return sendFile(response, path.join(__dirname, "client", "app.js"), "text/javascript; charset=utf-8");
if (request.method === "GET" && url.pathname === "/app.css") return sendFile(response, path.join(__dirname, "client", "app.css"), "text/css; charset=utf-8");
if (request.method === "GET" && url.pathname.startsWith("/vendor/")) return sendVendorFile(response, url.pathname, context.repoRoot);
if (request.method === "GET" && url.pathname === "/api/state") return sendJson(response, 200, state(area, junctionReference, debug));
if (request.method === "POST" && url.pathname === "/api/traffic-signals") return readBody(request).then((body) => {
const document = validateDocument(body, fs.readFileSync(area.input, "utf8"));
writeJsonAtomic(area.outputs.nativeTrafficSignals, document);
sendJson(response, 200, { ok: true, trafficSignals: document, runtime: runtime(document) });
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
if (request.method === "POST" && url.pathname === "/api/traffic-signals/generate") return Promise.resolve().then(() => {
const compiled = readCompiled(area);
const generated = generate(fs.readFileSync(area.input, "utf8"), readLayer(path.join(area.outputs.nativeRoadDir, "layers", "vehicle_stop_lines.geojson")), readLayer(path.join(area.outputs.nativeRoadDir, "layers", "intersection_surface.geojson")));
const current = validateDocument(readJson(area.outputs.nativeTrafficSignals), fs.readFileSync(area.input, "utf8"));
const present = new Set(current.assemblies.features.map((feature) => feature.properties.signal_uid));
current.assemblies.features.push(...generated.assemblies.features.filter((feature) => !present.has(feature.properties.signal_uid)));
writeJsonAtomic(area.outputs.nativeTrafficSignals, current);
sendJson(response, 200, { ok: true, trafficSignals: current, runtime: runtime(current), generated: generated.assemblies.features.length, compiled: Boolean(compiled) });
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
if (request.method === "POST" && url.pathname === "/api/overrides") return readBody(request).then((body) => {
const compiled = readCompiled(area);
const overrides = validateOverrides(body, { roads: compiled.model.roads, endpoints: compiled.model.endpoints });
writeJsonAtomic(area.outputs.nativeRoadOverrides, overrides);
sendJson(response, 200, { ok: true, overrides });
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
if (request.method === "POST" && url.pathname === "/api/junction-clusters") return readBody(request).then((body) => {
if (!debug) throw new Error("该接口仅在 --debug 模式下可用。");
const added = addJunctionCluster(context.configPath, body, readCompiled(area), context.readAreaConfig, context.repoRoot);
context.compileFresh();
const refreshed = context.readAreaConfig(context.configPath, { repoRoot: context.repoRoot });
sendJson(response, 200, { ok: true, added, ...state(refreshed, junctionReference, debug) });
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
if (request.method === "POST" && url.pathname === "/api/compile") return Promise.resolve().then(() => {
context.compileFresh();
sendJson(response, 200, state(area, junctionReference));
}).catch((error) => sendJson(response, 500, { ok: false, error: error.message }));
sendJson(response, 404, { error: "Not found" });
}
function state(area, junctionReference = null, debug = false) {
const nativeDir = area.outputs.nativeRoadDir;
const osm2streetsRoadSurface = path.join(area.outputs.geojsonDir, "road_surface.geojson");
const trafficSignals = fs.existsSync(area.outputs.nativeTrafficSignals)
? validateDocument(readJson(area.outputs.nativeTrafficSignals), fs.readFileSync(area.input, "utf8"))
: { schema: "native-traffic-signals/v1", provenance: "empty", assemblies: { type: "FeatureCollection", features: [] } };
const trafficRuntime = runtime(trafficSignals);
const compiled = readCompiled(area);
return { areaId: area.id, debug: debug ? { junctionCandidates: junctionCandidates(compiled) } : null, compiled, overrides: loadOverrides(area.outputs.nativeRoadOverrides), trafficSignals, trafficRuntime, comparison: readJson(path.join(nativeDir, "comparison.json")), junctionReference, layers: { nativeRoadSurface: readLayer(path.join(nativeDir, "layers", "road_surface.geojson")), edgeLines: readLayer(path.join(nativeDir, "layers", "edge_lines.geojson")), nativeSidewalkSurface: readLayer(path.join(nativeDir, "layers", "sidewalk_surface.geojson")), nativeIntersectionSurface: readLayer(path.join(nativeDir, "layers", "intersection_surface.geojson")), laneCenterlines: readLayer(path.join(nativeDir, "layers", "lane_centerlines.geojson")), laneSeparators: readLayer(path.join(nativeDir, "layers", "lane_separators.geojson")), centerLines: readLayer(path.join(nativeDir, "layers", "center_lines.geojson")), directionArrows: readLayer(path.join(nativeDir, "layers", "direction_arrows.geojson")), turnArrows: readLayer(path.join(nativeDir, "layers", "turn_arrows.geojson")), crosswalks: readLayer(path.join(nativeDir, "layers", "crosswalks.geojson")), vehicleStopLines: readLayer(path.join(nativeDir, "layers", "vehicle_stop_lines.geojson")), connectors: readLayer(path.join(nativeDir, "layers", "connectors.geojson")), osm2streetsRoadSurface: fs.existsSync(osm2streetsRoadSurface) ? readLayer(osm2streetsRoadSurface) : null } };
}
// The compiler reports candidates as advisory diagnostics. Lift them into their
// own payload with a stable index so the map can label them "#1, #2, ..." and
// the inspector can offer a ready-to-paste cluster配置.
// Append one detected cluster to the hand-authored area config. The candidate
// must still be present in the latest compile, so a stale browser tab cannot
// write a cluster that no longer exists. The edited config is validated by the
// real loader before it replaces the file: an invalid write would break every
// later command, and the file is git-tracked so a bad accept stays revertible.
function addJunctionCluster(configPath, body, compiled, readAreaConfig, repoRoot) {
const index = Number(body?.index);
if (!Number.isInteger(index)) throw new Error("请求缺少候选编号 index。");
const candidate = junctionCandidates(compiled).find((item) => item.index === index);
if (!candidate) throw new Error(`候选 #${index} 不在最新一次编译结果里,请刷新页面后重试。`);
const raw = readJson(configPath);
const templates = raw.nativeRoad?.junctionTemplates;
if (!templates) throw new Error("区域配置缺少 nativeRoad.junctionTemplates,请先手工建立该节点。");
const clusters = Array.isArray(templates.clusters) ? templates.clusters : [];
const taken = new Set(clusters.flatMap((cluster) => (cluster.nodeIds || []).map(String)));
const clash = candidate.nodeIds.filter((nodeId) => taken.has(String(nodeId)));
if (clash.length) throw new Error(`节点 ${clash.join("、")} 已属于其他复杂路口配置。`);
const id = uniqueClusterId(`cluster-${candidate.nodeIds[0]}`, new Set(clusters.map((cluster) => cluster.id)));
const cluster = {
id,
template: candidate.template,
coreRadiusMeters: candidate.coreRadiusMeters,
cornerRadiusMeters: 12,
outerRadiusExtraMeters: 18,
nodeIds: candidate.nodeIds.map(String),
};
const next = { ...raw, nativeRoad: { ...raw.nativeRoad, junctionTemplates: { ...templates, enabled: true, clusters: [...clusters, cluster] } } };
const staging = `${configPath}.candidate-${process.pid}.json`;
fs.writeFileSync(staging, `${JSON.stringify(next, null, 2)}\n`);
try {
readAreaConfig(staging, { repoRoot });
} catch (error) {
fs.unlinkSync(staging);
throw new Error(`写入后的配置无法通过校验,已放弃:${error.message}`);
}
fs.unlinkSync(staging);
writeJsonAtomic(configPath, next);
return cluster;
}
function uniqueClusterId(base, taken) {
if (!taken.has(base)) return base;
for (let suffix = 2; suffix < 100; suffix += 1) if (!taken.has(`${base}-${suffix}`)) return `${base}-${suffix}`;
throw new Error("无法生成唯一的 cluster id。");
}
function junctionCandidates(compiled) {
return (compiled?.diagnostics || [])
.filter((item) => item.rule === "complex-junction-candidate" && item.suggestedCluster)
.sort((first, second) => second.suggestedCluster.nodeCount - first.suggestedCluster.nodeCount || first.suggestedCluster.diameterMeters - second.suggestedCluster.diameterMeters)
.map((item, index) => ({ index: index + 1, id: item.id, message: item.message, coordinate: item.geometry?.coordinates || null, ...item.suggestedCluster }));
}
function readJunctionReference(file) {
if (!fs.existsSync(file)) throw new Error(`Junction reference not found: ${file}`);
const converted = convertGeoJson(JSON.parse(fs.readFileSync(file, "utf8")));
return { source: file, coordinateSystem: "GCJ-02", converted };
}
function readCompiled(area) { return readJson(path.join(area.outputs.nativeRoadDir, "compiled.json")); }
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
function readLayer(file) { return fs.existsSync(file) ? readJson(file) : { type: "FeatureCollection", features: [] }; }
function readBody(request) { return new Promise((resolve, reject) => { let body = ""; request.setEncoding("utf8"); request.on("data", (part) => { body += part; if (body.length > 1024 * 1024) request.destroy(); }); request.on("end", () => { try { resolve(JSON.parse(body)); } catch (_) { reject(new Error("Request body must be JSON.")); } }); request.on("error", reject); }); }
function sendFile(response, file, type) { response.writeHead(200, { "Content-Type": type, "Cache-Control": "no-store" }); fs.createReadStream(file).pipe(response); }
function sendVendorFile(response, pathname, repoRoot) {
const match = /^\/vendor\/(ol|rbush|quickselect)\/(.+)$/.exec(pathname);
if (!match) return sendJson(response, 404, { error: "Not found" });
const root = path.join(repoRoot, "node_modules", match[1]);
const file = path.resolve(root, match[2]);
if (!file.startsWith(`${root}${path.sep}`) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return sendJson(response, 404, { error: "Not found" });
return sendFile(response, file, file.endsWith(".css") ? "text/css; charset=utf-8" : "text/javascript; charset=utf-8");
}
function sendJson(response, status, value) { response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }); response.end(`${JSON.stringify(value)}\n`); }
module.exports = { startWorkbench };