Skip to content

Commit 27e123e

Browse files
committed
feat: 字体碰撞网格改用 poly-decomp-es 凸分解,替换 earcut 三角网格
- 每个字形轮廓按子轮廓独立凹分解为凸多边形,挂为共享固定刚体上的 compound convexHull 碰撞体,实心碰撞替代零厚度三角面,方块不易穿模 - 孔洞子轮廓同样参与分解(区域视为实心),与旧方案的实际行为一致 - 移除 earcut 依赖 - 删除从未被消费的预留字段 textTriangles 及其世界坐标收集逻辑 - 同步 README 中文字体说明的措辞
1 parent f1f51ef commit 27e123e

7 files changed

Lines changed: 74 additions & 75 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,10 @@ that point.
119119

120120
`font-path` swaps the collision font. It accepts a local `.ttf`/`.otf` path or an `http(s)` URL.
121121
The bundled Liberation Serif Bold is used by default because its contours are clean and
122-
reliably triangulated. Custom fonts are risky:
122+
decompose stably. Custom fonts are not guaranteed to work:
123123

124-
- Contours that are not closed or that self-intersect are silently tolerated by most
125-
renderers, but the triangulation used for the physics collider rejects them.
124+
- Fonts with irregular contours (open or self-intersecting) may decompose into unreliable
125+
collision shapes.
126126
- Some fonts cannot be parsed by opentype.js at all (common ones such as DejaVu fail on their
127127
GSUB tables).
128128
- Different font metrics usually require re-tuning `font-size` and `text-top`.

‎README_zh.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,9 @@ web preview 里验证。值中不能包含花括号、分号或 `]]>`。
108108
限制模拟时长,仍能拿到该时刻为止的轨迹。
109109

110110
`font-path` 用于替换碰撞字体,可以给本地 `.ttf`/`.otf` 路径,也可以直接给 `http(s)` 链接。
111-
默认使用内置的 Liberation Serif Bold,因为它轮廓规整、能稳定三角化。自定义字体有风险:
111+
默认使用内置的 Liberation Serif Bold,因为它轮廓规整、分解结果稳定。自定义字体不保证可用:
112112

113-
- 未闭合或自相交的轮廓,大多数渲染器会静默忽略,但物理碰撞体使用的三角化算法会直接报错。
113+
- 轮廓不规整(未闭合、自相交等)的字体,碰撞体的分解结果可能不可靠、形状异常。
114114
- 部分字体根本无法被 opentype.js 解析(例如很常见的 DejaVu 系列,会因 GSUB 表解析失败)。
115115
- 字体度量不同,通常需要重新调整 `font-size` 和 `text-top`。
116116

‎__tests__/parseTextPath.test.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,19 +69,18 @@ describe('getTextPaths', () => {
6969
)
7070
})
7171

