A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): Hair cards draw a soft blended tip pass below their cutoff
yhhf99986afd1a6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7f9b450a..fd2964948 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,7 @@ published separately; it ships inside the editor.- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.+- **Hair tips.** The Hair shader can draw the soft outer band of its cards: `u_tipSoftness` is how far below the cutoff alpha a second, blended pass draws each strand's tip fading out, sorted with the other blended draws, so tips are not stair-stepped by coverage. A model imported with Character Materials also has its hair triangles put in the order that pass wants, the cards nearest the middle of the hair first. Off by default.- **Character materials on import.** Importing a model can now give its character materials the right shader: turn on Character Materials in the model's import settings and a material whose name says skin, face, head, hair or eye gets the Skin, Hair or Eye shader with its normal and occlusion/roughness maps bound, and hair is cut out by its alpha and feathered by coverage. Off by default.- **Curvature-shaped skin scattering.** The Skin shader can take its wrap past the terminator per colour and shape it by curvature: `u_preIntegrate` (red travels furthest, every colour further where the surface turns sharply) and `u_curvature`, so a nose or an ear glows at its edge while a flat cheek stays crisp. Off by default.- **Skin detail normal layer.** The Skin shader has a detail normal layer: `u_detailMap` is a fine normal map tiled over the surface (`u_detailTile`) for pores and creases, laid on the sharp normal the shine reads by `u_detailStrength` (0 leaves it out) and not on the soft diffuse normals.diff --git a/desktop b/desktopindex 50a6ccd99..c86231940 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 50a6ccd99bd77f2a799922439e69412f2319af16+Subproject commit c86231940cd41f6d214bf8b9e723fa92f92701b4diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdxindex 8ae17e544..c2948ae9a 100644--- a/docs/astro/src/content/docs/assets/models.mdx+++ b/docs/astro/src/content/docs/assets/models.mdx@@ -214,7 +214,7 @@ replaces them — a model told to occlude itself keeps doing so through its mate## Character materials-A model's materials import on the Model shader. Turn on **Character Materials** (`characterMaterials: auto`) in the model's import settings and a material whose name says skin, face, head, hair or eye gets the Skin, Hair or Eye shader instead, with its normal map and its occlusion/roughness map bound to them. A hair material is cut out by its alpha (`u_alphaCutoff`, 0.5 unless the source says otherwise) and drawn without blending, so its edges are feathered by coverage. The name is read word by word, so `BodySkin` and `Hair_A` match while `Eyelashes` and `Headband` do not, and the colour texture's file name counts too. A name is a convention, not a fact: look at what it chose in the materials the import writes, and change a shader by hand where it guessed wrong. Eyes need their iris maps (`u_depthMap`, `u_irisNormalMap`) assigned by hand, as the source has no slot for them. It is off by default, so re-importing never changes a material you did not ask about.+A model's materials import on the Model shader. Turn on **Character Materials** (`characterMaterials: auto`) in the model's import settings and a material whose name says skin, face, head, hair or eye gets the Skin, Hair or Eye shader instead, with its normal map and its occlusion/roughness map bound to them. The hair's triangles are also put in the order a blended draw wants, the cards nearest the middle of the hair first, which is back to front from any side for a shell of cards around a head (a ponytail that leaves the shell is not ordered by it). A hair material is cut out by its alpha (`u_alphaCutoff`, 0.5 unless the source says otherwise) and drawn without blending, so its edges are feathered by coverage. The name is read word by word, so `BodySkin` and `Hair_A` match while `Eyelashes` and `Headband` do not, and the colour texture's file name counts too. A name is a convention, not a fact: look at what it chose in the materials the import writes, and change a shader by hand where it guessed wrong. Eyes need their iris maps (`u_depthMap`, `u_irisNormalMap`) assigned by hand, as the source has no slot for them. It is off by default, so re-importing never changes a material you did not ask about.## Animationsdiff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdxindex 760b70d8e..9e7e32cdd 100644--- a/docs/astro/src/content/docs/graphics/materials.mdx+++ b/docs/astro/src/content/docs/graphics/materials.mdx@@ -84,7 +84,7 @@ texture), the diffuse light is Kajiya-Kay (a strand is lit by how far the lighthighlights along the strand, shifted against each other by `u_shiftMap` (`u_shiftAmount`, `u_shiftTile`): a white one near the surface and a colouredone under it (`u_secondaryTint`). `u_roughness` sets how tight the lines are. Light comes through the strands from behind (`u_translucency`),`u_sharpen` keeps the fine strands a card is covered in from washing out at a slant, and `u_rootDark` darkens the roots by the occlusion map.-`u_alphaCutoff` cuts a card out by its texture's alpha, feathered by alpha-to-coverage under MSAA, and the card then casts its own shape into shadow maps, not the rectangle it is drawn on. A hair model is usually cards or ribbons, not strands; this shader gives the shading of a strand to what the geometry gives it.+`u_alphaCutoff` cuts a card out by its texture's alpha, feathered by alpha-to-coverage under MSAA, and the card then casts its own shape into shadow maps. `u_tipSoftness` adds the soft outer band: where the alpha falls from the cutoff down by that much, a second blended pass draws the strand's tip fading out, sorted with the other blended draws, so tips do not stair-step under coverage (0 leaves it out). The card's own shape goes into shadow maps too, not the rectangle it is drawn on. A hair model is usually cards or ribbons, not strands; this shader gives the shading of a strand to what the geometry gives it.**Eye** (`builtin:eye`) builds an eye from two maps and a few numbers. `u_depthMap` is white over the iris and the dome of the cornea, and `u_irisNormalMap` holds that dome's normals (import both with sRGB off). The view ray is bent into the cornea (`u_ior`) and carried down to the iris (`u_irisDepth`), so the iris moves behind the surface as the eye turns. The iris itself is drawn from `u_irisColor` to `u_irisColor2` with fibres, a dark limbal ring (`u_limbal`) and a pupil (`u_pupilSize`), against the white (`u_scleraColor`), which is lit with light that wraps past the terminator (`u_scleraWrap`). The cornea is a near-mirror (`u_corneaRoughness`, `u_specular`), so every light and the sky show as a catchlight. The lids shade the eye: `u_lidMap` is an authored occlusion map (white where the eye is open), and `u_lidShadow` darkens, and fades the cornea's reflections, where the surface faces up (from `u_lidStart`, a dot with the world's up, to straight up), which is the upper lid on an upright head. A painted eye texture on the mesh multiplies the result.diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdxindex 63b2955a5..ba87bcab0 100644--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx@@ -185,7 +185,7 @@ chart,每片投影到自己的平面,再按**同一个**世界-纹素比打包## 角色材质-模型的材质默认导入到 Model 着色器。在模型的导入设置里打开**角色材质**(`characterMaterials: auto`)后,名字里带 skin、face、head、hair 或 eye 的材质会改用 Skin、Hair 或 Eye 着色器,并绑上它的法线贴图和遮蔽/粗糙度贴图。头发材质按 alpha 裁剪(`u_alphaCutoff`,源文件没说就取 0.5),并且不做混合绘制,边缘由覆盖率来柔化。名字是按单词读的,所以 `BodySkin`、`Hair_A` 会命中,`Eyelashes`、`Headband` 不会,颜色贴图的文件名也算。名字只是约定,不是事实:请看导入写出的材质选了什么,猜错的地方手动改着色器。眼睛的虹膜贴图(`u_depthMap`、`u_irisNormalMap`)需要手动指定,源文件里没有对应的位置。默认关闭,所以重新导入不会改动你没要求改的材质。+模型的材质默认导入到 Model 着色器。在模型的导入设置里打开**角色材质**(`characterMaterials: auto`)后,名字里带 skin、face、head、hair 或 eye 的材质会改用 Skin、Hair 或 Eye 着色器,并绑上它的法线贴图和遮蔽/粗糙度贴图。头发的三角形还会按混合绘制需要的顺序重排,最靠近头发中心的发片排在最前,对围绕头部的一圈发片来说,从任何一侧看这都是由后向前(离开这一圈的马尾不受这个排序约束)。头发材质按 alpha 裁剪(`u_alphaCutoff`,源文件没说就取 0.5),并且不做混合绘制,边缘由覆盖率来柔化。名字是按单词读的,所以 `BodySkin`、`Hair_A` 会命中,`Eyelashes`、`Headband` 不会,颜色贴图的文件名也算。名字只是约定,不是事实:请看导入写出的材质选了什么,猜错的地方手动改着色器。眼睛的虹膜贴图(`u_depthMap`、`u_irisNormalMap`)需要手动指定,源文件里没有对应的位置。默认关闭,所以重新导入不会改动你没要求改的材质。## 动画diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdxindex 0446bf4c1..e435bddc5 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx@@ -65,7 +65,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一**皮肤**(`builtin:skin`)不模糊画面。光进入皮肤又在不远处出来,会让弯曲表面的受光一侧变软,这里按颜色分开做:漫反射光取自比表面自己的法线更软的法线,红色最软(`u_blurRed`、`u_blurGreen`,是法线贴图的 mip 层级),所以毛孔和高光保持清晰。明暗交界线被染暖(`u_sssColor`、`u_sssWrap`),薄的或曲率大的地方会透光(`u_translucency`、`u_thinness`:耳朵、鼻翼、手指),高光是两层(`u_specular`、`u_lobe2`、`u_lobe2Roughness`),另有一层很淡的绒毛光照亮边缘(`u_fuzz`)。打开 `u_subsurface` 还会把它标记给[次表面散射](/docs/zh-cn/graphics/post-processing/#次表面散射)特效,在更大的尺度上扩散剩下的光,代价是会模糊画面。`u_preIntegrate` 让明暗交界线之后的环绕光按颜色分开(红色最远),并在表面急转的地方变宽,所以鼻翼和耳朵边缘会透出光,而平坦的脸颊保持清晰;`u_curvature` 是每个世界单位内多快的转折算作急转。`u_detailMap` 是平铺在表面上的第二张细法线图(`u_detailTile`),用来补烘焙贴图没有足够像素表现的毛孔和皮纹:它按 `u_detailStrength`(0 表示不用)叠在高光读取的锐利法线上,不叠在柔和的漫反射法线上。导入时关闭 sRGB,并把环绕方式设为重复。它对每个像素做三次光照计算,所以适合镜头里的角色皮肤,不适合一群人。-**头发**(`builtin:hair`)把发丝当发丝来打光。`u_flowMap` 说明发丝朝哪个方向(红、绿是贴图上的一个方向),漫反射是 Kajiya-Kay(发丝被光照亮的程度取决于光离它的走向有多远),高光是两条沿发丝的窄高光,由 `u_shiftMap` 把它们错开(`u_shiftAmount`、`u_shiftTile`):一条白的靠近表面,一条带颜色的在下面(`u_secondaryTint`)。`u_roughness` 决定线条有多紧。光会从发丝背面透过来(`u_translucency`),`u_sharpen` 让发片上密布的细发丝在斜着看时不被冲淡,`u_rootDark` 按遮蔽图把发根压暗。`u_alphaCutoff` 按贴图的 alpha 把发片抠出形状,在 MSAA 下由 alpha-to-coverage 柔化边缘,发片投进阴影图里的也是这个形状,而不是它所在的矩形。头发模型通常是发片或发带而不是真正的发丝;这个着色器把发丝的明暗给了几何本身给不了的部分。+**头发**(`builtin:hair`)把发丝当发丝来打光。`u_flowMap` 说明发丝朝哪个方向(红、绿是贴图上的一个方向),漫反射是 Kajiya-Kay(发丝被光照亮的程度取决于光离它的走向有多远),高光是两条沿发丝的窄高光,由 `u_shiftMap` 把它们错开(`u_shiftAmount`、`u_shiftTile`):一条白的靠近表面,一条带颜色的在下面(`u_secondaryTint`)。`u_roughness` 决定线条有多紧。光会从发丝背面透过来(`u_translucency`),`u_sharpen` 让发片上密布的细发丝在斜着看时不被冲淡,`u_rootDark` 按遮蔽图把发根压暗。`u_alphaCutoff` 按贴图的 alpha 把发片抠出形状,在 MSAA 下由 alpha-to-coverage 柔化边缘,`u_tipSoftness` 增加柔和的外缘:alpha 从裁剪值往下降这么多的范围内,由第二遍混合绘制把发丝尖端渐隐地画出来,和其他混合绘制一起排序,所以发梢不会在覆盖率下出现阶梯(0 表示不用)。发片投进阴影图里的也是这个形状,而不是它所在的矩形。头发模型通常是发片或发带而不是真正的发丝;这个着色器把发丝的明暗给了几何本身给不了的部分。**眼睛**(`builtin:eye`)用两张贴图和几个数值做出一只眼睛。`u_depthMap` 在虹膜和角膜穹顶上为白色,`u_irisNormalMap` 是这个穹顶的法线(两张都要以关闭 sRGB 的方式导入)。视线在角膜处折射(`u_ior`)再下行到虹膜(`u_irisDepth`),所以眼球转动时虹膜在表面后面移动。虹膜本身由 `u_irisColor` 到 `u_irisColor2` 绘制,带纤维纹理、深色角膜缘(`u_limbal`)和瞳孔(`u_pupilSize`),衬在眼白(`u_scleraColor`)上,眼白的光会绕过明暗交界线(`u_scleraWrap`)。角膜近似镜面(`u_corneaRoughness`、`u_specular`),所以每盏灯和天空都会变成一个眼神光。眼睑会给眼睛投下阴影:`u_lidMap` 是手绘的遮蔽图(眼睛睁开处为白色),`u_lidShadow` 会在表面朝上的地方(从 `u_lidStart` 即与世界上方向的点积起,到正上方)变暗并淡化角膜的反射,在头部直立时这就是上眼睑。网格上画的眼睛贴图会与结果相乘。diff --git a/fixtures/scenes/hair-tips.esscene b/fixtures/scenes/hair-tips.esscenenew file mode 100644index 000000000..6614c7674--- /dev/null+++ b/fixtures/scenes/hair-tips.esscene@@ -0,0 +1,155 @@+{+ "version": 4,+ "name": "HairTips",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Off",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -150,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 250,+ "y": 250,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true,+ "material": "/scenes/hair-tips/off.esmaterial",+ "texture": "@uuid:7c3e9a41-2b5d-4e8f-a1c6-9d0f4b2e7a56"+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "On",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 150,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 250,+ "y": 250,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true,+ "material": "/scenes/hair-tips/on.esmaterial",+ "texture": "@uuid:7c3e9a41-2b5d-4e8f-a1c6-9d0f4b2e7a56"+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "rotation": {+ "x": 0,+ "y": 0,+ "z": 0,+ "w": 1+ }+ }+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 0.8,+ "meshShadows": false+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/fixtures/scenes/hair-tips.png b/fixtures/scenes/hair-tips.pngnew file mode 100644index 000000000..58e14f34dBinary files /dev/null and b/fixtures/scenes/hair-tips.png differdiff --git a/fixtures/scenes/hair-tips.textures.json b/fixtures/scenes/hair-tips.textures.jsonnew file mode 100644index 000000000..c6135a12d--- /dev/null+++ b/fixtures/scenes/hair-tips.textures.json@@ -0,0 +1,3 @@+{+ "7c3e9a41-2b5d-4e8f-a1c6-9d0f4b2e7a56": "/scenes/hair-tips.png"+}\ No newline at end of filediff --git a/fixtures/scenes/hair-tips/off.esmaterial b/fixtures/scenes/hair-tips/off.esmaterialnew file mode 100644index 000000000..290dc00e9--- /dev/null+++ b/fixtures/scenes/hair-tips/off.esmaterial@@ -0,0 +1,14 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:hair",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_alphaCutoff": 0.6,+ "u_tipSoftness": 0,+ "u_specular": 0+ }+}\ No newline at end of filediff --git a/fixtures/scenes/hair-tips/on.esmaterial b/fixtures/scenes/hair-tips/on.esmaterialnew file mode 100644index 000000000..14d042b9d--- /dev/null+++ b/fixtures/scenes/hair-tips/on.esmaterial@@ -0,0 +1,14 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:hair",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_alphaCutoff": 0.6,+ "u_tipSoftness": 0.3,+ "u_specular": 0+ }+}\ No newline at end of filediff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 39f2f662a..429fe8b5d 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -761,6 +761,7 @@ if (opts.command === 'import-model' || opts.command === 'import-gltf') {);if (lightmapUVFor(opts)) warnings.push(...importer.applyLightmapUV(meshes));warnings.push(...await importer.generateLods(meshes, lodSettingsFor(opts)));+ if (characters) importer.orderHairTriangles(meshes);for (const w of warnings) console.warn(` ! ${w}`);if (!root && meshes.length > 0) {console.warn(' ! no project found above the source — refs are bare file names'diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.tsindex 363ba848c..13ac3ac5a 100644--- a/pipeline/src/assets/modelImport.ts+++ b/pipeline/src/assets/modelImport.ts@@ -11,7 +11,7 @@* second set of rules for what a model IS in this engine.*/import {- MeshChannel, encodeMesh, unwrapLightmapUV, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION,+ MeshChannel, MeshChannelType, encodeMesh, unwrapLightmapUV, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION,MATERIAL_FORMAT_VERSION, BlendMode, CullMode,type MeshData, type MaterialAssetData, type PrefabData, type PrefabEntityData,type PrefabComponentData as ComponentData,@@ -614,6 +614,59 @@ export function characterShading(material: ImportedMaterial): CharacterShading |return undefined;}+/**+ * Put the triangles of every hair mesh in the order a blended draw wants them: the ones nearest the middle of the hair first, the outermost+ * last. A hair model is a shell of cards around a head, and seen from outside a card nearer the middle is behind one further out, from+ * whichever side the camera looks, so one fixed order is the back-to-front order for all of them. Draws go through the index buffer in+ * order, which is what makes this an ordering at all. It is an approximation and says so: a ponytail that leaves the shell is not ordered+ * by it. Only meshes whose material {@link characterShading} calls hair; the levels of detail are ordered too.+ */+export function orderHairTriangles(meshes: ImportedMesh[]): void {+ for (const mesh of meshes) {+ if (!mesh.material || characterShading(mesh.material) !== 'hair') continue;+ const centre = hairCentre(mesh.data);+ if (!centre) continue;+ sortTriangles(mesh.data, centre);+ for (const lod of mesh.lods ?? []) sortTriangles(lod.data, centre);+ }+}++function positionsOf(data: MeshData): Float32Array | undefined {+ const channel = data.channels.find((c) => c.semantic === MeshChannel.Position && c.type === MeshChannelType.Float32 && c.components >= 3);+ if (!channel) return undefined;+ const view = new DataView(data.vertices.buffer, data.vertices.byteOffset, data.vertices.byteLength);+ const out = new Float32Array(data.vertexCount * 3);+ for (let i = 0; i < data.vertexCount; i++) {+ for (let k = 0; k < 3; k++) out[i * 3 + k] = view.getFloat32(i * data.vertexStride + channel.offset + k * 4, true);+ }+ return out;+}++/** The middle of the mesh's bounding box. */+function hairCentre(data: MeshData): [number, number, number] | undefined {+ const [lx, ly, lz] = data.aabbMin, [hx, hy, hz] = data.aabbMax;+ return [(lx + hx) / 2, (ly + hy) / 2, (lz + hz) / 2];+}++function sortTriangles(data: MeshData, centre: [number, number, number]): void {+ const positions = positionsOf(data);+ const count = Math.floor(data.indices.length / 3);+ if (!positions || count < 2) return;+ const key = new Float64Array(count);+ for (let t = 0; t < count; t++) {+ let x = 0, y = 0, z = 0;+ for (let k = 0; k < 3; k++) {+ const v = data.indices[t * 3 + k]! * 3;+ x += positions[v]!; y += positions[v + 1]!; z += positions[v + 2]!;+ }+ key[t] = Math.hypot(x / 3 - centre[0], y / 3 - centre[1], z / 3 - centre[2]);+ }+ const order = Array.from({ length: count }, (_, t) => t).sort((a, b) => key[a]! - key[b]! || a - b);+ const sorted = new Uint32Array(data.indices.length);+ order.forEach((from, to) => { sorted.set(data.indices.subarray(from * 3, from * 3 + 3), to * 3); });+ data.indices = sorted;+}+/** Whether a material gets a product: it says something a MeshRenderer cannot, or its name asks for a character shader. */function hasProduct(material: ImportedMaterial, refs: ProductRefs): boolean {return needsMaterial(material) || (!!refs.characters && characterShading(material) !== undefined);diff --git a/pipeline/tests/character-materials.test.ts b/pipeline/tests/character-materials.test.tsindex e83d7e28a..dfdaf464c 100644--- a/pipeline/tests/character-materials.test.ts+++ b/pipeline/tests/character-materials.test.ts@@ -2,7 +2,8 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, expect, it } from 'vitest';import { BlendMode } from 'esengine';-import { characterShading, materialProducts, type ImportedImageRef, type ImportedMaterial, type ImportedMesh } from '../src/assets/modelImport';+import { MeshChannel, MeshChannelType } from 'esengine';+import { characterShading, materialProducts, orderHairTriangles, type ImportedImageRef, type ImportedMaterial, type ImportedMesh } from '../src/assets/modelImport';const image = (file: string, data = false): ImportedImageRef => ({ file, external: true, ...(data ? { settings: { sRGB: false } } : {}) } as ImportedImageRef);@@ -53,3 +54,35 @@ describe('materialProducts with character materials', () => {expect(by.nitro_m3!.shader).toBe('builtin:model');});});++describe('orderHairTriangles', () => {+ // Three triangles at distances 1, 3 and 2 from the middle of the box, written outermost-first.+ function hairMesh(name: string): ImportedMesh {+ const ring = [[3, 0, 0], [1, 0, 0], [2, 0, 0]];+ const positions: number[] = [];+ for (const [x] of ring) positions.push(x!, 0, 0, x! + 0.1, 0.1, 0, x!, 0.1, 0.1);+ const vertices = new Uint8Array(positions.length * 4);+ new Float32Array(vertices.buffer).set(positions);+ return {+ name, vertexCount: 9, triangleCount: 3, material: material(0, name),+ data: {+ channels: [{ semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 }],+ vertexStride: 12, vertexCount: 9, vertices, indices: new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 8]),+ aabbMin: [-2, 0, 0], aabbMax: [2, 0, 0],+ },+ } as ImportedMesh;+ }++ it('puts the triangles nearest the middle of the hair first', () => {+ const hair = hairMesh('Hair');+ orderHairTriangles([hair]);+ // Distances from x=0: 3.03 (tri 0), 1.03 (tri 1), 2.03 (tri 2) -> 1, 2, 0.+ expect(Array.from(hair.data.indices)).toEqual([3, 4, 5, 6, 7, 8, 0, 1, 2]);+ });++ it('leaves a mesh that is not hair alone', () => {+ const cloth = hairMesh('Jacket');+ orderHairTriangles([cloth]);+ expect(Array.from(cloth.data.indices)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+ });+});diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex b20ff5670..98eff904b 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -1399,6 +1399,10 @@ const HAIR = `#pragma shader "Hair"// A card's alpha cut at this level, and sharpened to about a texel so alpha-to-coverage feathers the edge of every strand instead of stair-stepping it; 0 keeps the card opaque.#pragma param u_alphaCutoff float default(0) range(0,1) ui(slider)#pragma coverage u_alphaCutoff+// The soft outer band of a card: where its alpha falls from the cutoff down by this much, a second, blended pass draws the strand's tip fading out+// (the opaque pass keeps what is above the cutoff, feathered by coverage). Sorted with the other blended draws; 0 leaves it out.+#pragma param u_tipSoftness float default(0) range(0,0.5) ui(slider)+#pragma tips u_tipSoftness#pragma fragmentprecision highp float;@@ -1446,11 +1450,18 @@ void main() {vec4 base = texture(u_textures[0], v_texCoord, u_sharpen) * v_color * u_tint;// Before any discard: a derivative needs every fragment of its quad.float alpha = 1.0;+#ifdef ES_TIP_PASS+ // The band below the cutoff, fading in toward it, and a texel past it so it meets the opaque card without a gap.+ alpha = (base.a - (u_alphaCutoff - u_tipSoftness)) / max(u_tipSoftness, 1e-4);+ if (base.a >= u_alphaCutoff + fwidth(base.a) || alpha <= 0.0) discard;+ alpha = min(alpha, 1.0);+#elseif (u_alphaCutoff > 0.0) {alpha = (base.a - u_alphaCutoff) / max(fwidth(base.a), 1e-4) + 0.5;if (alpha <= 0.0) discard;alpha = min(alpha, 1.0);}+#endiffloat root = texture(u_ormMap, v_texCoord).r;float ao = mix(1.0, root, u_occlusionStrength);base.rgb *= mix(1.0, 0.35 + 0.65 * root, u_rootDark);@@ -1521,11 +1532,17 @@ fn packNormal(n : vec3f) -> vec2f {let T = vec3f(0.0, 1.0, 0.0);#endifvar alpha = 1.0;+#ifdef ES_TIP_PASS+ alpha = (base.a - (mc.u_alphaCutoff - mc.u_tipSoftness)) / max(mc.u_tipSoftness, 1e-4);+ if (base.a >= mc.u_alphaCutoff + edge || alpha <= 0.0) { discard; }+ alpha = min(alpha, 1.0);+#elseif (mc.u_alphaCutoff > 0.0) {alpha = (base.a - mc.u_alphaCutoff) / edge + 0.5;if (alpha <= 0.0) { discard; }alpha = min(alpha, 1.0);}+#endiflet ao = mix(1.0, orm.r, mc.u_occlusionStrength);base = vec4f(base.rgb * mix(1.0, 0.35 + 0.65 * orm.r, mc.u_rootDark), base.a);let noise = (shiftTex - 0.5) * mc.u_shiftAmount;diff --git a/src/esengine/bindings/MaterialBindings.cpp b/src/esengine/bindings/MaterialBindings.cppindex 114f9be1d..3a6f262c6 100644--- a/src/esengine/bindings/MaterialBindings.cpp+++ b/src/esengine/bindings/MaterialBindings.cpp@@ -47,6 +47,7 @@ static MaterialUniformLayout buildMaterialLayout(const resource::ParsedShader& pMaterialUniformLayout layout;layout.blockSize = parsed.materialBlockSize;layout.coverageParam = parsed.coverageParam;+ layout.tipParam = parsed.tipParam;layout.usesGBuffer = parsed.usesGBuffer;layout.usesLights = parsed.usesLights;layout.highPrecision = parsed.highPrecision;diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex fd2406749..15a6d3aa1 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -944,6 +944,21 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {const bool wire = shading == ShadingMode::Wireframe;if (wire) key.depthBias = kWireFillBias;pushBatchDraw(draw_list, clips, instOffset, 0, 0, resident->indexCount, key);+ // A cutout that asks for tips gets its soft outer band as a second, blended draw of the same+ // instance: no depth written, sorted with the other blended draws, and no surface record.+ if (!depthPass && !wire && key.materialId != 0 && ctx.materials && ctx.materials->hasTipPass(key.materialId)) {+ const u32 tipProgram = ctx.materials->meshProgram(key.materialId, ctx.resources, resident->hasNormals, skinned,+ key.envTextureId != 0, resident->hasLightmapUV, false,+ resident->hasTangents, true);+ if (tipProgram != 0) {+ BatchDrawKey tips = key;+ tips.shaderId = tipProgram;+ tips.stage = RenderStage::Transparent;+ tips.blend = BlendMode::Normal;+ tips.depthWrite = false;+ pushBatchDraw(draw_list, clips, instOffset, 0, 0, resident->indexCount, tips);+ }+ }// The edges, as a second draw of the same instance with its own ink: same// vertices, the mesh's line list, tested against the surface just drawn.if (wire && resident->hasEdges()) {diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 9449c2382..094f1afdb 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -67,7 +67,7 @@ void MaterialStore::clear() {u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals, bool skinned, bool envMapped,- bool lightmapped, bool gbuffer, bool tangents) const {+ bool lightmapped, bool gbuffer, bool tangents, bool tipPass) const {// Only for a shader that has something to write: one that never mentions the feature would// compile the same program twice and then be declared to write an output it does not have.if (gbuffer) {@@ -82,7 +82,8 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resour| (envMapped ? (1ull << 34) : 0ull)| (lightmapped ? (1ull << 36) : 0ull)| (gbuffer ? (1ull << 38) : 0ull)- | (tangents && withNormals ? (1ull << 39) : 0ull);+ | (tangents && withNormals ? (1ull << 39) : 0ull)+ | (tipPass ? (1ull << 40) : 0ull);std::vector<std::string> features{ "MESH" };if (withNormals) features.push_back("MESH_NORMALS");if (skinned) features.push_back("SKINNED");@@ -97,6 +98,7 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resour// positional light is read from where it is rather than from the plane.features.push_back("ES_SURFACE_3D");if (gbuffer) features.push_back("ES_GBUFFER");+ if (tipPass) features.push_back("ES_TIP_PASS");const u32 program = variantProgram(materialId, resources, shape, features, "resident geometry");if (gbuffer && program != 0) gbuffer_programs_.insert(program);return program;diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 7585752c1..58df15723 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -92,6 +92,8 @@ struct MaterialUniformLayout {/// The param whose value above zero makes output alpha coverage (see/// ParsedShader::coverageParam); empty when the shader declares none.std::string coverageParam;+ /// The float param that turns the shader's blended tip pass on (see ParsedShader::tipParam).+ std::string tipParam;/// The shader reads the scene's surface record (ParsedShader::usesGBuffer).bool usesGBuffer = false;/// The shader reads the frame's light block and shadow atlas (ParsedShader::usesLights).@@ -196,7 +198,7 @@ public:u32 meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals = false, bool skinned = false,bool envMapped = false, bool lightmapped = false, bool gbuffer = false,- bool tangents = false) const;+ bool tangents = false, bool tipPass = false) const;/// Whether @p programId is a variant that writes the surface record's second output — set when/// it was compiled for a pass that has one AND the material's shader has something to write@@ -360,6 +362,19 @@ public:return value > 0.0f;}+ /// Whether @p materialId draws a blended pass over its opaque one: its shader names a tip param and this+ /// material holds it above zero.+ bool hasTipPass(u32 materialId) const {+ const MaterialRecord* m = find(materialId);+ const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;+ if (!layout || layout->tipParam.empty()) return false;+ const MaterialParamSlot* slot = layout->find(layout->tipParam);+ if (!slot || slot->offset + sizeof(f32) > m->uboBytes.size()) return false;+ f32 value = 0.0f;+ std::memcpy(&value, m->uboBytes.data() + slot->offset, sizeof(f32));+ return value > 0.0f;+ }+/// The registered #pragma-param layout for a shader program, or nullptr./// The post-process pipeline reads it to pack pass params through the same/// reflected MaterialConstants block a material would use.diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 689b5bb7a..18c88ba85 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -727,6 +727,11 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeRcontinue;}+ if (directive == "tips") {+ result.tipParam = argument;+ continue;+ }+if (directive == "gbuffer") {result.usesGBuffer = true;continue;diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hppindex 37d9a4093..5c90b5eb4 100644--- a/src/esengine/resource/ShaderParser.hpp+++ b/src/esengine/resource/ShaderParser.hpp@@ -152,6 +152,10 @@ struct ParsedShader {/// output alpha is coverage (a cutout sharpened to one texel), so an opaque draw/// may turn it into multisample coverage instead of a hard edge.std::string coverageParam;+ /// `#pragma tips <param>`: while that float param is above zero, the shader draws a second, blended+ /// pass (compiled with ES_TIP_PASS) over the opaque one: the soft outer band of a cutout that+ /// coverage alone would stair-step.+ std::string tipParam;/// `#pragma gbuffer`: a post-process shader reads the scene's surface record (normal, roughness,/// metalness) at unit kGBufferUnit, so the frame must draw one for it.bool usesGBuffer = false;diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d2a57641b..45e670cf4 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2553,6 +2553,8 @@ export const NOTED = {{"note":"The Eye shader shades the eye the lids sit on: `u_lidMap` is an authored occlusion map, and `u_lidShadow` darkens, and fades the cornea's reflections, where the surface faces up from `u_lidStart`, which is the upper lid on an upright head."},"feat(import): a model can give its skin, hair and eye materials the character shaders":{"note":"Importing a model can now give its character materials the right shader: turn on Character Materials in the model's import settings and a material whose name says skin, face, head, hair or eye gets the Skin, Hair or Eye shader with its normal and occlusion/roughness maps bound, and hair is cut out by its alpha and feathered by coverage. Off by default."},+ "feat(render): Hair cards draw a soft blended tip pass below their cutoff":+ {"note":"The Hair shader can draw the soft outer band of its cards: `u_tipSoftness` is how far below the cutoff alpha a second, blended pass draws each strand's tip fading out, sorted with the other blended draws, so tips are not stair-stepped by coverage. A model imported with Character Materials also has its hair triangles put in the order that pass wants, the cards nearest the middle of the hair first. Off by default."},"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":{"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex eb0342e6c..a4b0f2781 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -214,6 +214,9 @@ export const SCENES = [{ id: "skin-preintegrate", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/skin-preint.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.3125,\"y\":0.5,\"rgb\":[77,32,24],\"tol\":15},{\"x\":0.8125,\"y\":0.5,\"rgb\":[94,13,0],\"tol\":15}]" } },// The Eye shader's lid shadow: two quads facing up under a light from above, the right with u_lidShadow 1, so the surface the upper lid sits over is darker.{ id: "eye-lid", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/eye-lid.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.117,\"y\":0.5,\"rgb\":[159,157,154],\"tol\":15},{\"x\":0.859,\"y\":0.5,\"rgb\":[64,63,62],\"tol\":15}]" } },+ // The Hair shader's tip pass: two cards whose alpha ramps from 0 to 1 across them, cut at 0.6; the right one draws the band below the cutoff as a+ // second, blended pass fading in toward it, so a pixel at alpha 0.45 shows the card half over the background where the left shows only the background.+ { id: "hair-tips", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/hair-tips.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/hair-tips.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.229,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":10},{\"x\":0.729,\"y\":0.5,\"rgb\":[106,106,106],\"tol\":15},{\"x\":0.39,\"y\":0.5,\"rgb\":[204,204,204],\"tol\":15}]" } },{ id: "skin-detail", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/skin-detail.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/skin-detail.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[137,89,80],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[253,205,197],\"tol\":20}]" } },{ id: "mesh-shadow-cutout", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-cutout.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-shadow-cutout.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.6,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20},{\"x\":0.167,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20}]" } },{ id: "mesh-shadow-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-material.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.708,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.167,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20}]" } },