72-
it('emits path data, a bounding box and a triangulated mesh per glyph', async () => {
72+
it('emits path data, a bounding box and a convex mesh per glyph', async () => {
7373
const [glyph] = await getTextPaths('H', 40, DEFAULT_OPTIONS.font)
7474

7575
expect(glyph.pathData.startsWith('M')).toBe(true)
7676
expect(glyph.rect.width).toBeGreaterThan(0)
7777
expect(glyph.rect.height).toBeGreaterThan(0)
7878

79-
// 三角网格与同一份轮廓一一对应:索引按三元组组织,且不越界
80-
const vertexCount = glyph.paths.vertices.length / 2
81-
const indices = Array.from(glyph.paths.indices)
82-
expect(vertexCount).toBeGreaterThan(0)
83-
expect(indices.length % 3).toBe(0)
84-
expect(Math.max(...indices)).toBeLessThan(vertexCount)
79+
// 凸网格与同一份轮廓对应:每个凸块都是至少三个顶点的多边形
80+
expect(glyph.paths.polygons.length).toBeGreaterThan(0)
81+
for (const polygon of glyph.paths.polygons) {
82+
expect(polygon.length).toBeGreaterThanOrEqual(3)
83+
}
8584
})
8685

8786
it('returns one entry per glyph and scales with font size', async () => {

‎bun.lock‎

Lines changed: 3 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@
4949
"@actions/core": "^3.0.0",
5050
"@dimforge/rapier2d": "^0.19.3",
5151
"@dimforge/rapier2d-compat": "^0.19.3",
52-
"earcut": "^3.2.3",
5352
"opentype.js": "^2.0.0",
54-
"points-on-path": "^0.2.1"
53+
"points-on-path": "^0.2.1",
54+
"poly-decomp-es": "^0.4.2"
5555
},
5656
"devDependencies": {
5757
"@biomejs/biome": "2.5.4",

‎src/utils/parseTextPath.ts‎

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,40 @@
1-
import earcut from 'earcut'
21
import * as opentype from 'opentype.js'
32
import { pointsOnPath } from 'points-on-path'
3+
import type { Point, Polygon } from 'poly-decomp-es'
4+
import {
5+
makeCCW,
6+
quickDecomp,
7+
removeCollinearPoints,
8+
removeDuplicatePoints
9+
} from 'poly-decomp-es'
410
import { SCALE } from '../const'
511
import type { TextPathResult } from './physics'
612

7-
function svgPathToRapierTrimesh(path: string, scale = 1, tolerance = 1) {
13+
/**
14+
* 把 SVG path 的每个子轮廓独立凹分解为凸多边形集合(顶点已按 scale 缩放)。
15+
* 子轮廓之间互相独立处理:孔洞轮廓同样参与分解,即孔洞区域被视为实心
16+
*/
17+
function svgPathToConvexPolygons(
18+
path: string,
19+
scale = 1,
20+
tolerance = 1
21+
): Polygon[] {
822
const subPaths = pointsOnPath(path, tolerance)
9-
const points = subPaths.flat()
10-
11-
const vertices = points.map(
12-
([x, y]) => [x * scale, y * scale] as [number, number]
13-
)
1423

15-
const flatVertices = vertices.flat()
16-
17-
const indices = earcut(flatVertices)
18-
19-
return {
20-
vertices: new Float32Array(flatVertices),
21-
indices: new Uint32Array(indices)
24+
const polygons: Polygon[] = []
25+
for (const subPath of subPaths) {
26+
// 采样点可能含重复点与共线点,会让分解产生退化凸块,先清理
27+
const polygon: Point[] = subPath.map(
28+
([x, y]) => [x * scale, y * scale] as Point
29+
)
30+
removeDuplicatePoints(polygon, 0.01)
31+
removeCollinearPoints(polygon, 0.01)
32+
// 清理后不足 3 点的轮廓构不成多边形
33+
if (polygon.length < 3) continue
34+
makeCCW(polygon)
35+
polygons.push(...quickDecomp(polygon))
2236
}
37+
return polygons
2338
}
2439

2540
/** 字体数据来源:本地路径、远程 URL(字符串或 URL 对象),或已读取好的字体数据 */
@@ -102,7 +117,7 @@ async function resolveFontData(font: FontSource): Promise<ArrayBuffer> {
102117
}
103118

104119
/**
105-
* 解析文字为可渲染的轮廓路径,同时产出 SVG 用的 pathData 与物理用的三角网格。
120+
* 解析文字为可渲染的轮廓路径,同时产出 SVG 用的 pathData 与物理用的凸多边形网格。
106121
*
107122
* @param font 字体来源(.ttf/.otf):本地路径、URL、URL 字符串,或
108123
* Buffer / ArrayBuffer(如 `files[0].arrayBuffer()` 的结果);省略时用内置字体
@@ -143,20 +158,19 @@ export async function getTextPaths(
143158
const bbox = path.getBoundingBox()
144159
const pathData = path.toPathData(2)
145160

146-
let triangulated: ReturnType<typeof svgPathToRapierTrimesh>
161+
let decomposed: Polygon[]
147162
try {
148-
triangulated = svgPathToRapierTrimesh(pathData)
163+
decomposed = svgPathToConvexPolygons(pathData)
149164
} catch (error) {
165+
// 防御性包装:上游分解几乎不抛错,抛出时也带上字体来源便于定位
150166
throw new Error(
151-
`Failed to triangulate a glyph from font "${describeFont(font)}". ` +
152-
'Some fonts contain open or self-intersecting contours that the ' +
153-
'triangulation algorithm cannot handle.',
167+
`Failed to decompose a glyph from font "${describeFont(font)}"`,
154168
{ cause: error }
155169
)
156170
}
157171

158172
return {
159-
paths: triangulated,
173+
paths: { polygons: decomposed },
160174
pathData: pathData,
161175
rect: {
162176
x: bbox.x1,

‎src/utils/physics.ts‎

Lines changed: 23 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
RigidBodyDesc,
66
World
77
} from '@dimforge/rapier2d-compat'
8+
import type { Polygon } from 'poly-decomp-es'
89
import {
910
DEFAULT_OPTIONS,
1011
FRICTION,
@@ -147,8 +148,8 @@ async function createWord(width: number, height: number) {
147148

148149
export interface TextPathResult {
149150
paths: {
150-
vertices: Float32Array
151-
indices: Uint32Array
151+
/** 字形子轮廓凹分解出的凸多边形集合(字形局部坐标,y 轴向下) */
152+
polygons: Polygon[]
152153
}
153154
pathData: string
154155
rect: {
@@ -217,8 +218,6 @@ export interface SimulationResult {
217218
time: number
218219
textPaths: Pick<TextPathResult, 'rect' | 'pathData'>[]
219220
contributions: ContributionJson[]
220-
/** 用户名文字碰撞体的三角网格(世界坐标),用于 web 端渲染 */
221-
textTriangles: number[][]
222221
/** 文字在物理世界中的 X 偏移量 */
223222
offsetX: number
224223
/** 文字在物理世界中的 Y 偏移量 */
@@ -277,8 +276,8 @@ export interface SimulationOptions {
277276
* 自定义字体(.ttf/.otf):本地路径、远程 URL(字符串或 URL 对象),或
278277
* 已读取好的 Buffer / ArrayBuffer(如 `files[0].arrayBuffer()` 的结果),
279278
* 默认使用内置的 Liberation Serif Bold。
280-
* 谨慎修改:部分字体存在未闭合或自相交的轮廓,操作系统渲染时会自动忽略这些瑕疵,
281-
* 但本项目的轮廓三角化算法会直接报错;另有部分字体因 opentype.js 的 GSUB 解析限制无法使用。
279+
* 谨慎修改:轮廓不规整(未闭合、自相交等)的字体,分解出的碰撞形状可能不可靠;
280+
* 另有部分字体因 opentype.js 的 GSUB 解析限制无法使用。
282281
* 字体度量差异也可能导致文字位置和碰撞形态需要重新调整
283282
*/
284283
font?: FontSource
@@ -290,8 +289,6 @@ export interface SimulationWorld {
290289
/** 贡献方块(含轨迹记录器),每步迭代后调用 update 采集轨迹 */
291290
contributions: Contribution[]
292291
textPaths: TextPathResult[]
293-
/** 文字碰撞体的三角网格(世界坐标),用于 web 端渲染 */
294-
textTriangles: number[][]
295292
/** 文字在物理世界中的 X 偏移量 */
296293
offsetX: number
297294
/** 文字在物理世界中的 Y 偏移量 */
@@ -321,7 +318,7 @@ export async function createSimulationWorld(
321318
const world = await createWord(width, height)
322319
const contributions: Contribution[] = []
323320

324-
// 创建用户名文字静止刚体(居中对齐),同时收集三角网格数据
321+
// 创建用户名文字静止碰撞体(居中对齐)
325322
const textPaths = await getTextPaths(text, fontSize, font)
326323

327324
const { centerY, offsetX } = getTextBoundBox(textPaths, {
@@ -330,35 +327,24 @@ export async function createSimulationWorld(
330327
textTop
331328
})
332329

333-
const textTriangles: number[][] = []
334-
335330
for (const { paths } of textPaths) {
336-
const { vertices, indices } = paths
337-
if (!vertices.length && !indices.length) continue
338-
// 翻转 Y 轴:opentype 字形在基线下方(y 为负),物理世界需要正向
339-
const flippedVertices = new Float32Array(vertices.length)
340-
for (let i = 0; i < vertices.length; i += 2) {
341-
flippedVertices[i] = vertices[i]
342-
flippedVertices[i + 1] = -vertices[i + 1]
343-
}
344-
world.createCollider(
345-
ColliderDesc.trimesh(flippedVertices, indices).setFriction(FRICTION),
346-
world.createRigidBody(
347-
RigidBodyDesc.fixed().setTranslation(offsetX, centerY)
348-
)
331+
const { polygons } = paths
332+
if (!polygons.length) continue
333+
// 同一字形的全部凸块挂在共享的静止刚体上,作为 compound collider 参与碰撞
334+
const textBody = world.createRigidBody(
335+
RigidBodyDesc.fixed().setTranslation(offsetX, centerY)
349336
)
350-
for (let i = 0; i < indices.length; i += 3) {
351-
const i0 = indices[i] * 2,
352-
i1 = indices[i + 1] * 2,
353-
i2 = indices[i + 2] * 2
354-
textTriangles.push([
355-
offsetX + flippedVertices[i0],
356-
centerY + flippedVertices[i0 + 1],
357-
offsetX + flippedVertices[i1],
358-
centerY + flippedVertices[i1 + 1],
359-
offsetX + flippedVertices[i2],
360-
centerY + flippedVertices[i2 + 1]
361-
])
337+
for (const polygon of polygons) {
338+
// 翻转 Y 轴:opentype 字形在基线下方(y 为负),物理世界需要正向
339+
const flippedVertices = new Float32Array(polygon.length * 2)
340+
for (let i = 0; i < polygon.length; i++) {
341+
flippedVertices[i * 2] = polygon[i][0]
342+
flippedVertices[i * 2 + 1] = -polygon[i][1]
343+
}
344+
// 顶点近乎共线的退化凸块求不出凸包,跳过
345+
const colliderDesc = ColliderDesc.convexHull(flippedVertices)
346+
if (!colliderDesc) continue
347+
world.createCollider(colliderDesc.setFriction(FRICTION), textBody)
362348
}
363349
}
364350

@@ -413,7 +399,6 @@ export async function createSimulationWorld(
413399
world,
414400
contributions,
415401
textPaths,
416-
textTriangles,
417402
offsetX,
418403
centerY
419404
}
@@ -430,7 +415,7 @@ export async function startSimulation(
430415
maxSimulationTime,
431416
speed
432417
} = withDefaults(DEFAULT_OPTIONS, options)
433-
const { world, contributions, textPaths, textTriangles, offsetX, centerY } =
418+
const { world, contributions, textPaths, offsetX, centerY } =
434419
await createSimulationWorld(options)
435420

436421
// 容差从 SVG 像素换算回物理坐标单位,让压缩函数与渲染缩放解耦;
@@ -504,7 +489,6 @@ export async function startSimulation(
504489
pathData: pathData,
505490
rect: rect
506491
})),
507-
textTriangles,
508492
offsetX,
509493
centerY
510494
}

0 commit comments

Comments
 (0)