diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b6984537..7ed415d7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,4 +34,4 @@ jobs: - name: Test in Electron run: pnpm run test:ci - timeout-minutes: 5 \ No newline at end of file + timeout-minutes: 10 \ No newline at end of file diff --git a/docs/BUG_AUDIT_2026-09.md b/docs/BUG_AUDIT_2026-09.md new file mode 100644 index 000000000..1887047b6 --- /dev/null +++ b/docs/BUG_AUDIT_2026-09.md @@ -0,0 +1,80 @@ +# 引擎 Bug 巡检报告(2026-09-27) + +分支:`feat/bugfix-and-analysis-20260927` +方法:在 Chrome(WebGPU,Mac Metal)里逐个加载 `samples/` 下全部 159 个示例,捕获 +`console.error` / `unhandledrejection` / `GPUDevice.uncapturederror`,同时截图目测; +并对 `src/` 与 `packages/*` 做 `tsc --noEmit`,最后跑 `npm test`(Electron + SwiftShader)。 + +## 结论 + +| 项目 | 结果 | +| --- | --- | +| Electron CI(54 个测试文件) | 修复前后均全绿 | +| 核心 `tsc` | 通过 | +| `packages/physics-rapier` `tsc` | 修复前 2 个错误,修复后通过 | +| 示例巡检 | 159 个示例全部能加载;1 个直接崩溃,1 个逻辑错误,1 个引擎级首帧问题,1 个内存/日志问题,1 个示例参数问题 | + +## 已修复 + +### 1. Rapier `CharacterController` 崩溃(示例黑屏) + +- 现象:`Sample_RapierCharacter` 黑屏,控制台 `TypeError: Physics.world.updateSceneQueries is not a function`。 +- 根因:仓库根 `package.json` 依赖 `@dimforge/rapier3d-compat@^0.19.3`,而插件代码按 0.14 API 写的。 + 0.15 起 `World.updateSceneQueries()` 被删除(查询管线并入 broad-phase,由 `step()` 刷新)。 + 插件自己的 `package.json` 仍写着 `^0.14.0`,掩盖了 API 漂移。 +- 修复:`packages/physics-rapier/character/CharacterController.ts` 改调 + `propagateModifiedBodyPositionsToColliders()`;`packages/physics-rapier/package.json` 依赖改为 `^0.19.3`。 + +### 2. `CharacterController` 首帧穿透地面 + +- 现象:修掉崩溃后,角色在第 1 帧就掉到 y = −358,永远落不到地面。 +- 根因(两层叠加): + 1. 引擎在 `renderLoop`(`Physics.update()`)之前先跑组件 `onUpdate`,所以创建当帧还没有 `world.step()`, + broad-phase BVH 是空的,`computeColliderMovement` 扫不到地板,直接返回完整位移。 + 2. 引擎首帧 `Time.delta` 是页面启动以来的整段时间(见第 3 条),重力一次积分出几十米。 +- 修复:`Physics` 新增 `stepCount`;`CharacterController.move()` 在自身创建后至少经过一次 `step()` 才开始移动。 + +### 3. 引擎首帧 / 恢复后 `Time.delta` 巨大(引擎级) + +- 现象:`Engine3D._tick` 用 `time - Time.time` 算 delta,`Time.time` 初始为 0,首帧 delta = rAF 时间戳 + (通常 1–5 秒);`pause()` 后 `resume()` 的第一帧同样等于整个暂停时长。任何按 dt 积分的逻辑 + (物理、动画、控制器、插值器)都会在这一帧跳一大步。 +- 修复:`src/Engine3D.ts` 加 `_resetDelta` 标记,循环首次启动与 `resume()` 后的第一帧使用名义 1/60 s。 + +### 4. 矩阵上传 staging buffer 无上限累积 + 每帧刷警告 + +- 现象:多数示例每帧打印 + `Warning: mapAsync requests from N frames ago have not resolved yet. MB of staging buffers allocated.` + 实测 `GlobalBindGroup` 的矩阵 buffer 池里挂着 72 个空闲 staging buffer(每个都是整张矩阵表大小)。 +- 根因:`GPUBufferBase.mapAsyncWrite` 的计数器只增不减(复用时不减),启动阶段 GPU 编译管线导致 + `mapAsync` 延迟 20+ 帧,池子一次性膨胀到几十个,之后计数永远高于阈值,警告每帧触发; + 空闲 buffer 也永远不释放,`destroy()` 也不清理它们。 +- 修复:计数器改为真正的"在途"数量(resolve 时递减);空闲池上限 3 个,多余的在 resolve 时销毁; + `destroy()` 释放池内 buffer;警告改为每次积压只报一次并给出 MB 数; + `MatrixGPUBuffer.writeBufferByHeap` 改为委托给同一实现(保留旧名)。 + +### 5. `Physics.init({ deterministic: true })` 设置了不存在的字段 + +- `numAdditionalFrictionIterations` 在 Rapier 0.15 已删除,赋值静默无效且 `tsc` 报错。已移除该行。 + +### 6. `Sample_Label` 标签重叠(示例) + +- `distanceInvariantSize` 的参考深度硬编码 10 m,示例相机在 30 m,标签宽度被放大 3 倍互相盖住。 + 示例相机距离改为 10。 + +## 确认不是 bug(巡检中误判后排除) + +- **Rapier 物体悬空 / 动画不动**:Chrome 后台标签页 rAF 停止,是测试环境问题。改用 Worker 驱动帧循环后全部正常。 +- **SpotLight 全黑、BoundingBox/DirectLightShadow 镜头贴脸**:`HoverCameraController` 初始插值尚未到位。 +- **Skyline 无效果**:示例相机俯视,画面里没有天空边界;抬头后能看到红色描边。 +- **GraphicGrass 大蓝三角**:示例本身的草叶就是纯色三角面。 +- **音频 / 视频示例**:依赖 `cdn.orillusion.com` 与自动播放策略,未计入。 + +## 遗留(未改动,建议后续处理) + +- `@dimforge/rapier3d-compat` 内部 `init()` 触发 wasm-bindgen 的 + "using deprecated parameters for the initialization function" 警告,是上游包问题。 +- `packages/geometry/tsconfig.json` 缺 `experimentalDecorators`,直接 `tsc -p` 会报装饰器错误 + (构建脚本靠命令行参数补上)。 +- `src/loader/parser/prefab/prefabData/APatch.ts` 装饰器里引用自身类,只有在旧式装饰器下合法。 +- 详细的引擎功能缺口见 `docs/ENGINE_COMPARISON_2026-09.md`。 diff --git a/docs/ENGINE_COMPARISON_2026-09.md b/docs/ENGINE_COMPARISON_2026-09.md new file mode 100644 index 000000000..e99a1c87e --- /dev/null +++ b/docs/ENGINE_COMPARISON_2026-09.md @@ -0,0 +1,256 @@ +# Orillusion 0.9.2 与 three.js / Babylon.js / Unity / Unreal 的差距分析(2026-09) + +依据:本仓库 `src/`、`packages/`、`samples/` 的实际代码盘点(不是 README 承诺),对照四个引擎当前公开版本 +(three.js r17x WebGPURenderer + TSL、Babylon.js 8、Unity 6 URP/HDRP、Unreal 5.x)。 +四者中 three.js 与 Babylon 是直接竞品(同为浏览器引擎),Unity / Unreal 只作"能力天花板"参照, +它们的原生平台、编辑器体量与 Web 引擎不在同一赛道,逐项对标时会注明"不适用"。 + +## 1. 一句话定位 + +| 引擎 | 定位 | 对 Orillusion 的启示 | +| --- | --- | --- | +| Orillusion | WebGPU-only 的渲染引擎,Forward+ 与 RenderGraph 为核心,带 GIS / 大坐标特性 | 技术栈最新,包袱最少,但功能面与生态最薄 | +| three.js | 最通用的 Web 3D 库,WebGL + WebGPU 双后端,TSL 节点着色语言 | 生态与文档是护城河;Orillusion 需要在"WebGPU 原生做得更深"上找差异 | +| Babylon.js | 功能最全的 Web 引擎:编辑器、Node Material、Havok、GUI、XR | 是 Orillusion 功能缺口的最直接对照表 | +| Unity | 通用游戏引擎,编辑器驱动,URP / HDRP 两条管线 | 内容工作流(编辑器、Prefab、序列化、LOD、烘焙)的标杆 | +| Unreal | AAA 引擎:Nanite、Lumen、VSM、Substrate | 渲染上限的标杆,Web 端不可直接对标 | + +## 2. 总览评分 + +5 = 业界领先,3 = 可用但有明显短板,1 = 缺失或仅有骨架。分数是相对同类能力的主观评估。 + +| 维度 | Orillusion | three.js | Babylon.js | Unity | Unreal | +| --- | --- | --- | --- | --- | --- | +| 渲染管线架构 | 4 | 3 | 4 | 5 | 5 | +| 材质 / PBR 完整度 | 3 | 5 | 5 | 5 | 5 | +| 光照 / 阴影 / GI | 3 | 3 | 4 | 5 | 5 | +| 后处理 | 3 | 4 | 5 | 5 | 5 | +| 动画系统 | 4 | 3 | 4 | 5 | 5 | +| 资产格式 / 压缩 / 流式 | 2 | 5 | 5 | 5 | 5 | +| 场景管理 / 剔除 / LOD | 2 | 3 | 4 | 5 | 5 | +| 物理 | 4 | 3(外接) | 5(Havok) | 5 | 5 | +| 2D / UI / 文本 | 2 | 2 | 5 | 5 | 5 | +| XR | 1 | 4 | 5 | 5 | 5 | +| 工具链 / 编辑器 / 调试 | 2 | 3 | 5 | 5 | 5 | +| 测试与质量保障 | 3 | 4 | 4 | 不适用 | 不适用 | +| 文档 / 社区 / 生态 | 1 | 5 | 5 | 5 | 5 | +| 包体积 / tree-shaking | 2 | 4 | 3 | 不适用 | 不适用 | +| 兼容性(WebGL 回退、移动端) | 1 | 5 | 5 | 不适用 | 不适用 | + +Orillusion 的强项:RenderGraph、Forward+ 集群光照、OIT(WBOIT + 双层深度剥离)、DDGI、PCSS、多实例、 +RTE 大坐标与 3D Tiles、Rapier 物理、动画图(分层、遮罩、IK、重定向)。这些里有几项 three.js 至今没有。 +弱项集中在"内容管线"(资产格式、LOD、流式、编辑器、序列化)和"生态"(文档、示例站、社区、WebGL 回退)。 + +## 3. 逐项对比 + +### 3.1 渲染管线 + +已有:`ForwardRendererJob` 的 pass 链(ClusterLighting → PreDepth → HiZ → MotionVector → GPUCull → +Shadow → Reflection → GI → Color → Sky → SceneColorPyramid → Transmission → Decal → 透明 → OIT → Post → GUI), +`RenderGraph` 有依赖调度、瞬态资源别名池、`dumpDot`。MSAA、TAA、FXAA、log depth、RTE、stencil 都在。 + +| 能力 | Orillusion | three.js | Babylon | Unity / UE | +| --- | --- | --- | --- | --- | +| 延迟管线 | 仅占位(`DeferredRendererJob` 直接 throw) | 无(Forward) | 有 PrePass / 部分延迟 | HDRP 与 UE 都是延迟 | +| GPU 剔除接入绘制 | 计算完但 ColorPass 仍走 CPU 列表 | 无 | 无 | Unity GPU Resident Drawer、UE Nanite | +| LOD | 无 | `LOD` 对象 | `LODGroup`、自动 LOD 生成 | 完整 LOD + HLOD | +| Tonemapping | 仅 ACES / None | ACES、AgX、Neutral、Reinhard、Cineon | 多种 + 颜色分级 | 完整颜色分级 | +| HDR 输出 | 无 | 有(`rgba16float` swapchain) | 有 | 有 | +| 实例化 / 批处理 | 有 InstancedMesh 与 EntityBatchCollect | InstancedMesh、BatchedMesh | Thin Instances | GPU Instancing / SRP Batcher | +| 遮挡剔除 | Hi-Z pass 已有,Occlusion 系统 98 行 | 无 | 硬件遮挡查询 | 有 | + +建议: +1. **把 GPUCull 真正接入 ColorPass 的 indirect draw**,这是已完成 80% 的工作,收益最大。 +2. **LOD 组件 + 屏幕空间误差**,同一套逻辑可以复用给 3D Tiles 的 `geometricError`(当前解析了但没用)。 +3. Tonemap 至少补 AgX 与 Khronos Neutral(glTF 官方推荐),并把 `LUT_glsl` 接成颜色分级 pass。 +4. 延迟管线要么补齐要么从 API 中移除占位,避免误导使用者。 + +### 3.2 材质与着色 + +已有:`LitMaterial` 覆盖 base / metallic-roughness / AO / normal / emissive / clearcoat / transmission / +volume / IOR / specular;SSS 与 hair 有 shader;WGSL 预处理器支持 `#include` / `#if` / 整型 uniform; +有 GLSL→WGSL 转换器。 + +| 能力 | Orillusion | three.js | Babylon | Unity / UE | +| --- | --- | --- | --- | --- | +| Sheen / Iridescence / Anisotropy / Dispersion | 无 | 全有 | 全有 | 有 | +| 节点材质 / 可视化着色 | 无 | TSL(代码即节点图) | Node Material Editor | Shader Graph / Material Editor | +| 自定义材质门槛 | 需写完整 WGSL pass + 注册 | `MeshStandardNodeMaterial` 插槽式扩展 | `CustomMaterial` 插入点 | 图形化 | +| 着色器热重载 | 缓存失效有,管线不重建;vite `hmr:false` | 有 | 有 | 有 | +| 皮肤 SSS | `SkinMaterial` 是 MVP 骨架,实际按普通 Lit 渲染 | 无内建 | 有 | 有 | + +建议: +1. 补 sheen / iridescence / anisotropy,这是 glTF 扩展落地的前提,三个都是几十行 BRDF。 +2. 设计一个 **材质插槽 API**(类似 three 的 node slot 或 Babylon 的 `CustomMaterial`), + 让用户不用复制整个 `PBRLitShader` 就能改 albedo / normal / emissive。 +3. `SkinMaterial` 要么接上 `PBRLitSSSShader` 要么标 experimental。 + +### 3.3 光照、阴影、GI + +已有:方向光 / 点光 / 聚光,IES,CSM,点光 cube shadow,PCF / PCSS,静态阴影缓存,接触阴影, +DDGI 探针体,SSGI(实验),反射探针 + IBL 预过滤,SSR,GTAO。 + +| 能力 | Orillusion | three.js | Babylon | Unity / UE | +| --- | --- | --- | --- | --- | +| 面光源 | 无(仅有 `rectLight` import 名) | RectAreaLight(LTC) | Area lights(8.x) | 有 | +| Lightmap / 烘焙 | 无 | 支持贴图 | 支持 + 在线烘焙 | 完整烘焙器 | +| VSM / ESM | 无 | VSM | ESM、PCSS、级联 | VSM(UE)、PCSS | +| 实时 GI | DDGI 可用;VCT 是骨架;SSGI 实验 | 无 | 无(只有 SSR / 反射探针) | Lumen / SSGI / APV | +| IBL 阴影 | 无 | 无 | 有(8.0) | 有 | +| 体积光 / 雾 | GodRay + GlobalFog;`_Sample_VolumetricFog` 停用 | 无内建 | 有体积光 | 有 | + +建议: +1. **面光源(LTC)**:three 与 Babylon 都有,产品/建筑可视化场景必需。 +2. **Lightmap 读取**:只做读取(UV2 + 贴图),不做烘焙,就能承接 Blender / Unity 导出的静态场景。 +3. 清理 `VoxelConeTracingGI` 骨架与 `postProcessing.ssao` 无消费的设置项,把 SSGI 要么做完要么下线。 + +### 3.4 后处理 + +已有 16 个 Post 类(Bloom、TAA、FXAA、Tonemap、GTAO、SSR、SSGI、DoF、GlobalFog、VolumetricFog、 +GodRay、Outline、Skyline、ContactShadow、GBuffer 调试)。数量上不弱于 three(EffectComposer 系)。 + +缺:运动模糊(MotionVector 已经算了但没人用)、色差、暗角、胶片颗粒、镜头光晕、颜色分级 LUT、SMAA。 +`packages/post/index.ts` 是空文件。 + +建议:补运动模糊 + 颜色分级 + 暗角三件套即可追平 Babylon 的 `DefaultRenderingPipeline`; +把 `packages/post` 要么填充要么删除。 + +### 3.5 动画 + +已有:GPU 蒙皮(compute)、`AnimatorComponent`(crossFade、分层、遮罩、附加混合、状态机钩子、 +`retargetTo`、IK 挂载)、1D BlendTree、CCD / TwoBone IK、重定向、morph、曲线 / 属性动画、动画事件。 + +这一块是 Orillusion 相对 three.js 的**优势项**(three 只有 `AnimationMixer` + 少量 IK 示例), +与 Babylon 相当。对 Unity 的差距: + +| 能力 | Orillusion | Unity / UE | +| --- | --- | --- | +| 2D BlendTree | 无 | 有 | +| 时间轴 / Sequencer | 无 | Timeline / Sequencer | +| 可视化状态机 | 仅代码钩子 | Animator 窗口 / Anim BP | +| 根运动 | 重定向选项里有 | 完整 | +| 物理动画(ragdoll) | 需自己拼 Rapier 关节 | 有 | + +建议:2D BlendTree 与一个简单的 Timeline(关键帧 + 事件轨道)即可覆盖大部分 Web 场景需求。 + +### 3.6 资产格式、压缩与流式 + +这是与 three / Babylon 差距最大的一块。 + +| 能力 | Orillusion | three.js | Babylon | +| --- | --- | --- | --- | +| glTF 扩展 | clearcoat、unlit、emissive_strength、ior、transmission、volume、texture_transform、lights_punctual、draco | 几乎全部 KHR / EXT | 几乎全部 | +| sheen / specular / variants / quantization / basisu | 空的 8 行 stub 类 | 有 | 有 | +| KTX2 / Basis 转码 | 无(只有 BC7 枚举) | 有 | 有 | +| meshopt / EXT_mesh_gpu_instancing | 无 | 有 | 有 | +| FBX / OBJ / USD / EXR | 仅 OBJ、RGBE | FBX、OBJ、USDZ、EXR、PLY、STL 等几十种 | 大部分 | +| 3D Tiles | 有,但整棵树一次性加载,`geometricError` / `refine` 没消费 | 社区 `3DTilesRendererJS` | 有 | +| 资源缓存 / 引用计数 | URL 级缓存 | `Cache` + 引用计数 | `AssetContainer` | +| Web Worker 解码 | 无 | Draco / KTX2 都在 worker | 有 | + +建议(按收益排序): +1. **KTX2 + Basis Universal 转码**(worker 内)。WebGPU 上没有压缩纹理意味着移动端显存直接翻 4–8 倍。 +2. 把 5 个 stub 扩展做实:`KHR_materials_sheen / specular / variants`、`KHR_mesh_quantization`、 + `KHR_texture_basisu`。其中 quantization 只是顶点格式映射。 +3. 3D Tiles 的 **SSE 驱动的加载 / 卸载**,否则 GIS 场景无法上规模。 +4. `EXT_meshopt_compression` + `EXT_mesh_gpu_instancing`(后者可直接映射到 `InstancedMesh`)。 + +### 3.7 场景管理、剔除、拾取、空间结构 + +已有:Object3D 组件模型(Unity 风格,不是真 ECS)、WASM 矩阵、八叉树 / KD 树 / 四叉树、 +GPU 像素拾取 + 碰撞体射线拾取。 + +缺:BVH(网格射线是暴力遍历)、`BoundingBox.intersectsRay` 与 `BoundingSphere.updateBound` 直接 throw "not implemented"、 +LOD、场景序列化(只有 prefab 导入没有导出)。three 有社区 `three-mesh-bvh`,Babylon 有场景序列化 / `.babylon`。 + +建议:先补两个 throw 的方法与一个 BVH,再考虑场景保存格式。 + +### 3.8 物理、粒子、特效、UI、音视频 + +| 能力 | Orillusion | three.js | Babylon | Unity / UE | +| --- | --- | --- | --- | --- | +| 物理 | Ammo + Rapier 双后端,车辆 / 角色 / 快照 | 无内建(社区 Rapier / cannon) | Havok(WASM)、Ammo、Cannon | PhysX / Chaos | +| 粒子 | CPU / compute 混合系统,`GPUParticleSystem` 是骨架 | 无内建 | GPU 粒子 + 编辑器 | VFX Graph / Niagara | +| UI | 无(GUIPass 只是 present blit) | 无 | 完整 2D GUI + 3D GUI | uGUI / UI Toolkit / UMG | +| 文本 | canvas 贴图 + opentype 3D 文字 | Troika(社区 SDF) | 有 | 有 | +| 音视频 | 位置音频、视频贴图、抠像 | 位置音频 | 有 | 有 | +| 地形 / 水 | TerrainGeometry、无水体 | 无 | 有水体 / 地形 | 有 | +| 导航网格 | A* + funnel,示例停用,无生成器 | 无 | Recast(WASM) | 有 | + +Rapier 集成是亮点(Babylon 之外唯一把角色控制器、车辆、快照做全的 Web 引擎), +但本次巡检发现它跟随的 Rapier API 版本落后(详见 `BUG_AUDIT_2026-09.md`),需要加一条 CI 用例覆盖。 +UI 是最明显的空白:任何产品级应用都需要 HUD / 标签 / 面板,目前只能靠 DOM 叠加。 + +### 3.9 相机与控制 + +有 5 种控制器与 ortho / perspective,缺物理相机模型(感光度 / 光圈 / 快门联动曝光与 DoF) +与轨道相机组件。Babylon 有 `ArcRotate / Universal / Follow / Device orientation` 等十余种。 + +### 3.10 工具链、DX、质量保障 + +| 能力 | Orillusion | three.js | Babylon | Unity / UE | +| --- | --- | --- | --- | --- | +| 编辑器 | 无 | 官方在线 editor(轻量) | Playground + Inspector + Editor | 核心竞争力 | +| 运行时 Inspector | dat.gui 封装 + Stats | 社区 | 内建 Inspector(场景树、材质、后处理全可调) | 有 | +| 帧调试 | `GBufferPost`、split debug、`dumpDot` | Spector.js(社区) | Spector.js(同团队)+ 帧统计 | RenderDoc / Frame Debugger | +| 测试 | Electron + SwiftShader,54 个文件,无截图回归 | 单元 + e2e 截图回归(每个 example 一张) | 视觉回归 + 单元 | 内部 | +| 文档 | typedoc 生成,无手册;示例站需自己跑 | 文档 + 手册 + 几百个在线示例 | 文档 + Playground 即时可改 | 完整 | +| TypeScript | 全 TS | 类型包 | 全 TS | C# / C++ | +| tree-shaking | `index.ts` 是全量桶文件,无 `sideEffects` | 好 | 一般 | 不适用 | +| WebGL 回退 | 无,直接 throw | 自动回退 | 自动回退 | 不适用 | +| OffscreenCanvas / Worker 渲染 | 不支持(依赖 DOM canvas) | 支持 | 支持 | 不适用 | +| WebXR | 无 | 完整 | 完整 | 不适用 | +| 移动端 | 有触控,无质量分档 | 有 | 有 | 有 | +| 多实例 / 多视口 | 有(本次 v2 重点) | 有 | 有 | 有 | + +建议: +1. **截图回归测试**:现有 Electron 基础设施已经能跑 WebGPU,只差"每个示例截一张图 + 比对"。 + 本次巡检就是靠人工截图找 bug,自动化后能挡住绝大多数渲染回归。 +2. **Inspector**:把已有的 dat.gui 面板产品化成场景树 + 材质 + 后处理的通用检视器,成本远低于编辑器。 +3. `package.json` 加 `sideEffects: false`,检查副作用注册(`MaterialRegister`、`ShaderLib.register`)改成显式导入。 +4. WebGL 回退可以不做(这是 Orillusion 的定位),但**必须提供能力检测 + 友好降级页面**的官方方案。 +5. WebXR 至少做到 `immersive-vr` 的 `XRWebGLBinding` 等价物(WebGPU 的 `XRGPUBinding` 已在 Chrome 落地)。 + +### 3.11 数学库 + +v2 已对齐 three.js 命名,缺 `Euler`、`Spherical`(现在是 OrbitController 的私有类)、`Cylindrical`、 +`Box2`、`Matrix2`、CatmullRom / 样条曲线、`SphericalHarmonics3`。`MathUtil` 里有角度制 / 弧度制不一致的 TODO。 + +### 3.12 性能与规模(结构性判断,未做基准) + +- 优点:WASM 矩阵、集群光照、OIT、Hi-Z、瞬态资源别名,都是 three.js 没有或刚有的。 +- 隐患:矩阵每帧整表上传(本次修了 staging 池泄漏,但方式本身仍是"全量拷贝", + 改成脏区间上传或 `queue.writeBuffer` 更简单);CPU 侧绘制列表没接 GPU cull; + 无 LOD 意味着大场景只能靠遮挡剔除;`Matrix4.maxCount` 固定分配。 +- 建议做一组公开基准(10 万实例、1 万光源、大 glTF 加载时间)并放进 CI 记录趋势。 + +## 4. 建议的优先级 + +**P0(3 个月内,决定"能不能用于产品")** +1. KTX2 / Basis 纹理压缩 + worker 解码 +2. LOD 组件 + GPU cull 接入绘制 +3. 截图回归测试 + 每个示例的 CI 覆盖 +4. 面光源(LTC)+ sheen / iridescence / anisotropy +5. 引擎首帧 / 恢复 delta、Rapier API 版本这类"基础可靠性"问题清零(本次已修一部分) + +**P1(6 个月内,决定"和 three / Babylon 比有没有理由选你")** +1. 运行时 Inspector +2. 材质插槽 / 轻量节点式自定义材质 +3. 3D Tiles 的 SSE 流式加载(Orillusion 的 GIS 差异化卖点) +4. 运动模糊 + 颜色分级 + AgX +5. 基础 UI 系统(面板、文本、图片、九宫格) +6. `sideEffects` + 桶文件拆分,给出包体积数据 + +**P2(长期)** +1. WebXR +2. Lightmap 读取 / 烘焙 +3. 延迟管线或移除占位 +4. Timeline / 2D BlendTree +5. 场景序列化格式与在线编辑器 + +## 5. 一页总结 + +Orillusion 的渲染内核已经是 WebGPU 引擎里较先进的一档(RenderGraph、Forward+、OIT、DDGI、多实例、RTE), +动画与物理也不输 Babylon。真正拉开差距的是**内容管线**(纹理压缩、LOD、流式、扩展覆盖)、 +**工具链**(Inspector、截图回归、文档站)和**生态**(WebGL 回退、XR、社区示例)。 +先把 P0 五项补齐,Orillusion 才能从"技术验证引擎"变成"可以承接产品项目的引擎"。 diff --git a/docs/STATUS_2026-09.md b/docs/STATUS_2026-09.md new file mode 100644 index 000000000..c1537378a --- /dev/null +++ b/docs/STATUS_2026-09.md @@ -0,0 +1,106 @@ +# Orillusion 巡检总结:已修复 / 未修复 / 缺失(2026-09-28) + +分支:`feat/bugfix-and-analysis-20260927`(改动尚未提交) +范围:`src/`、`packages/*`、`samples/`(159 个示例)、`test/`(54 个测试文件) +验证方式:Chrome WebGPU 逐示例加载 + 截图;`tsc --noEmit`;`npm test`(Electron + SwiftShader) +配套文档:`docs/BUG_AUDIT_2026-09.md`(巡检过程)、`docs/ENGINE_COMPARISON_2026-09.md`(与 three / Babylon / Unity / UE 的对比) + +--- + +## 一、已修复(6 项,7 个文件) + +| # | 问题 | 严重度 | 文件 | 验证 | +| --- | --- | --- | --- | --- | +| 1 | Rapier `CharacterController` 调用已删除的 `World.updateSceneQueries()`,示例直接崩溃黑屏 | 高 | `packages/physics-rapier/character/CharacterController.ts` | 示例恢复,`tsc` 通过 | +| 2 | `CharacterController` 首帧穿地(创建当帧 BVH 为空,角色掉到 y = −358) | 高 | `packages/physics-rapier/Physics.ts`、`CharacterController.ts` | 角色稳定站在 y = 0.96 | +| 3 | 引擎首帧 / `resume()` 后第一帧 `Time.delta` 等于整段页面加载或暂停时长 | 高(引擎级) | `src/Engine3D.ts` | 首帧 delta = 16.7 ms,CI 全绿 | +| 4 | 矩阵上传 staging buffer 池只增不减:72 个整表大小的空闲 buffer 常驻,每帧刷一条警告 | 中(内存 + 日志) | `src/gfx/graphics/webGpu/core/buffer/GPUBufferBase.ts`、`MatrixGPUBuffer.ts` | 稳态 ready = 3、pending = 0,警告只在积压时出现一次 | +| 5 | `Physics.init({deterministic:true})` 设置 Rapier 0.15 起已删除的 `numAdditionalFrictionIterations` | 低 | `packages/physics-rapier/Physics.ts` | `tsc` 通过 | +| 6 | `Sample_Label` 三个标签互相覆盖(相机 30 m 与 distanceInvariant 参考深度 10 m 不匹配) | 低(示例) | `samples/sprite/Sample_Label.ts` | 截图确认不重叠 | + +另:`packages/physics-rapier/package.json` 依赖由 `^0.14.0` 改为 `^0.19.3`,与根 `package.json` 一致,避免再次出现 API 漂移。 + +### 每项修了什么 + +**1. Rapier API 漂移。** 根依赖是 rapier3d-compat 0.19.3,插件按 0.14 写。0.15 起查询管线并入 broad-phase,由 `world.step()` 刷新,`updateSceneQueries()` 被删除。改为调用 0.19 保留的 `propagateModifiedBodyPositionsToColliders()`。用 `grep Physics.world.` 与 `pipeline/world.d.ts` 逐个比对,确认插件其余调用(`castRay`、`createCharacterController`、车辆控制器等)在 0.19 都存在。 + +**2. 首帧穿地。** 引擎每帧顺序是:组件 `onUpdate` → `renderLoop`(示例在这里调 `Physics.update()`)。角色在创建当帧就 `move()`,此时还没有 `world.step()`,BVH 为空,`computeColliderMovement` 扫不到任何东西,返回完整位移。`Physics` 新增 `stepCount`,控制器记录创建时的 step 数,至少经过一次 step 后才允许移动。 + +**3. 首帧 delta。** `_tick` 用 `time - Time.time` 算 delta,`Time.time` 初始为 0,第一帧 delta 等于 rAF 时间戳(通常 1–5 秒);`pause()` 期间 `Time.time` 冻结,`resume()` 第一帧 delta 等于暂停时长。物理、动画、插值器、控制器都会在这一帧跳一大步。加 `_resetDelta` 标记,循环首次启动和 `resume()` 后的第一帧使用 1/60 s。 + +**4. staging buffer 池。** `mapAsyncWrite` 的 `mapAsyncBuffersOutstanding` 在创建时加、复用时不减,启动阶段 GPU 编译管线导致 `mapAsync` 延迟 20 多帧,池子一次膨胀几十个后永远不缩,计数永远超过阈值,警告每帧触发;`destroy()` 也不释放池内 buffer。现在:计数改为真实在途数(resolve 时递减);空闲池上限 3 个,多余的在 resolve 时销毁;`destroy()` 释放池并把池置空,让在途的 buffer 自行释放;警告改为每次积压只报一次并带 MB 数,阈值 60;`MatrixGPUBuffer.writeBufferByHeap` 改为委托同一实现,去掉重复代码但保留旧函数名。 + +--- + +## 二、发现但未修复(需要你决定) + +| # | 问题 | 位置 | 为什么没改 | 建议 | +| --- | --- | --- | --- | --- | +| 1 | Rapier 初始化打印 wasm-bindgen 警告 `using deprecated parameters for the initialization function` | `@dimforge/rapier3d-compat` 内部 `init()` | 上游包问题,本仓库无法根治 | 等上游 0.20 或在 `Physics.init` 里临时过滤该条 console.warn 并注明原因 | +| 2 | `packages/geometry/tsconfig.json` 缺 `experimentalDecorators`,直接 `tsc -p` 报 8 个装饰器错误 | `packages/geometry/tsconfig.json` | 构建脚本用命令行参数补上,不影响产物 | 在 tsconfig 里补上,让 IDE 与 CLI 一致 | +| 3 | `APatch` 在自身装饰器参数里引用自身类 | `src/loader/parser/prefab/prefabData/APatch.ts:12` | 旧式装饰器下合法,核心 `tsc` 通过 | 改为字符串注册或延迟引用,避免以后切换到标准装饰器时炸 | +| 4 | 矩阵每帧整表上传(`mapAsync` + staging + copy),本次只修了泄漏,机制本身仍是全量拷贝 | `GPUBufferBase.mapAsyncWrite`、`MatrixBindGroup.writeBuffer` | 属于性能重构,超出 bug 修复范围 | 改成 `queue.writeBuffer` 脏区间上传,或按 `Matrix4.useCount` 只传使用部分 | +| 5 | `Sample_GraphicGrass` 视觉上是一堆纯色大三角,看不出是草 | `samples/graphic/Sample_GraphicGrass.ts` | 是示例设计(草叶为三角面 + `line3.png`),不是引擎问题 | 换贴图和相机参数让示例有说服力 | +| 6 | 音频 / 视频示例依赖 `cdn.orillusion.com` 与浏览器自动播放策略 | `samples/audio/*`、`samples/material/Sample_VideoMaterial.ts`、`samples/sprite/Sample_Video.ts` | 网络与策略问题,本地未验证 | 把资源放进 `public` 子模块 | +| 7 | 现有 CI 完全覆盖不到示例:本次所有 bug 出现时 `npm test` 都是绿的 | `test/`、`.github/workflows/ci.yml` | 需要新的基础设施 | 见下一节"缺失"第 1 条 | + +--- + +## 三、缺失的能力(引擎层面,未在本次实现) + +以下是代码里确认不存在或只有骨架的能力,按对产品可用性的影响排序。每条都给出与竞品的对照和实现代价估计(S = 1 周内,M = 1 个月内,L = 更长)。 + +### 优先级 P0 + +| # | 缺失 | 现状证据 | three.js / Babylon | 代价 | +| --- | --- | --- | --- | --- | +| 1 | **截图回归测试** | `test/` 只有单元与 pass 级测试,没有任何视觉比对 | three 每个 example 有基准图 | S,Electron 基础设施已经能跑 WebGPU | +| 2 | **KTX2 / Basis 纹理压缩** | 只有 `WebGPUConst` 里的 BC7 枚举,无转码器 | 两者都有 worker 转码 | M | +| 3 | **LOD 组件** | `src/` 和 `packages/` 无任何 LOD 实现 | `THREE.LOD`、Babylon `LODGroup` | S | +| 4 | **GPU 剔除接入绘制** | `GPUCullPass` 算完结果,`ColorPass` 仍遍历 CPU 列表 | Unity GPU Resident Drawer | M | +| 5 | **面光源** | 只有 `rectLight` 的 import 名,无实现 | three RectAreaLight、Babylon Area lights | S(LTC 表 + 几十行 BRDF) | +| 6 | **Sheen / Iridescence / Anisotropy** | `src/assets` 里没有 `sheen` 字样 | 两者全有 | S | + +### 优先级 P1 + +| # | 缺失 | 现状证据 | 对照 | 代价 | +| --- | --- | --- | --- | --- | +| 7 | 5 个 glTF 扩展是空 stub | `gltf/extends/` 下 sheen / specular / variants / quantization / basisu 各 8 行 | 两者全支持 | S–M | +| 8 | 3D Tiles 流式加载 | `TileSet.ts` 解析了 `geometricError` / `refine` 但不消费,整棵树一次性加载 | `3DTilesRendererJS` | M | +| 9 | 运行时 Inspector | 只有 dat.gui 封装 + Stats | Babylon Inspector | M | +| 10 | 材质插槽 / 轻量自定义材质 | 自定义材质要复制整个 `PBRLitShader` | three TSL、Babylon `CustomMaterial` | M | +| 11 | 运动模糊 / 颜色分级 / AgX | `MotionVectorPass` 已算但无人用;Tonemap 只有 ACES;`packages/post/index.ts` 为空 | Babylon `DefaultRenderingPipeline` | S | +| 12 | UI 系统 | `GUIPass` 只是 present blit | Babylon GUI | L | +| 13 | tree-shaking | `src/index.ts` 全量桶文件,无 `sideEffects` | three 可摇 | S | +| 14 | BVH + 两个 throw 的方法 | `BoundingBox.intersectsRay`、`BoundingSphere.updateBound` 抛 "not implemented" | three-mesh-bvh | S | + +### 优先级 P2 + +| # | 缺失 | 现状证据 | 代价 | +| --- | --- | --- | --- | +| 15 | WebXR | 无任何 XR 代码 | L | +| 16 | WebGL 回退或官方降级方案 | `Context3D` 直接 throw | 不做回退也要给检测 + 降级页 | +| 17 | OffscreenCanvas / Worker 渲染 | `Context3D` 依赖 DOM canvas | M | +| 18 | Lightmap 读取 | 无 | S | +| 19 | 延迟管线 | `DeferredRendererJob` 直接 throw 占位 | L,或删除占位 | +| 20 | VCT GI / SSGI | `VoxelConeTracingGI` 是骨架;SSGI 示例停用 | L,或下线 | +| 21 | `GPUParticleSystem` | 只推进位置,无渲染路径 | M | +| 22 | `SkinMaterial` SSS | 标 MVP,实际按普通 Lit 渲染 | S | +| 23 | 2D BlendTree / Timeline | 只有 1D | M | +| 24 | 场景序列化导出 | 只有 prefab 导入 | L | +| 25 | 数学库补全 | 无 `Euler`、`Spherical`(私有)、`Cylindrical`、`Box2`、样条、`SphericalHarmonics3` | S | +| 26 | 移动端质量分档 | 有触控,无分档 | S | + +--- + +## 四、一页看板 + +``` +已修复 6 项 Rapier 崩溃 / 首帧穿地 / 首帧 delta / staging 泄漏 / 废弃字段 / 示例重叠 +未修复 7 项 上游警告 / tsconfig / APatch 装饰器 / 全量矩阵上传 / 示例观感 / CDN 依赖 / CI 无示例覆盖 +缺失 P0 6 项 截图回归 / KTX2 / LOD / GPU cull 接入 / 面光源 / sheen 等 BRDF +缺失 P1 8 项 glTF stub / Tiles 流式 / Inspector / 材质插槽 / 后处理三件套 / UI / tree-shaking / BVH +缺失 P2 12 项 XR / 回退 / Worker / Lightmap / 延迟 / VCT / GPU 粒子 / SSS / Timeline / 序列化 / 数学 / 移动端 +``` + +建议下一步:先落"截图回归测试",因为本次 6 个 bug 里没有一个被现有 CI 捕获;有了它,后面每补一项能力都有安全网。 diff --git a/package.json b/package.json index b81245f8f..25698f961 100644 --- a/package.json +++ b/package.json @@ -32,19 +32,20 @@ "dev": "vite", "build": "tsc --p tsconfig.build.json && vite build && npm run build:types && npm run minify", "build:test": "tsc --p tsconfig.build.json && vite build && npm run build:packages", - "build:packages": "npm run build:physics && npm run build:media && npm run build:stats && npm run build:particle && npm run build:graphic && npm run build:geometry", + "build:packages": "npm run build:physics && npm run build:media && npm run build:stats && npm run build:particle && npm run build:graphic && npm run build:geometry && npm run build:atmosphere", "build:physics": "cd packages/physics && npm run build", "build:media": "cd packages/media-extention && npm run build", "build:stats": "cd packages/stats && npm run build", "build:particle": "cd packages/particle && npm run build", "build:graphic": "cd packages/graphic && npm run build", "build:geometry": "cd packages/geometry && npm run build", + "build:atmosphere": "cd packages/atmosphere && npm run build", "build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json && find src -name \"*.d.ts\" | while read file; do mkdir -p dist/$(dirname \"$file\"); cp \"$file\" dist/\"$file\"; done && mv dist/src dist/types", "minify": "node scripts/minify.mjs", "test": "electron test/ci/main.js", "test:manual": "xvfb-maybe -- electron --enable-unsafe-webgpu --enable-features=Vulkan --use-vulkan=swiftshader --use-webgpu-adapter=swiftshader --no-sandbox test/ci/main_manual.js", "test:ci": "xvfb-maybe -- electron --enable-unsafe-webgpu --enable-features=Vulkan --use-vulkan=swiftshader --use-webgpu-adapter=swiftshader --no-sandbox test/ci/main.js", - "docs": "npm run docs:core && npm run docs:physics && npm run docs:physics-rapier && npm run docs:media && npm run docs:stats && npm run docs:particle && npm run docs:graphic", + "docs": "npm run docs:core && npm run docs:physics && npm run docs:physics-rapier && npm run docs:media && npm run docs:stats && npm run docs:particle && npm run docs:graphic && npm run docs:atmosphere", "docs:typedoc": "npx typedoc --plugin typedoc-plugin-markdown --tsconfig tsconfig.build.json --gitRevision main --hideBreadcrumbs --router member --readme none --excludeInternal --excludePrivate --excludeProtected --excludeExternals --sort source-order --out", "docs:core": "npm run docs:typedoc docs/api src/index.ts", "docs:physics": "cd packages/physics && npm run docs", @@ -53,6 +54,7 @@ "docs:stats": "cd packages/stats && npm run docs", "docs:particle": "cd packages/particle && npm run docs", "docs:graphic": "cd packages/graphic && npm run docs", + "docs:atmosphere": "cd packages/atmosphere && npm run docs", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s" }, "devDependencies": { diff --git a/packages/atmosphere/component/AtmosphericComponent.ts b/packages/atmosphere/component/AtmosphericComponent.ts new file mode 100644 index 000000000..d3672648b --- /dev/null +++ b/packages/atmosphere/component/AtmosphericComponent.ts @@ -0,0 +1,218 @@ +import { AtmosphericScatteringSky, AtmosphericScatteringSkySetting } from "../textures/AtmosphericScatteringSky"; +import { SkyRenderer } from "../renderer/SkyRenderer"; +import { Context3D, Transform } from "@orillusion/core"; + +class HistoryData { + public rotateX: number; + public rotateY: number; + + public sunX: number; + public sunY: number; + + constructor() { + this.reset(); + } + + public reset(): this { + this.rotateX = this.rotateY = this.sunX = this.sunY = Number.MAX_VALUE; + return this; + } + + public isRotateChange(rx: number, ry: number): boolean { + return Math.abs(this.rotateX - rx) >= 0.001 || Math.abs(this.rotateY - ry) >= 0.001; + } + + public isSkyChange(x: number, y: number): boolean { + return Math.abs(this.sunX - x) >= 0.001 || Math.abs(this.sunY - y) >= 0.001; + } + + public save(x: number, y: number, rx: number, ry: number): this { + this.sunX = x; + this.sunY = y; + this.rotateX = rx; + this.rotateY = ry; + + return this; + } +} + +/** + * Physically based atmospheric sky box component. + * + * Drop-in replacement for the core `AtmosphericComponent`: same knobs, but the + * sky is produced by a Hillaire-style LUT chain with an optional volumetric + * cloud layer instead of the single-pass Chapman approximation (still + * reachable through {@link showV1}). + * + * @group Components + */ +export class AtmosphericComponent extends SkyRenderer { + + private _atmosphericScatteringSky: AtmosphericScatteringSky; + private _pendingSetting: AtmosphericScatteringSkySetting; + private _onChange: boolean = true; + private _relatedTransform: Transform; + private _historyData: HistoryData; + private _useAsEnvMap: boolean = true; + + /** Whether the atmospheric sky texture is also assigned as the + * scene's envMap (feeding material IBL / reflections). Default true. + * Set false — before start() or at runtime — to keep the visible + * sky dome while scene.envMap stays untouched. */ + public get useAsEnvMap(): boolean { return this._useAsEnvMap; } + public set useAsEnvMap(value: boolean) { + if (this._useAsEnvMap == value) return; + this._useAsEnvMap = value; + const scene = this.transform?.scene3D; + if (!scene || !this._atmosphericScatteringSky) return; + if (value) { + scene.envMap = this._atmosphericScatteringSky; + } else if (scene.envMap == this._atmosphericScatteringSky) { + // Null restores the lazy defaultSky fallback in Scene3D.envMap. + scene.envMap = null; + } + } + + /** The baked sky texture and its LUT chain. Null until the component has + * seen the view it renders through — see {@link _ensureSky}. */ + public get atmosphericScatteringSky(): AtmosphericScatteringSky { + return this._atmosphericScatteringSky; + } + + /** CPU-side setting object. Available pre-GPU: setters mutate this; the + * GPU sky consumes it on first render. */ + private get _setting(): AtmosphericScatteringSkySetting { + return this._atmosphericScatteringSky?.setting ?? this._pendingSetting; + } + + /** Horizontal sun position in normalized [0,1] sky coordinates. */ + public get sunX() { return this._setting.sunX; } + public set sunX(value) { + if (this._setting.sunX != value) { this._setting.sunX = value; this._onChange = true; } + } + + /** Vertical sun position in normalized [0,1] sky coordinates. */ + public get sunY() { return this._setting.sunY; } + public set sunY(value) { + if (this._setting.sunY != value) { this._setting.sunY = value; this._onChange = true; } + } + + /** Eye (viewer) altitude in meters used by the scattering model. */ + public get eyePos() { return this._setting.eyePos; } + public set eyePos(value) { + if (this._setting.eyePos != value) { this._setting.eyePos = value; this._onChange = true; } + } + + /** Angular radius of the sun disc. */ + public get sunRadius() { return this._setting.sunRadius; } + public set sunRadius(value) { + if (this._setting.sunRadius != value) { this._setting.sunRadius = value; this._onChange = true; } + } + + /** Radiance (intensity) of the sun. */ + public get sunRadiance() { return this._setting.sunRadiance; } + public set sunRadiance(value) { + if (this._setting.sunRadiance != value) { this._setting.sunRadiance = value; this._onChange = true; } + } + + /** Overall brightness of the sun. */ + public get sunBrightness() { return this._setting.sunBrightness; } + public set sunBrightness(value) { + if (this._setting.sunBrightness != value) { this._setting.sunBrightness = value; this._onChange = true; } + } + + /** Whether the sun disc is drawn in the sky. */ + public get displaySun() { return this._setting.displaySun; } + public set displaySun(value) { + if (this._setting.displaySun != value) { this._setting.displaySun = value; this._onChange = true; } + } + + /** Whether the volumetric cloud layer is ray-marched into the sky. */ + public get enableClouds() { return this._setting.enableClouds; } + public set enableClouds(value) { + if (this._setting.enableClouds != value) { this._setting.enableClouds = value; this._onChange = true; } + } + + /** Render the legacy Chapman-approximation sky instead of the LUT chain. */ + public get showV1() { return this._setting.showV1; } + public set showV1(value) { + if (this._setting.showV1 != value) { this._setting.showV1 = value; this._onChange = true; } + } + + /** Exposure fed to the tonemap / gamma step of the sky kernel. */ + public get hdrExposure() { return this._setting.hdrExposure; } + public set hdrExposure(value) { + if (this._setting.hdrExposure != value) { this._setting.hdrExposure = value; this._onChange = true; } + } + + /** Initialize history tracking and the pending sky setting. */ + public init(): void { + super.init(); + this._historyData = new HistoryData(); + this._pendingSetting = new AtmosphericScatteringSkySetting(); + } + + /** + * Build the GPU sky on the owning engine's context. Deferred out of + * `init()` because a component can be added to a Scene3D before the view + * it renders through — and therefore its Context3D — is known. + */ + private _ensureSky(ctx?: Context3D) { + if (this._atmosphericScatteringSky) return; + this._atmosphericScatteringSky = new AtmosphericScatteringSky(this._pendingSetting, ctx); + let scene = this.transform.scene3D; + this.map = this._atmosphericScatteringSky; + if (this._useAsEnvMap) { + // The sky texture already carries isHDRTexture from its ctor. + scene.envMap = this._atmosphericScatteringSky; + } + } + + /** Ensure the GPU sky exists, then run base startup. */ + public start(view?: any): void { + const ctx = view?.engine3D?.context3D ?? this.transform?.view3D?.engine3D?.context3D; + this._ensureSky(ctx); + super.start(); + } + + /** Transform whose rotation is kept in sync with the sun direction. */ + public get relativeTransform() { + return this._relatedTransform; + } + + public set relativeTransform(value: Transform) { + this._relatedTransform = value; + this._historyData.reset(); + } + + /** Per-frame update: sync sun/transform rotation and re-bake the sky on change. */ + public onUpdate(view?: any) { + const ctx = view?.engine3D?.context3D ?? this.transform?.view3D?.engine3D?.context3D; + this._ensureSky(ctx); + + if (this._relatedTransform) { + this._relatedTransform.rotationZ = 0; + if (this._historyData.isRotateChange(this._relatedTransform.rotationX, this._relatedTransform.rotationY)) { + this.sunX = (this._relatedTransform.rotationY + 90) / 360; + this.sunY = this._relatedTransform.rotationX / 180 + 0.5; + } else if (this._historyData.isSkyChange(this.sunX, this.sunY)) { + this._relatedTransform.rotationY = this.sunX * 360 - 90; + this._relatedTransform.rotationX = (this.sunY - 0.5) * 180; + } + this._historyData.save(this.sunX, this.sunY, this._relatedTransform.rotationX, this._relatedTransform.rotationY); + } + + if (this._onChange && this._atmosphericScatteringSky) { + this._onChange = false; + this._atmosphericScatteringSky.apply(); + } + } + + /** Destroy the component and release the GPU sky resources. */ + public destroy(force?: boolean): void { + super.destroy(force); + this._atmosphericScatteringSky?.destroy(force); + this._atmosphericScatteringSky = null; + this._onChange = null; + } +} diff --git a/packages/atmosphere/index.ts b/packages/atmosphere/index.ts new file mode 100644 index 000000000..72d6e6148 --- /dev/null +++ b/packages/atmosphere/index.ts @@ -0,0 +1,3 @@ +export * from './component/AtmosphericComponent'; +export * from './renderer/SkyRenderer'; +export * from './textures/AtmosphericScatteringSky'; diff --git a/packages/atmosphere/package.json b/packages/atmosphere/package.json new file mode 100644 index 000000000..339a39896 --- /dev/null +++ b/packages/atmosphere/package.json @@ -0,0 +1,27 @@ +{ + "name": "@orillusion/atmosphere", + "version": "0.1.0", + "author": "Orillusion", + "description": "Orillusion Physically Based Atmosphere Plugin", + "main": "./dist/atmosphere.umd.js", + "module": "./dist/atmosphere.es.js", + "module:dev": "./index.ts", + "types": "./dist/index.d.ts", + "files": ["dist"], + "scripts": { + "dev": "vite", + "build": "vite build && npm run build:types && npm run build:clean", + "build:types": "tsc --emitDeclarationOnly --experimentalDecorators -p tsconfig.json", + "build:clean": "mv dist/packages/atmosphere/* dist && rm -rf dist/src && rm -rf dist/packages", + "docs": "npm run docs:typedoc ../../docs/atmosphere index.ts", + "docs:typedoc": "npx typedoc --plugin typedoc-plugin-markdown --tsconfig tsconfig.json --gitRevision main --hideBreadcrumbs --router member --readme none --excludeInternal --excludePrivate --excludeProtected --excludeExternals --sort source-order --out" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Orillusion/orillusion.git" + }, + "peerDependencies": { + "@orillusion/core": ">=0.9.0" + } +} diff --git a/packages/atmosphere/renderer/SkyRenderer.ts b/packages/atmosphere/renderer/SkyRenderer.ts new file mode 100644 index 000000000..0031b444a --- /dev/null +++ b/packages/atmosphere/renderer/SkyRenderer.ts @@ -0,0 +1,8 @@ +/** + * The upstream PR vendored a copy of the engine's SkyRenderer into this + * package. Core's renderer has since become multi-instance aware — it sizes + * the sky sphere from the owning view's engine setting and registers itself + * per Scene3D through `EntityCollect.setSky` — so the package re-exports it + * rather than forking engine internals that would drift on every release. + */ +export { SkyRenderer } from "@orillusion/core"; diff --git a/packages/atmosphere/shader/AtmosphereEarth.wgsl b/packages/atmosphere/shader/AtmosphereEarth.wgsl new file mode 100644 index 000000000..ee8c6f78b --- /dev/null +++ b/packages/atmosphere/shader/AtmosphereEarth.wgsl @@ -0,0 +1,111 @@ +fn GetAtmosphereParameters() -> AtmosphereParameters { + var info: AtmosphereParameters; + + let EarthBottomRadius: f32 = 6360.0; + var scalar: f32 = 1.0; // TODO: control with uniform + var EarthTopRadius: f32 = EarthBottomRadius + 100.0 * scalar; + var EarthRayleighScaleHeight: f32 = 8.0 * scalar; + var EarthMieScaleHeight: f32 = 1.2 * scalar; + + info.BottomRadius = EarthBottomRadius; + info.TopRadius = EarthTopRadius; + info.GroundAlbedo = vec3(1.0, 1.0, 1.0); + + info.RayleighDensityExpScale = -1.0 / EarthRayleighScaleHeight; + info.RayleighScattering = vec3(0.005802, 0.013558, 0.033100); + + info.MieDensityExpScale = -1.0 / EarthMieScaleHeight; + info.MieScattering = vec3(0.003996, 0.003996, 0.003996); + info.MieExtinction = vec3(0.004440, 0.004440, 0.004440); + info.MieAbsorption = info.MieExtinction - info.MieScattering; + info.MiePhaseG = 0.8; + + info.AbsorptionDensity0LayerWidth = 25.0 * scalar; + info.AbsorptionDensity0ConstantTerm = -2.0 / 3.0; + info.AbsorptionDensity0LinearTerm = 1.0 / (15.0 * scalar); + info.AbsorptionDensity1ConstantTerm = 8.0 / 3.0; + info.AbsorptionDensity1LinearTerm = -1.0 / (15.0 * scalar); + info.AbsorptionExtinction = vec3(0.000650, 0.001881, 0.000085); + + // Cloud parameters + info.CloudBaseHeight = 3.0; // Base height of clouds in km + info.CloudTopHeight = 5.0; // Top height of clouds in km + info.CloudScattering = vec3(0.9, 0.9, 0.9); // Albedo of clouds + info.CloudAbsorption = vec3(0.001, 0.001, 0.001); + info.CloudPhaseG = 0.8; + info.CloudK = 0.5; + + return info; +} + +fn getAlbedo(scattering: vec3, extinction: vec3) -> vec3 { + return vec3( + scattering.x / max(0.001, extinction.x), + scattering.y / max(0.001, extinction.y), + scattering.z / max(0.001, extinction.z) + ); +} + +fn sampleMediumRGB(WorldPos: vec3, Atmosphere: AtmosphereParameters) -> MediumSampleRGB { + var viewHeight: f32 = length(WorldPos) - Atmosphere.BottomRadius; + + var densityMie: f32 = exp(Atmosphere.MieDensityExpScale * viewHeight); + var densityRay: f32 = exp(Atmosphere.RayleighDensityExpScale * viewHeight); + var clampVal: f32 = Atmosphere.AbsorptionDensity1LinearTerm * viewHeight + Atmosphere.AbsorptionDensity1ConstantTerm; + if viewHeight < Atmosphere.AbsorptionDensity0LayerWidth { + clampVal = Atmosphere.AbsorptionDensity0LinearTerm * viewHeight + Atmosphere.AbsorptionDensity0ConstantTerm; + } + var densityOzo: f32 = clamp(clampVal, 0.0, 1.0); + + var s: MediumSampleRGB; + + s.scatteringMie = densityMie * Atmosphere.MieScattering; + s.absorptionMie = densityMie * Atmosphere.MieAbsorption; + s.extinctionMie = densityMie * Atmosphere.MieExtinction; + + s.scatteringRay = densityRay * Atmosphere.RayleighScattering; + s.absorptionRay = vec3(0.0, 0.0, 0.0); + s.extinctionRay = s.scatteringRay + s.absorptionRay; + + s.scatteringOzo = vec3(0.0, 0.0, 0.0); + s.absorptionOzo = densityOzo * Atmosphere.AbsorptionExtinction; + s.extinctionOzo = s.scatteringOzo + s.absorptionOzo; + + if uniformBuffer.enableClouds > .5 { + var cloudDensity: f32 = sampleCloudDensity(WorldPos, Atmosphere); + s.scatteringCloud = cloudDensity * Atmosphere.CloudScattering; + s.absorptionCloud = cloudDensity * Atmosphere.CloudAbsorption; + s.extinctionCloud = s.scatteringCloud + s.absorptionCloud; + } + + s.scattering = s.scatteringMie + s.scatteringRay + s.scatteringOzo + s.scatteringCloud; + s.absorption = s.absorptionMie + s.absorptionRay + s.absorptionOzo + s.absorptionCloud; + s.extinction = s.extinctionMie + s.extinctionRay + s.extinctionOzo + s.extinctionCloud; + s.albedo = getAlbedo(s.scattering, s.extinction); + + return s; +} + +fn sigmoid(x: f32) -> f32 { + return 1.0 / (1.0 + exp(-x)); +} + +fn sampleCloudDensity(WorldPos: vec3, Atmosphere: AtmosphereParameters) -> f32 { + var x: f32 = length(WorldPos) - Atmosphere.BottomRadius; + var ymin: f32 = Atmosphere.CloudBaseHeight; + var ymax: f32 = Atmosphere.CloudTopHeight; + var yt: f32 = 1.0; + var baseVal: f32 = smoothstep(ymin, ymin + yt, x) * (1. - smoothstep(ymax - yt, ymax, x)); + var noiseScale: f32 = 1. / 11000.; + var uv0: vec2 = WorldPos.xz * noiseScale; + var noiseValue: f32 = sampleCloudTexture(uv0); + var noiseExpression: f32 = 12.; + var noiseFactor: f32 = sigmoid(noiseValue * 2.0 * noiseExpression - noiseExpression); + return baseVal * noiseFactor; +} + +// sample the cloud texture +fn sampleCloudTexture(uv: vec2) -> f32 { + var coords = vec2(uv * vec2(textureDimensions(cloudTexture, 0))); + return textureSampleLevel(cloudTexture, cloudTextureSampler, coords, 0).r; +} diff --git a/packages/atmosphere/shader/AtmosphereUniforms.wgsl b/packages/atmosphere/shader/AtmosphereUniforms.wgsl new file mode 100644 index 000000000..c59896be6 --- /dev/null +++ b/packages/atmosphere/shader/AtmosphereUniforms.wgsl @@ -0,0 +1,16 @@ +struct UniformData { + width: f32, + height: f32, + sunU: f32, + sunV: f32, + eyePos: f32, + sunRadius: f32, // = 500.0; + sunRadiance: f32, // = 20.0; + mieG: f32, // = 0.76; + mieHeight: f32, // = 1200; + sunBrightness: f32, // = 1.0; + displaySun: f32, // > 0.5: true + enableClouds: f32, // > 0.5: true + hdrExposure: f32, // = 1.0; + skyColor: vec4, // sky color +}; \ No newline at end of file diff --git a/packages/atmosphere/shader/AtmosphericScatteringIntegration.wgsl b/packages/atmosphere/shader/AtmosphericScatteringIntegration.wgsl new file mode 100644 index 000000000..8fa1ca2d0 --- /dev/null +++ b/packages/atmosphere/shader/AtmosphericScatteringIntegration.wgsl @@ -0,0 +1,429 @@ +// the max distance to ray march in meters +var defaultTMaxMax: f32 = 9000000.0; +var PLANET_RADIUS_OFFSET: f32 = 0.01; + +// Sample per pixel for ray marching +// 16.0 without clouds +// 128.0 for thicker atmosphere +// 256.0 for clouds +var RayMarchMinMaxSPP: vec2 = vec2(1.0, 16.0); +var RayMarchMinMaxSPPCloud: vec2 = vec2(1.0, 256.0); +var MULTI_SCATTERING_POWER_SERIE: u32 = 1; +var MULTISCATAPPROX_ENABLED: u32 = 1; +var SHADOWMAP_ENABLED: u32 = 0; +var VOLUMETRIC_SHADOW_ENABLED: u32 = 1; +var MultiScatteringLUTRes: f32 = 32.0; + +struct SingleScatteringResult { + L: vec3, // Scattered light (luminance) + OpticalDepth: vec3, // Optical depth (1/m) + Transmittance: vec3, // Transmittance in [0,1] (unitless) + MultiScatAs1: vec3, + NewMultiScatStep0Out: vec3, + NewMultiScatStep1Out: vec3, +}; + +var SunLuminance: vec3 = vec3(1000000.0); // arbitrary. But fine, not use when comparing the models + +struct AtmosphereParameters { + BottomRadius: f32, + TopRadius: f32, + + RayleighDensityExpScale: f32, + RayleighScattering: vec3, + + MieDensityExpScale: f32, + MieScattering: vec3, + MieExtinction: vec3, + MieAbsorption: vec3, + MiePhaseG: f32, + + AbsorptionDensity0LayerWidth: f32, + AbsorptionDensity0ConstantTerm: f32, + AbsorptionDensity0LinearTerm: f32, + AbsorptionDensity1ConstantTerm: f32, + AbsorptionDensity1LinearTerm: f32, + AbsorptionExtinction: vec3, + + GroundAlbedo: vec3, + + CloudBaseHeight: f32, + CloudTopHeight: f32, + CloudScattering: vec3, + CloudAbsorption: vec3, + CloudPhaseG: f32, + CloudK: f32, +}; + +struct MediumSampleRGB { + scattering: vec3, + absorption: vec3, + extinction: vec3, + + scatteringMie: vec3, + absorptionMie: vec3, + extinctionMie: vec3, + + scatteringRay: vec3, + absorptionRay: vec3, + extinctionRay: vec3, + + scatteringOzo: vec3, + absorptionOzo: vec3, + extinctionOzo: vec3, + + scatteringCloud: vec3, + absorptionCloud: vec3, + extinctionCloud: vec3, + + albedo: vec3, +}; + +fn ComputeSphereNormal(coord: vec2, phiStart: f32, phiLength: f32, thetaStart: f32, thetaLength: f32) -> vec3 { + var normal: vec3; + normal.x = -sin(thetaStart + coord.y * thetaLength) * sin(phiStart + coord.x * phiLength); + normal.y = -cos(thetaStart + coord.y * thetaLength); + normal.z = -sin(thetaStart + coord.y * thetaLength) * cos(phiStart + coord.x * phiLength); + return normalize(normal); +} + +fn raySphereIntersectNearest(r0: vec3, rd: vec3, s0: vec3, sR: f32) -> f32 { + var a: f32 = dot(rd, rd); + var s0_r0: vec3 = r0 - s0; + var b: f32 = 2.0 * dot(rd, s0_r0); + var c: f32 = dot(s0_r0, s0_r0) - (sR * sR); + var delta: f32 = b * b - 4.0 * a * c; + if delta < 0.0 || a == 0.0 { + return -1.0; + } + var sol0: f32 = (-b - sqrt(delta)) / (2.0 * a); + var sol1: f32 = (-b + sqrt(delta)) / (2.0 * a); + if sol0 < 0.0 && sol1 < 0.0 { + return -1.0; + } + if sol0 < 0.0 { + return max(0.0, sol1); + } else if sol1 < 0.0 { + return max(0.0, sol0); + } + return max(0.0, min(sol0, sol1)); +} + +fn CornetteShanksMiePhaseFunction(g: f32, cosTheta: f32) -> f32 { + var k: f32 = 3.0 / (8.0 * PI) * (1.0 - g * g) / (2.0 + g * g); + return k * (1.0 + cosTheta * cosTheta) / pow(1.0 + g * g - 2.0 * g * -cosTheta, 1.5); +} + +fn RayleighPhase(cosTheta: f32) -> f32 { + var factor: f32 = 3.0 / (16.0 * PI); + return factor * (1.0 + cosTheta * cosTheta); +} + +fn hgPhase(g: f32, cosTheta: f32) -> f32 { + return CornetteShanksMiePhaseFunction(g, cosTheta); +} + +// dual-lobe hg phase +fn dualLobeHgPhase(g: f32, cosTheta: f32, k: f32) -> f32 { + var phase1: f32 = hgPhase(g, cosTheta); + var phase2: f32 = hgPhase(-g, cosTheta); + return mix(phase1, phase2, k); +} + +fn LutTransmittanceParamsToUv(Atmosphere: AtmosphereParameters, viewHeight: f32, viewZenithCosAngle: f32) -> vec2 { + var H: f32 = sqrt(max(0.0, Atmosphere.TopRadius * Atmosphere.TopRadius - Atmosphere.BottomRadius * Atmosphere.BottomRadius)); + var rho: f32 = sqrt(max(0.0, viewHeight * viewHeight - Atmosphere.BottomRadius * Atmosphere.BottomRadius)); + + var discriminant: f32 = viewHeight * viewHeight * (viewZenithCosAngle * viewZenithCosAngle - 1.0) + Atmosphere.TopRadius * Atmosphere.TopRadius; + var d: f32 = max(0.0, (-viewHeight * viewZenithCosAngle + sqrt(discriminant))); // Distance to atmosphere boundary + + var d_min: f32 = Atmosphere.TopRadius - viewHeight; + var d_max: f32 = rho + H; + var x_mu: f32 = (d - d_min) / (d_max - d_min); + var x_r: f32 = rho / H; + + return vec2(x_mu, x_r); +} + +fn fromUnitToSubUvs(u: f32, resolution: f32) -> f32 { + return (u + 0.5 / resolution) * (resolution / (resolution + 1.0)); +} + +fn fromSubUvsToUnit(u: f32, resolution: f32) -> f32 { + return (u - 0.5 / resolution) * (resolution / (resolution - 1.0)); +} + +fn GetSunLuminance(WorldPos: vec3, WorldDir: vec3, PlanetRadius: f32) -> vec3 { + var sun_direction: vec3 = normalize(getSunDirection()); + if dot(WorldDir, sun_direction) > cos(0.5 * 0.505 * PI / 180.0) { + var t: f32 = raySphereIntersectNearest(WorldPos, WorldDir, vec3(0.0, 0.0, 0.0), PlanetRadius); + if t < 0.0 { // no intersection + return SunLuminance; // arbitrary. But fine, not use when comparing the models + } + } + return vec3(0.0); +} + +fn MoveToTopAtmosphere(WorldPos: ptr>, WorldDir: vec3, AtmosphereTopRadius: f32) -> bool { + var viewHeight: f32 = length(*WorldPos); + if viewHeight > AtmosphereTopRadius { + var tTop: f32 = raySphereIntersectNearest(*WorldPos, WorldDir, vec3(0.0, 0.0, 0.0), AtmosphereTopRadius); + if tTop >= 0.0 { + var UpVector: vec3 = *WorldPos / viewHeight; + var UpOffset: vec3 = UpVector * -0.01; + *WorldPos = *WorldPos + WorldDir * tTop + UpOffset; + } else { + // Ray is not intersecting the atmosphere + return false; + } + } + return true; // ok to start tracing +} + +fn getSunDirection() -> vec3 { + var sun = vec2(uniformBuffer.sunU, uniformBuffer.sunV); + var L: vec3 = ComputeSphereNormal(vec2(sun.x, sun.y), 0.0, PI_2, 0.0, PI); + return L; +} + +fn GetTransmittanceToSun(Atmosphere: AtmosphereParameters, P: vec3) -> vec3 { + var pHeight: f32 = length(P); + var UpVector: vec3 = P / pHeight; + var SunZenithCosAngle: f32 = dot(getSunDirection(), UpVector); + var uv = LutTransmittanceParamsToUv(Atmosphere, pHeight, SunZenithCosAngle); + return textureSampleLevel(transmittanceTexture, transmittanceTextureSampler, uv, 0).rgb; +} + +fn GetMultipleScattering(Atmosphere: AtmosphereParameters, scattering: vec3, extinction: vec3, worlPos: vec3, viewZenithCosAngle: f32) -> vec3 { + var uv = saturate(vec2(viewZenithCosAngle * 0.5 + 0.5, (length(worlPos) - Atmosphere.BottomRadius) / (Atmosphere.TopRadius - Atmosphere.BottomRadius))); + uv = vec2(fromUnitToSubUvs(uv.x, MultiScatteringLUTRes), fromUnitToSubUvs(uv.y, MultiScatteringLUTRes)); + + var multiScatteredLuminance: vec3 = textureSampleLevel(multipleScatteringTexture, multipleScatteringTextureSampler, uv, 0).rgb; + return multiScatteredLuminance; +} + +fn getShadow(Atmosphere: AtmosphereParameters, P: vec3) -> f32 { + // TODO: sample cascading shadow map + return 1.0; +} + +fn computeVolumetricShadow(WorldPos: vec3, LightDir: vec3, Atmosphere: AtmosphereParameters) -> f32 { + var shadow: f32 = 1.0; + var stepSize: f32 = 0.3; // Adjust based on scene scale + var pos: vec3 = WorldPos; + for (var i: f32 = 0.0; i < 10.0; i += 1.0) { // Number of steps can be adjusted + pos += stepSize * LightDir; + shadow *= 1.0 - sampleCloudDensity(pos, Atmosphere); + if (shadow < 0.05) { + break; // Early exit for low shadow values + } + } + return shadow; +} + +// near: 0.01, far: 10000 +fn linearizeDepth(depth: f32, near: f32, far: f32) -> f32 { + var z: f32 = depth * 2.0 - 1.0; // Back to NDC + return (2.0 * near * far) / (far + near - z * (far - near)); +} + +fn IntegrateScatteredLuminance( + pixPos: vec2, + WorldPos: vec3, + WorldDir: vec3, + SunDir: vec3, + Atmosphere: AtmosphereParameters, + ground: bool, + SampleCountIni: f32, + DepthBufferValue: f32, + VariableSampleCount: bool, + MieRayPhase: bool, + tMaxMax: f32, + resolution: vec2 +) -> SingleScatteringResult { + var debugEnabled: bool = false; + var result: SingleScatteringResult = SingleScatteringResult(vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0)); + + var ClipSpace: vec3 = vec3((pixPos / resolution) * vec2(2.0, 2.0) - vec2(1.0, 1.0), 1.0); + + // Compute next intersection with atmosphere or ground + var earthO: vec3 = vec3(0.0, 0.0, 0.0); + var tBottom: f32 = raySphereIntersectNearest(WorldPos, WorldDir, earthO, Atmosphere.BottomRadius); + var tTop: f32 = raySphereIntersectNearest(WorldPos, WorldDir, earthO, Atmosphere.TopRadius); + var tMax: f32 = 0.0; + if tBottom < 0.0 { + if tTop < 0.0 { + tMax = 0.0; // No intersection with earth nor atmosphere: stop right away + return result; + } else { + tMax = tTop; + } + } else { + if tTop > 0.0 { + tMax = min(tTop, tBottom); + } + } + + if DepthBufferValue >= 0.0 { + ClipSpace.z = DepthBufferValue; + if ClipSpace.z < 1.0 { + // TODO: use uniformBuffer.invViewProjMatrix to get the world position + var DepthBufferWorldPos: vec4 = mat4x4() * vec4(ClipSpace, 1.0); + DepthBufferWorldPos /= DepthBufferWorldPos.w; + + var tDepth: f32 = length(DepthBufferWorldPos.xyz - (WorldPos + vec3(0.0, -Atmosphere.BottomRadius, 0.0))); // apply earth offset to go back to origin as top of earth mode. + tMax = min(tMax, tDepth); + } + } + tMax = min(tMax, tMaxMax); + + // Sample count + var SampleCount: f32 = SampleCountIni; + var SampleCountFloor: f32 = SampleCountIni; + var tMaxFloor: f32 = tMax; + if VariableSampleCount { + var spp: vec2 = RayMarchMinMaxSPP; + if uniformBuffer.enableClouds > 0.5 { + spp = RayMarchMinMaxSPPCloud; + } + SampleCount = mix(spp.x, spp.y, clamp(tMax * 0.01, 0.0, 1.0)); + SampleCountFloor = floor(SampleCount); + tMaxFloor = tMax * SampleCountFloor / SampleCount; // rescale tMax to map to the last entire step segment. + } + var dt: f32 = tMax / SampleCount; + + // Phase functions + var uniformPhase: f32 = 1.0 / (4.0 * PI); + var wi: vec3 = SunDir; + var wo: vec3 = WorldDir; + var cosTheta: f32 = dot(wi, wo); + var MiePhaseValue: f32 = hgPhase(Atmosphere.MiePhaseG, -cosTheta); // negate cosTheta because WorldDir is an "in" direction. + var RayleighPhaseValue: f32 = RayleighPhase(cosTheta); + var CloudPhaseValue: f32 = dualLobeHgPhase(Atmosphere.CloudPhaseG, cosTheta, Atmosphere.CloudK); + + // #ifdef ILLUMINANCE_IS_ONE + var globalL: vec3 = vec3(1.0); + // #else + // var globalL: vec3 = iSunIlluminance; + // #endif + + // Ray march the atmosphere to integrate optical depth + var L: vec3 = vec3(0.0); + var throughput: vec3 = vec3(1.0); + var OpticalDepth: vec3 = vec3(0.0); + var t: f32 = 0.0; + var tPrev: f32 = 0.0; + var SampleSegmentT: f32 = 0.3; + + // TODO: improve sampling and performance inside of the cloud layer + // compute the intersection points pointing in WorldDir direction + var tCloudBottom: f32 = raySphereIntersectNearest(WorldPos, WorldDir, earthO, Atmosphere.BottomRadius + Atmosphere.CloudBaseHeight); + var tCloudTop: f32 = raySphereIntersectNearest(WorldPos, WorldDir, earthO, Atmosphere.BottomRadius + Atmosphere.CloudTopHeight); + + // Ray marching loop + for (var s: f32 = 0.0; s < SampleCount; s += 1.0) { + if VariableSampleCount { + var t0: f32 = s / SampleCountFloor; + var t1: f32 = (s + 1.0) / SampleCountFloor; + t0 = t0 * t0; + t1 = t1 * t1; + t0 = tMaxFloor * t0; + if t1 > 1.0 { + t1 = tMax; + } else { + t1 = tMaxFloor * t1; + } + t = t0 + (t1 - t0) * SampleSegmentT; + dt = t1 - t0; + } else { + var NewT: f32 = tMax * (s + SampleSegmentT) / SampleCount; + dt = NewT - t; + t = NewT; + } + var P: vec3 = WorldPos + t * WorldDir; + + var medium: MediumSampleRGB = sampleMediumRGB(P, Atmosphere); + var SampleOpticalDepth: vec3 = medium.extinction * dt; + var SampleTransmittance: vec3 = exp(-SampleOpticalDepth); + OpticalDepth += SampleOpticalDepth; + + var pHeight: f32 = length(P); + var UpVector: vec3 = P / pHeight; + var SunZenithCosAngle: f32 = dot(SunDir, UpVector); + var uv = LutTransmittanceParamsToUv(Atmosphere, pHeight, SunZenithCosAngle); + var transmittanceTextureSize = vec2(textureDimensions(transmittanceTexture, 0)); + var transmittanceTextureCoord = vec2(transmittanceTextureSize * uv); + var TransmittanceToSun: vec3 = textureLoad(transmittanceTexture, transmittanceTextureCoord, 0).rgb; + + var PhaseTimesScattering: vec3; + if MieRayPhase { + PhaseTimesScattering = medium.scatteringMie * MiePhaseValue + medium.scatteringRay * RayleighPhaseValue + medium.scatteringCloud * MiePhaseValue; + } else { + PhaseTimesScattering = medium.scattering * uniformPhase; + } + + // Earth shadow + var tEarth: f32 = raySphereIntersectNearest(P, SunDir, earthO + PLANET_RADIUS_OFFSET * UpVector, Atmosphere.BottomRadius); + var earthShadow: f32 = 1.0; + if tEarth >= 0.0 { + earthShadow = 0.0; + } + + // Dual scattering for multi scattering + var multiScatteredLuminance: vec3 = vec3(0.0); + if MULTISCATAPPROX_ENABLED == 1 { + multiScatteredLuminance = GetMultipleScattering(Atmosphere, medium.scattering, medium.extinction, P, SunZenithCosAngle); + } + + var shadow: f32 = 1.0; + if SHADOWMAP_ENABLED == 1 { + shadow = getShadow(Atmosphere, P); + } + if VOLUMETRIC_SHADOW_ENABLED == 1 && uniformBuffer.enableClouds > 0.5 { + shadow = computeVolumetricShadow(P, SunDir, Atmosphere); + } + + var S: vec3 = globalL * (earthShadow * shadow * TransmittanceToSun * PhaseTimesScattering + multiScatteredLuminance * medium.scattering); + + if MULTI_SCATTERING_POWER_SERIE == 0 { + result.MultiScatAs1 += throughput * medium.scattering * 1.0 * dt; + } else { + var MS: vec3 = medium.scattering * 1.0; + var MSint: vec3 = (MS - MS * SampleTransmittance) / medium.extinction; + result.MultiScatAs1 += throughput * MSint; + } + + // Evaluate input to multi scattering + { + var newMS: vec3; + + newMS = earthShadow * TransmittanceToSun * medium.scattering * uniformPhase * 1.0; + result.NewMultiScatStep0Out += throughput * (newMS - newMS * SampleTransmittance) / medium.extinction; + + newMS = medium.scattering * uniformPhase * multiScatteredLuminance; + result.NewMultiScatStep1Out += throughput * (newMS - newMS * SampleTransmittance) / medium.extinction; + } + + var Sint: vec3 = (S - S * SampleTransmittance) / medium.extinction; + L += throughput * Sint; + throughput *= SampleTransmittance; + + tPrev = t; + } + + if ground && tMax == tBottom && tBottom > 0.0 { + // Account for bounced light off the earth + var P: vec3 = WorldPos + tBottom * WorldDir; + var pHeight: f32 = length(P); + var UpVector: vec3 = P / pHeight; + var NdotL: f32 = clamp(dot(normalize(UpVector), normalize(SunDir)), 0.0, 1.0); + var albedo: vec3 = Atmosphere.GroundAlbedo; + var TransmittanceToSun: vec3 = GetTransmittanceToSun(Atmosphere, P); + L += globalL * TransmittanceToSun * throughput * NdotL * albedo / PI; + } + + result.L = L; + result.OpticalDepth = OpticalDepth; + result.Transmittance = throughput; + return result; +} diff --git a/packages/atmosphere/shader/AtmosphericScatteringSky.wgsl b/packages/atmosphere/shader/AtmosphericScatteringSky.wgsl new file mode 100644 index 000000000..2bede0565 --- /dev/null +++ b/packages/atmosphere/shader/AtmosphericScatteringSky.wgsl @@ -0,0 +1,258 @@ +#include 'ColorUtil_frag' +#include 'AtmosphereUniforms' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture : texture_storage_2d; + +var uv01: vec2; +var fragCoord: vec2; +var texSizeF32: vec2; + +var PI:f32 = 3.1415926535; +var PI_2:f32 = 0.0; +var EPSILON:f32 = 0.0000001; +var SAMPLES_NUMS:i32 = 16; + +var transmittance:vec3; +var insctrMie:vec3; +var insctrRayleigh:vec3; + +@compute @workgroup_size( 8 , 8 , 1 ) +fn CsMain(@builtin(workgroup_id) workgroup_id: vec3, @builtin(global_invocation_id) globalInvocation_id: vec3) { + fragCoord = vec2(globalInvocation_id.xy); + texSizeF32 = vec2(uniformBuffer.width, uniformBuffer.height); + uv01 = vec2(globalInvocation_id.xy) / texSizeF32; + uv01.y = 1.0 - uv01.y - EPSILON; + PI_2 = PI * 2.0; + textureStore(outTexture, fragCoord, mainImage(uv01));//vec4(uv01, 0.0, 1.0)); +} + +struct ScatteringParams { + sunRadius: f32, + sunRadiance: f32, + + mieG: f32, + mieHeight: f32, + + rayleighHeight: f32, + + waveLambdaMie: vec3, + waveLambdaOzone: vec3, + waveLambdaRayleigh: vec3, + + earthRadius: f32, + earthAtmTopRadius: f32, + earthCenter: vec3, +} + +fn ComputeSphereNormal(coord: vec2, phiStart: f32, phiLength: f32, thetaStart: f32, thetaLength: f32) -> vec3 { + var normal: vec3; + normal.x = -sin(thetaStart + coord.y * thetaLength) * sin(phiStart + coord.x * phiLength); + normal.y = -cos(thetaStart + coord.y * thetaLength); + normal.z = -sin(thetaStart + coord.y * thetaLength) * cos(phiStart + coord.x * phiLength); + return normalize(normal); +} + +fn ComputeRaySphereIntersection(position: vec3, dir: vec3, center: vec3, radius: f32) -> vec2 { + var origin: vec3 = position - center; + var B = dot(origin, dir); + var C = dot(origin, origin) - radius * radius; + var D = B * B - C; + + var minimaxIntersections: vec2; + if D < 0.0 { + minimaxIntersections = vec2(-1.0, -1.0); + } else { + D = sqrt(D); + minimaxIntersections = vec2(-B - D, -B + D); + } + + return minimaxIntersections; +} + +fn ComputeWaveLambdaRayleigh(lambda: vec3) -> vec3 { + var n: f32 = 1.0003; + var N: f32 = 2.545E25; + var pn: f32 = 0.035; + var n2: f32 = n * n; + var pi3: f32 = PI * PI * PI; + var rayleighConst: f32 = (8.0 * pi3 * pow(n2 - 1.0, 2.0)) / (3.0 * N) * ((6.0 + 3.0 * pn) / (6.0 - 7.0 * pn)); + return vec3(rayleighConst) / (lambda * lambda * lambda * lambda); +} + +fn ComputePhaseMie(theta: f32, g: f32) -> f32 { + var g2 = g * g; + return (1.0 - g2) / pow(1.0 + g2 - 2.0 * g * saturate(theta), 1.5) / (4.0 * PI); +} + +fn ComputePhaseRayleigh(theta: f32) -> f32 { + var theta2 = theta * theta; + return (theta2 * 0.75 + 0.75) / (4.0 * PI); +} + +fn ChapmanApproximation(X: f32, h: f32, cosZenith: f32) -> f32 { + var c = sqrt(X + h); + var c_exp_h = c * exp(-h); + + if cosZenith >= 0.0 { + return c_exp_h / (c * cosZenith + 1.0); + } else { + var x0 = sqrt(1.0 - cosZenith * cosZenith) * (X + h); + var c0 = sqrt(x0); + + return 2.0 * c0 * exp(X - x0) - c_exp_h / (1.0 - c * cosZenith); + } +} + +fn GetOpticalDepthSchueler(h: f32, H: f32, earthRadius: f32, cosZenith: f32) -> f32 { + return H * ChapmanApproximation(earthRadius / H, h / H, cosZenith); +} + +fn GetTransmittance(setting: ScatteringParams, L: vec3, V: vec3) -> vec3 { + var ch = GetOpticalDepthSchueler(L.y, setting.rayleighHeight, setting.earthRadius, V.y); + return exp(-(setting.waveLambdaMie + setting.waveLambdaRayleigh) * ch); +} + +fn ComputeOpticalDepth(setting: ScatteringParams, samplePoint: vec3, V: vec3, L: vec3, neg: f32) -> vec2 { + var rl = length(samplePoint); + var h = rl - setting.earthRadius; + var r: vec3 = samplePoint / rl; + + var cos_chi_sun = dot(r, L); + var cos_chi_ray = dot(r, V * neg); + + var opticalDepthSun = GetOpticalDepthSchueler(h, setting.rayleighHeight, setting.earthRadius, cos_chi_sun); + var opticalDepthCamera = GetOpticalDepthSchueler(h, setting.rayleighHeight, setting.earthRadius, cos_chi_ray) * neg; + + return vec2(opticalDepthSun, opticalDepthCamera); +} + +fn AerialPerspective(setting: ScatteringParams, start: vec3, end: vec3, V: vec3, L: vec3, infinite: i32) { + var inf_neg: f32 = 1.0; + if infinite == 0 { + inf_neg = -1.0; + } + + var sampleStep: vec3 = (end - start) / f32(SAMPLES_NUMS); + var samplePoint: vec3 = end - sampleStep; + var sampleLambda: vec3 = setting.waveLambdaMie + setting.waveLambdaRayleigh + setting.waveLambdaOzone; + + var sampleLength: f32 = length(sampleStep); + + var scattering: vec3 = vec3(0.0); + var lastOpticalDepth: vec2 = ComputeOpticalDepth(setting, end, V, L, inf_neg); + + for (var i: i32 = 1; i < SAMPLES_NUMS; i = i + 1) { + var opticalDepth: vec2 = ComputeOpticalDepth(setting, samplePoint, V, L, inf_neg); + + var segment_s: vec3 = exp(-sampleLambda * (opticalDepth.x + lastOpticalDepth.x)); + var segment_t: vec3 = exp(-sampleLambda * (opticalDepth.y - lastOpticalDepth.y)); + + transmittance *= segment_t; + + scattering = scattering * segment_t; + scattering += exp(-(length(samplePoint) - setting.earthRadius) / setting.rayleighHeight) * segment_s; + + lastOpticalDepth = opticalDepth; + samplePoint = samplePoint - sampleStep; + } + + insctrMie = scattering * setting.waveLambdaMie * sampleLength; + insctrRayleigh = scattering * setting.waveLambdaRayleigh * sampleLength; +} + +fn ComputeSkyboxChapman(setting: ScatteringParams, eye: vec3, V: vec3, L: vec3) -> f32 { + var neg: i32 = 1; + var outerIntersections: vec2 = ComputeRaySphereIntersection(eye, V, setting.earthCenter, setting.earthAtmTopRadius); + if outerIntersections.y < 0.0 { + return 0.0; + } + var innerIntersections: vec2 = ComputeRaySphereIntersection(eye, V, setting.earthCenter, setting.earthRadius); + if innerIntersections.x > 0.0 { + neg = 0; + outerIntersections.y = innerIntersections.x; + } + + let eye0 = eye - setting.earthCenter; + + var start: vec3 = eye0 + V * max(0.0, outerIntersections.x); + var end: vec3 = eye0 + V * outerIntersections.y; + + AerialPerspective(setting, start, end, V, L, neg); + + //bool intersectionTest = innerIntersections.x < 0.0 && innerIntersections.y < 0.0; + //return intersectionTest ? 1.0 : 0.0; + + if innerIntersections.x < 0.0 && innerIntersections.y < 0.0 { + return 1.0; + } + return 0.0; +} + +fn ComputeSkyInscattering(setting: ScatteringParams, eye: vec3, V: vec3, L: vec3) -> vec4 { + transmittance = vec3(1.0); + insctrMie = vec3(0.0); + insctrRayleigh = vec3(0.0); + var intersectionTest: f32 = ComputeSkyboxChapman(setting, eye, V, L); + + var phaseTheta = dot(V, L); + var phaseMie = ComputePhaseMie(phaseTheta, setting.mieG); + var phaseRayleigh = ComputePhaseRayleigh(phaseTheta); + var phaseNight = 1.0 - saturate(transmittance.x * EPSILON); + + var insctrTotalMie: vec3 = insctrMie * phaseMie; + var insctrTotalRayleigh: vec3 = insctrRayleigh * phaseRayleigh; + + var sky: vec3 = (insctrTotalMie + insctrTotalRayleigh) * setting.sunRadiance; + if uniformBuffer.displaySun > 0.5 { + var angle: f32 = saturate((1.0 - phaseTheta) * setting.sunRadius); + var cosAngle: f32 = cos(angle * PI * 0.5); + var edge: f32 = 0.0; + if angle >= 0.9 { + edge = smoothstep(0.9, 1.0, angle); + } + + var limbDarkening: vec3 = GetTransmittance(setting, -L, V); + limbDarkening *= pow(vec3(cosAngle), vec3(0.420, 0.503, 0.652)) * mix(vec3(1.0), vec3(1.2, 0.9, 0.5), edge) * intersectionTest; + sky += limbDarkening * uniformBuffer.sunBrightness; + } + return vec4(sky, phaseNight * intersectionTest); +} + +fn noise(uv: vec2) -> f32 { + return fract(dot(sin(vec3(uv.xyx) * vec3(uv.xyy) * 1024.0), vec3(341896.483, 891618.637, 602649.7031))); +} + +fn mainImage(uv: vec2) -> vec4 { + let eyePosition = uniformBuffer.eyePos; + var sun = vec2(uniformBuffer.sunU, uniformBuffer.sunV); + var V: vec3 = ComputeSphereNormal(uv, 0.0, PI_2, 0.0, PI); + var L: vec3 = ComputeSphereNormal(vec2(sun.x, sun.y), 0.0, PI_2, 0.0, PI); + + var setting: ScatteringParams; + setting.sunRadius = uniformBuffer.sunRadius;//500.0; + setting.sunRadiance = uniformBuffer.sunRadiance;//20.0; + setting.mieG = uniformBuffer.mieG;//0.76; + setting.mieHeight = uniformBuffer.mieHeight;// 1200.0; + setting.rayleighHeight = 8000.0; + setting.earthRadius = 6360000.0; + setting.earthAtmTopRadius = 6420000.0; + setting.earthCenter = vec3(0, -setting.earthRadius, 0); + setting.waveLambdaMie = vec3(0.0000002); + + // wavelength with 680nm, 550nm, 450nm + setting.waveLambdaRayleigh = ComputeWaveLambdaRayleigh(vec3(0.000000680, 0.000000550, 0.000000450)); + + // see https://www.shadertoy.com/view/MllBR2 + setting.waveLambdaOzone = vec3(1.36820899679147, 3.31405330400124, 0.13601728252538) * 0.0000006 * 2.504; + + var eye: vec3 = vec3(0, eyePosition, 0); + var sky0: vec4 = ComputeSkyInscattering(setting, eye, V, L); + var sky = vec3(sky0.rgb); + + sky = ACESToneMapping(sky.rgb, uniformBuffer.hdrExposure); + sky = pow(sky.rgb, vec3(1.0 / 1.2)); // gamma + + var fragColor: vec4 = vec4((sky.rgb), 1.0); + return fragColor; +} \ No newline at end of file diff --git a/packages/atmosphere/shader/AtmosphericScatteringSky_shader.ts b/packages/atmosphere/shader/AtmosphericScatteringSky_shader.ts new file mode 100644 index 000000000..7b2c4ee26 --- /dev/null +++ b/packages/atmosphere/shader/AtmosphericScatteringSky_shader.ts @@ -0,0 +1,44 @@ +import { ShaderLib } from "@orillusion/core"; +import source from "./AtmosphericScatteringSky.wgsl?raw"; +import transmittance from "./RenderTransmittanceLutPS.wgsl?raw"; +import integration from "./AtmosphericScatteringIntegration.wgsl?raw"; +import multiscatter from "./NewMultiScattCS.wgsl?raw"; +import earth from "./AtmosphereEarth.wgsl?raw"; +import uniforms from "./AtmosphereUniforms.wgsl?raw"; +import raymarch from "./RenderSkyRayMarching.wgsl?raw"; +import skyview from "./SkyViewLutPS.wgsl?raw"; +import cloud from "./CloudNoise.wgsl?raw"; + +/** + * @internal + */ +export class AtmosphericScatteringSky_shader { + /** Legacy (Chapman-approximation) single-pass sky, kept behind `showV1`. */ + public static cs: string = source; + public static transmittance_cs: string = transmittance; + public static multiscatter_cs: string = multiscatter; + public static integration: string = integration; + public static raymarch_cs: string = raymarch; + public static skyview_cs: string = skyview; + public static earth: string = earth; + public static uniforms: string = uniforms; + public static cloud_cs: string = cloud; + + /** + * Publish the WGSL chunks the compute kernels above `#include`. + * + * ComputeShader expands `#include` in its constructor (ShaderReflection + * runs the Preprocessor there), so the chunks must already be in + * ShaderLib before the first AtmosphericScatteringSky is built — hence + * the module-scope call below rather than a component hook. + * `ShaderLib.register` overwrites by key, so repeat calls are harmless + * and multiple Engine3D instances share one registry. + */ + public static register(): void { + ShaderLib.register('AtmosphericScatteringIntegration', AtmosphericScatteringSky_shader.integration); + ShaderLib.register('AtmosphereEarth', AtmosphericScatteringSky_shader.earth); + ShaderLib.register('AtmosphereUniforms', AtmosphericScatteringSky_shader.uniforms); + } +} + +AtmosphericScatteringSky_shader.register(); diff --git a/packages/atmosphere/shader/CloudNoise.wgsl b/packages/atmosphere/shader/CloudNoise.wgsl new file mode 100644 index 000000000..b624359a6 --- /dev/null +++ b/packages/atmosphere/shader/CloudNoise.wgsl @@ -0,0 +1,45 @@ +#include 'AtmosphereUniforms' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture: texture_storage_2d; + +var uv01: vec2; +var fragCoord: vec2; +var texSizeF32: vec2; +var PI: f32 = 3.1415926535897932384626433832795; +var PI_2: f32 = 0.0; +var EPSILON:f32 = 0.0000001; + +@compute @workgroup_size(8, 8, 1) +fn CsMain(@builtin(workgroup_id) workgroup_id: vec3, @builtin(global_invocation_id) globalInvocation_id: vec3) { + fragCoord = vec2(globalInvocation_id.xy); + texSizeF32 = vec2(uniformBuffer.width, uniformBuffer.height); + uv01 = vec2(globalInvocation_id.xy) / texSizeF32; + uv01.y = 1.0 - uv01.y - EPSILON; + PI_2 = PI * 2.0; + uv01 *= vec2(10., 10.); + var coord = vec3(uv01, 1.0); + var noiseValue = 1. - worleyNoise3D(coord); + var outColor = vec4(noiseValue, noiseValue, noiseValue, 1.); + textureStore(outTexture, fragCoord, outColor); +} + +fn worleyNoise3D(pos: vec3) -> f32 { + var minDist: f32 = 1.0; // Large number to start with + for (var z: i32 = -1; z <= 1; z++) { + for (var y: i32 = -1; y <= 1; y++) { + for (var x: i32 = -1; x <= 1; x++) { + var cell = floor(pos) + vec3(f32(x), f32(y), f32(z)); + var point = cell + hash3D(cell); // hash3D is a function you need to define + var dist = distance(pos, point); + minDist = min(minDist, dist); + } + } + } + return minDist; +} + +fn hash3D(p: vec3) -> vec3 { + // Simple hash function, replace with a better one if needed + return fract(sin(vec3(dot(p, vec3(127.1, 311.7, 74.7)), dot(p, vec3(269.5, 183.3, 246.1)), dot(p, vec3(113.5, 271.9, 124.6)))) * 43758.5453); +} \ No newline at end of file diff --git a/packages/atmosphere/shader/NewMultiScattCS.wgsl b/packages/atmosphere/shader/NewMultiScattCS.wgsl new file mode 100644 index 000000000..d653d5d27 --- /dev/null +++ b/packages/atmosphere/shader/NewMultiScattCS.wgsl @@ -0,0 +1,127 @@ +#include 'AtmosphereEarth' +#include 'AtmosphericScatteringIntegration' +#include 'AtmosphereUniforms' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture: texture_storage_2d; +@group(0) @binding(auto) var transmittanceTexture: texture_2d; +@group(0) @binding(auto) var transmittanceTextureSampler: sampler; +@group(0) @binding(auto) var multipleScatteringTexture: texture_2d; +@group(0) @binding(auto) var multipleScatteringTextureSampler: sampler; +@group(0) @binding(auto) var cloudTextureSampler: sampler; +@group(0) @binding(auto) var cloudTexture: texture_2d; + +var MultiScatAs1SharedMem: array, 64>; +var LSharedMem: array, 64>; + +var PI: f32 = 3.1415926535897932384626433832795; +var PI_2: f32 = 0.0; +var EPSILON: f32 = 0.0000001; +// var MULTI_SCATTERING_POWER_SERIE: u32 = 1; +var SQRTSAMPLECOUNT: u32 = 8; + +var MultipleScatteringFactor: f32 = 1.0; // change to 50 to see the texture + +@compute @workgroup_size(1, 1, 64) +fn CsMain(@builtin(global_invocation_id) ThreadId: vec3) { + var texSize = vec2(uniformBuffer.width, uniformBuffer.height); + var pixPos: vec2 = vec2(ThreadId.xy) + 0.5; + var uv: vec2 = pixPos / MultiScatteringLUTRes; + + uv = vec2(fromSubUvsToUnit(uv.x, MultiScatteringLUTRes), fromSubUvsToUnit(1. - uv.y, MultiScatteringLUTRes)); + + var Atmosphere: AtmosphereParameters = GetAtmosphereParameters(); + + var cosSunZenithAngle: f32 = uv.x * 2.0 - 1.0; + var sunDir: vec3 = vec3(0.0, sqrt(saturate(1.0 - cosSunZenithAngle * cosSunZenithAngle)), cosSunZenithAngle); + var viewHeight: f32 = Atmosphere.BottomRadius + saturate(uv.y + PLANET_RADIUS_OFFSET) * (Atmosphere.TopRadius - Atmosphere.BottomRadius - PLANET_RADIUS_OFFSET); + + var WorldPos: vec3 = vec3(0.0, 0.0, viewHeight); + var WorldDir: vec3 = vec3(0.0, 0.0, 1.0); + + const ground: bool = true; + const SampleCountIni: f32 = 20.0; + const DepthBufferValue: f32 = -1.0; + const VariableSampleCount: bool = false; + const MieRayPhase: bool = false; + + var SphereSolidAngle: f32 = 4.0 * PI; + var IsotropicPhase: f32 = 1.0 / SphereSolidAngle; + + + var sqrtSample: f32 = f32(SQRTSAMPLECOUNT); + var i: f32 = 0.5 + f32(ThreadId.z / SQRTSAMPLECOUNT); + var j: f32 = 0.5 + f32(ThreadId.z - u32(f32(ThreadId.z / SQRTSAMPLECOUNT) * f32(SQRTSAMPLECOUNT))); + { + var randA: f32 = i / sqrtSample; + var randB: f32 = j / sqrtSample; + var theta: f32 = 2.0 * PI * randA; + var phi: f32 = acos(1.0 - 2.0 * randB); + var cosPhi: f32 = cos(phi); + var sinPhi: f32 = sin(phi); + var cosTheta: f32 = cos(theta); + var sinTheta: f32 = sin(theta); + WorldDir.x = cosTheta * sinPhi; + WorldDir.y = sinTheta * sinPhi; + WorldDir.z = cosPhi; + var result: SingleScatteringResult = IntegrateScatteredLuminance(pixPos, WorldPos, WorldDir, sunDir, Atmosphere, ground, SampleCountIni, DepthBufferValue, VariableSampleCount, MieRayPhase, defaultTMaxMax, texSize); + + MultiScatAs1SharedMem[ThreadId.z] = result.MultiScatAs1 * SphereSolidAngle / (sqrtSample * sqrtSample); + LSharedMem[ThreadId.z] = result.L * SphereSolidAngle / (sqrtSample * sqrtSample); + } + + workgroupBarrier(); + + if ThreadId.z < 32 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 32]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 32]; + } + workgroupBarrier(); + + if ThreadId.z < 16 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 16]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 16]; + } + workgroupBarrier(); + + if ThreadId.z < 8 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 8]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 8]; + } + workgroupBarrier(); + if ThreadId.z < 4 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 4]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 4]; + } + workgroupBarrier(); + if ThreadId.z < 2 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 2]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 2]; + } + workgroupBarrier(); + if ThreadId.z < 1 { + MultiScatAs1SharedMem[ThreadId.z] += MultiScatAs1SharedMem[ThreadId.z + 1]; + LSharedMem[ThreadId.z] += LSharedMem[ThreadId.z + 1]; + } + workgroupBarrier(); + if ThreadId.z > 0 { + return; + } + + var MultiScatAs1: vec3 = MultiScatAs1SharedMem[0] * IsotropicPhase; + var InScatteredLuminance: vec3 = LSharedMem[0] * IsotropicPhase; + + var L: vec3 = vec3(0.0, 0.0, 0.0); + if MULTI_SCATTERING_POWER_SERIE == 0 { + var MultiScatAs1SQR: vec3 = MultiScatAs1 * MultiScatAs1; + L = InScatteredLuminance * (1.0 + MultiScatAs1 + MultiScatAs1SQR + MultiScatAs1 * MultiScatAs1SQR + MultiScatAs1SQR * MultiScatAs1SQR); + } else { + var r: vec3 = MultiScatAs1; + var SumOfAllMultiScatteringEventsContribution: vec3 = 1.0 / (1.0 - r); + L = InScatteredLuminance * SumOfAllMultiScatteringEventsContribution; + } + + var fragColor = vec4(MultipleScatteringFactor * L, 1.0); + var fragCoord = vec2(ThreadId.xy); + textureStore(outTexture, fragCoord, fragColor); +} diff --git a/packages/atmosphere/shader/RenderSkyRayMarching.wgsl b/packages/atmosphere/shader/RenderSkyRayMarching.wgsl new file mode 100644 index 000000000..1ceb25dfc --- /dev/null +++ b/packages/atmosphere/shader/RenderSkyRayMarching.wgsl @@ -0,0 +1,110 @@ +#include 'AtmosphereEarth' +#include 'AtmosphericScatteringIntegration' +#include 'AtmosphereUniforms' +#include 'ColorUtil_frag' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture: texture_storage_2d; + +@group(0) @binding(auto) var multipleScatteringTexture: texture_2d; +@group(0) @binding(auto) var multipleScatteringTextureSampler: sampler; + +@group(0) @binding(auto) var transmittanceTexture: texture_2d; +@group(0) @binding(auto) var transmittanceTextureSampler: sampler; + +@group(0) @binding(auto) var cloudTextureSampler: sampler; +@group(0) @binding(auto) var cloudTexture: texture_2d; + +var uv01: vec2; +var fragCoord: vec2; +var texSize: vec2; + +var PI: f32 = 3.1415926535897932384626433832795; +var PI_2: f32 = 0.0; +var EPSILON: f32 = 0.0000001; +var IS_HDR_SKY = false; + +@compute @workgroup_size(8, 8, 1) +fn CsMain(@builtin(global_invocation_id) ThreadId: vec3) { + fragCoord = vec2(ThreadId.xy); + texSize = vec2(uniformBuffer.width, uniformBuffer.height); + uv01 = vec2(ThreadId.xy) / texSize; + uv01.y = 1.0 - uv01.y - EPSILON; + PI_2 = PI * 2.0; + textureStore(outTexture, fragCoord, mainImage(uv01, vec2(fragCoord))); +} + +fn mainImage(uv: vec2, pixPos: vec2) -> vec4 { + var coords = vec2(uv * vec2(textureDimensions(multipleScatteringTexture, 0))); + var sampleA = textureSampleLevel(multipleScatteringTexture, multipleScatteringTextureSampler, uv, 0).rgb; + + coords = vec2(uv * vec2(textureDimensions(transmittanceTexture, 0))); + var sampleB = textureSampleLevel(transmittanceTexture, transmittanceTextureSampler, uv, 0).rgb; + + // sample the cloud texture + coords = vec2(uv * vec2(textureDimensions(cloudTexture, 0))); + var sampleC = textureSampleLevel(cloudTexture, cloudTextureSampler, uv, 0).rgb; + + var Atmosphere: AtmosphereParameters = GetAtmosphereParameters(); + + var eyePosition = uniformBuffer.eyePos; + var sun = vec2(uniformBuffer.sunU, uniformBuffer.sunV); + var WorldDir: vec3 = ComputeSphereNormal(uv, 0.0, PI_2, 0.0, PI); + var SunDir: vec3 = ComputeSphereNormal(vec2(sun.x, sun.y), 0.0, PI_2, 0.0, PI); + var WorldPos = vec3(0, Atmosphere.BottomRadius + eyePosition/1000.0 + 0.01, 0); + + const ground = false; + const SampleCountIni = 30.0; + const DepthBufferValue = -1.0; + const VariableSampleCount = true; + const MieRayPhase = true; + var result: SingleScatteringResult = IntegrateScatteredLuminance(pixPos, WorldPos, WorldDir, SunDir, Atmosphere, ground, SampleCountIni, DepthBufferValue, VariableSampleCount, MieRayPhase, defaultTMaxMax, texSize); + + var L: vec3 = result.L; + + // The ray march only integrates in-scattering, so the sun disc itself has + // to be added on top. `result.Transmittance` is the extinction the view ray + // already accumulated out to the top of the atmosphere, which is exactly + // what reddens the disc at sunrise/sunset. + if uniformBuffer.displaySun > 0.5 { + L += GetSunDisc(WorldPos, WorldDir, SunDir, Atmosphere) * result.Transmittance; + } + + // for HDR lighting + var sky: vec3; + if (IS_HDR_SKY) { + sky = LinearToGammaSpace(L) * uniformBuffer.hdrExposure; + } else { + // for LDR lighting + sky = ACESToneMapping(L.rgb, uniformBuffer.hdrExposure); + sky = pow(sky.rgb, vec3(1.0/1.2)); // gamma + } + + return vec4(sky, 1.0); +} + +/** + * Limb-darkened sun disc, parameterised exactly like the legacy V1 sky so the + * sunRadius / sunBrightness sliders behave the same on both paths: sunRadius + * is an inverse angular size (bigger value -> smaller disc). + */ +fn GetSunDisc(WorldPos: vec3, WorldDir: vec3, SunDir: vec3, Atmosphere: AtmosphereParameters) -> vec3 { + // Planet occludes the disc when the view ray hits the ground first. + var tGround: f32 = raySphereIntersectNearest(WorldPos, WorldDir, vec3(0.0, 0.0, 0.0), Atmosphere.BottomRadius); + if tGround >= 0.0 { + return vec3(0.0); + } + + var cosTheta: f32 = dot(WorldDir, SunDir); + var angle: f32 = saturate((1.0 - cosTheta) * uniformBuffer.sunRadius); + if angle >= 1.0 { + return vec3(0.0); + } + + var cosAngle: f32 = cos(angle * PI * 0.5); + var edge: f32 = smoothstep(0.9, 1.0, angle); + var limbDarkening: vec3 = pow(vec3(cosAngle), vec3(0.420, 0.503, 0.652)); + limbDarkening *= mix(vec3(1.0), vec3(1.2, 0.9, 0.5), edge); + + return limbDarkening * uniformBuffer.sunBrightness; +} \ No newline at end of file diff --git a/packages/atmosphere/shader/RenderTransmittanceLutPS.wgsl b/packages/atmosphere/shader/RenderTransmittanceLutPS.wgsl new file mode 100644 index 000000000..0ad8c1bf5 --- /dev/null +++ b/packages/atmosphere/shader/RenderTransmittanceLutPS.wgsl @@ -0,0 +1,76 @@ +#include 'AtmosphereEarth' +#include 'AtmosphericScatteringIntegration' +#include 'AtmosphereUniforms' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture: texture_storage_2d; +@group(0) @binding(auto) var transmittanceTexture: texture_2d; +@group(0) @binding(auto) var transmittanceTextureSampler: sampler; +@group(0) @binding(auto) var multipleScatteringTexture: texture_2d; +@group(0) @binding(auto) var multipleScatteringTextureSampler: sampler; +@group(0) @binding(auto) var cloudTextureSampler: sampler; +@group(0) @binding(auto) var cloudTexture: texture_2d; + +var uv01: vec2; +var fragCoord: vec2; +var texSizeF32: vec2; +var PI: f32 = 3.1415926535897932384626433832795; +var PI_2: f32 = 0.0; +var EPSILON:f32 = 0.0000001; + +@compute @workgroup_size(8 , 8 , 1) +fn CsMain(@builtin(workgroup_id) workgroup_id: vec3, @builtin(global_invocation_id) globalInvocation_id: vec3) { + fragCoord = vec2(globalInvocation_id.xy); + texSizeF32 = vec2(uniformBuffer.width, uniformBuffer.height); + uv01 = vec2(globalInvocation_id.xy) / texSizeF32; + uv01.y = 1.0 - uv01.y - EPSILON; + PI_2 = PI * 2.0; + textureStore(outTexture, fragCoord, RenderTransmittanceLutPS(vec2(fragCoord), uv01));//vec4(uv01, 0.0, 1.0)); +} + +struct UvToLutResult { + viewHeight: f32, + viewZenithCosAngle: f32, +}; + +fn UvToLutTransmittanceParams(Atmosphere: AtmosphereParameters, uv: vec2) -> UvToLutResult { + var result: UvToLutResult; + + var x_mu: f32 = uv.x; + var x_r: f32 = uv.y; + + var H: f32 = sqrt(Atmosphere.TopRadius * Atmosphere.TopRadius - Atmosphere.BottomRadius * Atmosphere.BottomRadius); + var rho: f32 = H * x_r; + result.viewHeight = sqrt(rho * rho + Atmosphere.BottomRadius * Atmosphere.BottomRadius); + + var d_min: f32 = Atmosphere.TopRadius - result.viewHeight; + var d_max: f32 = rho + H; + var d: f32 = d_min + x_mu * (d_max - d_min); + result.viewZenithCosAngle = (H * H - rho * rho - d * d) / (2.0 * result.viewHeight * d); + if d == 0.0 { + result.viewZenithCosAngle = 1.0; + } + result.viewZenithCosAngle = clamp(result.viewZenithCosAngle, -1.0, 1.0); + + return result; +} + +fn RenderTransmittanceLutPS(pixPos: vec2, uv: vec2) -> vec4 { + var Atmosphere: AtmosphereParameters = GetAtmosphereParameters(); + var transmittanceParams: UvToLutResult = UvToLutTransmittanceParams(Atmosphere, uv); + + var WorldPos: vec3 = vec3(0.0, 0.0, transmittanceParams.viewHeight); + var WorldDir: vec3 = vec3(0.0, sqrt(1.0 - transmittanceParams.viewZenithCosAngle * transmittanceParams.viewZenithCosAngle), transmittanceParams.viewZenithCosAngle); + + var ground = false; + var SampleCountIni = 40.0; // Can go a low as 10 sample but energy lost starts to be visible. + var DepthBufferValue = -1.0; + var VariableSampleCount = false; + var MieRayPhase = false; + + var scatteringResult: SingleScatteringResult = IntegrateScatteredLuminance(pixPos, WorldPos, WorldDir, getSunDirection(), Atmosphere, ground, SampleCountIni, DepthBufferValue, VariableSampleCount, MieRayPhase, defaultTMaxMax, texSizeF32); + var transmittance: vec3 = exp(-scatteringResult.OpticalDepth); + + // Optical depth to transmittance + return vec4(transmittance, 1.0); +} diff --git a/packages/atmosphere/shader/SkyViewLutPS.wgsl b/packages/atmosphere/shader/SkyViewLutPS.wgsl new file mode 100644 index 000000000..10228577f --- /dev/null +++ b/packages/atmosphere/shader/SkyViewLutPS.wgsl @@ -0,0 +1,121 @@ +#include 'AtmosphereEarth' +#include 'AtmosphericScatteringIntegration' +#include 'AtmosphereUniforms' + +@group(0) @binding(0) var uniformBuffer: UniformData; +@group(0) @binding(1) var outTexture: texture_storage_2d; +@group(0) @binding(auto) var transmittanceTexture: texture_2d; +@group(0) @binding(auto) var transmittanceTextureSampler: sampler; +@group(0) @binding(auto) var multipleScatteringTexture: texture_2d; +@group(0) @binding(auto) var multipleScatteringTextureSampler: sampler; +@group(0) @binding(auto) var cloudTextureSampler: sampler; +@group(0) @binding(auto) var cloudTexture: texture_2d; + +var uv01: vec2; +var fragCoord: vec2; +var texSize: vec2; +var PI: f32 = 3.1415926535897932384626433832795; +var PI_2: f32 = 0.0; +var EPSILON:f32 = 0.0000001; +var NONLINEARSKYVIEWLUT: bool = true; + +@compute @workgroup_size(8, 8, 1) +fn CsMain(@builtin(workgroup_id) workgroup_id: vec3, @builtin(global_invocation_id) globalInvocation_id: vec3) { + fragCoord = vec2(globalInvocation_id.xy); + texSize = vec2(uniformBuffer.width, uniformBuffer.height); + uv01 = vec2(globalInvocation_id.xy) / texSize; + uv01.y = 1.0 - uv01.y - EPSILON; + PI_2 = PI * 2.0; + textureStore(outTexture, fragCoord, SkyViewLutPS(vec2(fragCoord), uv01));//vec4(uv01, 0.0, 1.0)); +} + +fn UvToSkyViewLutParams(Atmosphere: AtmosphereParameters, viewHeight: f32, uv0: vec2) -> vec2 { + // Constrain uvs to valid sub texel range (avoid zenith derivative issue making LUT usage visible) + var uv = vec2(fromSubUvsToUnit(uv0.x, 192.0), fromSubUvsToUnit(uv0.y, 108.0)); + + var Vhorizon: f32 = sqrt(viewHeight * viewHeight - Atmosphere.BottomRadius * Atmosphere.BottomRadius); + var CosBeta: f32 = Vhorizon / viewHeight; // GroundToHorizonCos + var Beta: f32 = acos(CosBeta); + var ZenithHorizonAngle: f32 = PI - Beta; + var viewZenithCosAngle: f32; + + if uv.y < 0.5 { + var coord: f32 = 2.0 * uv.y; + coord = 1.0 - coord; + if NONLINEARSKYVIEWLUT { + coord = coord * coord; + } + coord = 1.0 - coord; + viewZenithCosAngle = cos(ZenithHorizonAngle * coord); + } else { + var coord: f32 = uv.y * 2.0 - 1.0; + if NONLINEARSKYVIEWLUT { + coord = coord * coord; + } + viewZenithCosAngle = cos(ZenithHorizonAngle + Beta * coord); + } + + var coord: f32 = uv.x; + coord = coord * coord; + var lightViewCosAngle: f32 = -(coord * 2.0 - 1.0); + + return vec2(viewZenithCosAngle, lightViewCosAngle); +} + + +fn SkyViewLutPS(pixPos: vec2, uv: vec2) -> vec4 { + var Atmosphere: AtmosphereParameters = GetAtmosphereParameters(); + + // var ClipSpace: vec3 = vec3((pixPos / vec2(192.0, 108.0)) * vec2(2.0, -2.0) - vec2(1.0, -1.0), 1.0); + // var HViewPos: vec4 = uniformBuffer.skyInvProjMat * vec4(ClipSpace, 1.0); + // var m = uniformBuffer.skyInvViewMat; + // var WorldDir: vec3 = normalize((mat3x3(m[0].xyz, m[1].xyz, m[2].xyz) * HViewPos.xyz) / HViewPos.w); + var WorldPos: vec3 = vec3(0, Atmosphere.BottomRadius + uniformBuffer.eyePos + 0.01, 0); + + var viewHeight: f32 = length(WorldPos); + + var lutParams = UvToSkyViewLutParams(Atmosphere, viewHeight, uv); + var viewZenithCosAngle: f32 = lutParams.x; + var lightViewCosAngle: f32 = lutParams.y; + + var sun = vec2(uniformBuffer.sunU, uniformBuffer.sunV); + var sun_direction: vec3 = ComputeSphereNormal(vec2(sun.x, sun.y), 0.0, PI_2, 0.0, PI); + + var SunDir: vec3; + { + var UpVector: vec3 = WorldPos / viewHeight; + var sunZenithCosAngle: f32 = dot(UpVector, sun_direction); + SunDir = normalize(vec3(sqrt(1.0 - sunZenithCosAngle * sunZenithCosAngle), 0.0, sunZenithCosAngle)); + } + + WorldPos = vec3(0.0, 0.0, viewHeight); + + var viewZenithSinAngle: f32 = sqrt(1.0 - viewZenithCosAngle * viewZenithCosAngle); + var WorldDir = vec3( + viewZenithSinAngle * lightViewCosAngle, + viewZenithSinAngle * sqrt(1.0 - lightViewCosAngle * lightViewCosAngle), + viewZenithCosAngle + ); + + // Move to top atmosphere + if !MoveToTopAtmosphere(&WorldPos, WorldDir, Atmosphere.TopRadius) { + // Ray is not intersecting the atmosphere + return vec4(0.0, 0.0, 0.0, 1.0); + } + + const ground: bool = false; + const SampleCountIni: f32 = 30.0; + const DepthBufferValue: f32 = -1.0; + const VariableSampleCount: bool = true; + const MieRayPhase: bool = true; + var texSize = vec2(uniformBuffer.width, uniformBuffer.height); + var ss: SingleScatteringResult = IntegrateScatteredLuminance( + pixPos, WorldPos, WorldDir, SunDir, Atmosphere, + ground, SampleCountIni, DepthBufferValue, VariableSampleCount, + MieRayPhase, defaultTMaxMax, texSize + ); + + var L: vec3 = ss.L; + + return vec4(L, 1.0); +} diff --git a/packages/atmosphere/textures/AtmosphericScatteringSky.ts b/packages/atmosphere/textures/AtmosphericScatteringSky.ts new file mode 100644 index 000000000..a5a1a36e4 --- /dev/null +++ b/packages/atmosphere/textures/AtmosphericScatteringSky.ts @@ -0,0 +1,338 @@ +import { AtmosphericScatteringSky_shader } from '../shader/AtmosphericScatteringSky_shader'; +import { + Engine3D, + Vector3, + Color, + Context3D, + HDRTextureCube, + Texture, + ComputeShader, + UniformGPUBuffer, + VirtualTexture, + GPUTextureFormat, + GPUAddressMode +} from "@orillusion/core"; + +/** + * AtmosphericScattering Sky Setting + * @group Texture + */ +export class AtmosphericScatteringSkySetting { + /** Angular size of the sun disc. */ + public sunRadius: number = 500.0; + /** Radiance (brightness) of the sun. */ + public sunRadiance: number = 11.0; + /** Mie scattering anisotropy factor (forward-scattering bias). */ + public mieG: number = 0.76; + /** Scale height of the Mie (aerosol) layer. */ + public mieHeight: number = 1200; + /** Height of the viewer's eye above the planet surface, in meters. */ + public eyePos: number = 1500; + /** Sun direction's horizontal (azimuth) parameter, in [0, 1]. */ + public sunX: number = 0.71; + /** Sun direction's vertical (elevation) parameter, in [0, 1]. */ + public sunY: number = 0.56; + /** Overall brightness multiplier applied to the sun. */ + public sunBrightness: number = 1.0; + /** Whether the sun disc is drawn in the sky. */ + public displaySun: boolean = true; + /** Whether the volumetric cloud layer is ray-marched into the sky. */ + public enableClouds: boolean = true; + /** Render the legacy Chapman-approximation sky instead of the LUT chain. */ + public showV1: boolean = false; + /** Default edge size of the generated sky cube texture. */ + public defaultTextureCubeSize: number = 512; + /** Default width of the generated panorama 2D texture. */ + public defaultTexture2DSize: number = 1024; + /** Tint color applied to the sky. */ + public skyColor: Color = new Color(1, 1, 1, 1); + /** Exposure fed to the tonemap / gamma step of the sky kernel. */ + public hdrExposure: number = 2; +} + +/** + * Physically based atmospheric scattering sky texture. + * + * Bakes a Hillaire-style LUT chain — transmittance, multiple scattering, sky + * view and a Worley cloud noise — and ray-marches them into an equirect + * panorama, which is then projected onto the cube faces used as the skybox + * and the scene environment map. + * + * @group Texture + */ +export class AtmosphericScatteringSky extends HDRTextureCube { + private _transmittanceLut: TransmittanceTexture2D; + private _multipleScatteringLut: MultipleScatteringTexture2D; + private _skyTexture: SkyTexture2D; + private _skyViewLut: SkyViewTexture2D; + private _cloudNoiseTexture: CloudNoiseTexture2D; + private _cubeSize: number; + /** The scattering parameters driving this sky's appearance. */ + public readonly setting: AtmosphericScatteringSkySetting; + private _internalTexture: AtmosphericTexture; + + /** + * @constructor + * @param setting AtmosphericScatteringSkySetting + * @param ctx the Context3D this sky's GPU resources belong to. Required + * when more than one Engine3D is alive — every texture, compute + * shader and uniform buffer below binds to exactly one device. + * @returns + */ + constructor(setting: AtmosphericScatteringSkySetting, ctx?: Context3D) { + super(); + this.setting = setting; + this.isHDRTexture = true; + this._cubeSize = setting.defaultTextureCubeSize; + + this._internalTexture = new AtmosphericTexture(setting.defaultTexture2DSize, setting.defaultTexture2DSize * 0.5, AtmosphericScatteringSky_shader.cs, null, ctx); + this._internalTexture.isHDRTexture = true; + this._internalTexture.updateUniforms(this.setting); + this._internalTexture.update(); + + this._cloudNoiseTexture = new CloudNoiseTexture2D(64, 64, ctx); + this._cloudNoiseTexture.updateUniforms(this.setting); + this._cloudNoiseTexture.update(); + + this._transmittanceLut = new TransmittanceTexture2D(256, 64, ctx); + this._transmittanceLut.updateUniforms(this.setting); + this._transmittanceLut.update(); + + this._multipleScatteringLut = new MultipleScatteringTexture2D(32, 32, ctx); + this._multipleScatteringLut.updateUniforms(this.setting); + this._multipleScatteringLut.updateTransmittance(this._transmittanceLut, this._cloudNoiseTexture); + this._multipleScatteringLut.update(); + + this._skyViewLut = new SkyViewTexture2D(192, 108, ctx); + this._skyViewLut.updateUniforms(this.setting); + this._skyViewLut.updateTextures(this._transmittanceLut, this._multipleScatteringLut, this._cloudNoiseTexture); + this._skyViewLut.update(); + + this._skyTexture = new SkyTexture2D(setting.defaultTexture2DSize, setting.defaultTexture2DSize * 0.5, ctx); + this._skyTexture.isHDRTexture = true; + this._skyTexture.updateUniforms(this.setting); + this._skyTexture.updateTextures(this._transmittanceLut, this._multipleScatteringLut, this._skyViewLut, this._cloudNoiseTexture); + this._skyTexture.update(); + + this.createFromTexture(this._cubeSize, this._skyTexture, ctx); + return this; + } + + /** Get the underlying panorama 2D texture used to build the sky cube. */ + public get texture2D(): Texture { + return this.setting.showV1 ? this._internalTexture : this._skyTexture; + } + + /** Transmittance LUT (256x64) — optical depth from a point to the sun. */ + public get transmittanceLut(): Texture { + return this._transmittanceLut; + } + + /** Multiple-scattering LUT (32x32). */ + public get multipleScatteringLut(): Texture { + return this._multipleScatteringLut; + } + + /** Sky-view LUT (192x108) — the low-res distant sky. */ + public get skyViewLut(): Texture { + return this._skyViewLut; + } + + /** Worley noise (64x64) driving the cloud layer's density. */ + public get cloudNoiseTexture(): Texture { + return this._cloudNoiseTexture; + } + + /** + * @internal + * @returns + */ + public apply(): this { + if (this.setting.showV1) { + this._internalTexture.updateUniforms(this.setting); + this._internalTexture.update(); + this._faceData.uploadErpTexture(this._internalTexture); + } else { + // Re-bake the whole chain, not just the panorama: the LUTs also + // read `enableClouds` through the shared medium sampling, and the + // sky-view LUT tracks the sun. They are tiny (256x64, 32x32, + // 192x108) next to the 1024x512 ray-march, so always-correct beats + // tracking which knob invalidates what. The cloud noise is + // setting-independent and is baked once in the constructor. + this._transmittanceLut.updateUniforms(this.setting); + this._transmittanceLut.update(); + this._multipleScatteringLut.updateUniforms(this.setting); + this._multipleScatteringLut.update(); + this._skyViewLut.updateUniforms(this.setting); + this._skyViewLut.update(); + this._skyTexture.updateUniforms(this.setting); + this._skyTexture.update(); + this._faceData.uploadErpTexture(this._skyTexture); + } + return this; + } + + /** Release the LUT chain along with the cube texture. */ + public destroy(force?: boolean): void { + super.destroy(force); + this._internalTexture?.destroy(force); + this._cloudNoiseTexture?.destroy(force); + this._transmittanceLut?.destroy(force); + this._multipleScatteringLut?.destroy(force); + this._skyViewLut?.destroy(force); + this._skyTexture?.destroy(force); + this._internalTexture = null; + this._cloudNoiseTexture = null; + this._transmittanceLut = null; + this._multipleScatteringLut = null; + this._skyViewLut = null; + this._skyTexture = null; + } +} + +/** + * @internal + * One compute-shader-backed rgba16float target of the LUT chain. + */ +class AtmosphericTexture extends VirtualTexture { + protected _computeShader: ComputeShader; + private _uniformBuffer: UniformGPUBuffer; + private _workerSize: Vector3; + + get workerSize(): Vector3 { + return this._workerSize; + } + + constructor(width: number, height: number, source: string, workerSize?: Vector3, ctx?: Context3D) { + super(width, height, GPUTextureFormat.rgba16float, false, GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING, 1, 0, 1, ctx); + this._workerSize = workerSize ?? new Vector3(8, 8, 1); + this._computeShader = new ComputeShader(source); + this._computeShader.entryPoint = 'CsMain'; + this.magFilter = 'linear'; + this.minFilter = 'linear'; + this.initCompute(width, height); + } + + protected initCompute(w: number, h: number): void { + this._uniformBuffer = new UniformGPUBuffer(16 * 4); + this._uniformBuffer.apply(); + + const black = Engine3D.resFor(this._boundCtx).blackTexture; + this._computeShader.setUniformBuffer('uniformBuffer', this._uniformBuffer); + this._computeShader.setStorageTexture(`outTexture`, this); + // Placeholders for the LUT inputs. Kernels that declare none of these + // simply ignore the extra entries — bind groups are built from shader + // reflection, not from this dictionary. + this._computeShader.setSamplerTexture(`transmittanceTexture`, black); + this._computeShader.setSamplerTexture(`multipleScatteringTexture`, black); + this._computeShader.setSamplerTexture(`cloudTexture`, black); + this._computeShader.workerSizeX = Math.ceil(w / this._workerSize.x); + this._computeShader.workerSizeY = Math.ceil(h / this._workerSize.y); + // Every kernel here writes a 2D target, so one workgroup deep. The + // multi-scattering kernel's 64 z-threads are a per-workgroup reduction + // over sample directions, not extra output rows. + this._computeShader.workerSizeZ = 1; + } + + public updateUniforms(setting: AtmosphericScatteringSkySetting): this { + this._uniformBuffer.setFloat('width', this.width); + this._uniformBuffer.setFloat('height', this.height); + this._uniformBuffer.setFloat('sunU', setting.sunX); + this._uniformBuffer.setFloat('sunV', setting.sunY); + this._uniformBuffer.setFloat('eyePos', setting.eyePos); + this._uniformBuffer.setFloat('sunRadius', setting.sunRadius); + this._uniformBuffer.setFloat('sunRadiance', setting.sunRadiance); + this._uniformBuffer.setFloat('mieG', setting.mieG); + this._uniformBuffer.setFloat('mieHeight', setting.mieHeight); + this._uniformBuffer.setFloat('sunBrightness', setting.sunBrightness); + this._uniformBuffer.setFloat('displaySun', setting.displaySun ? 1 : 0); + this._uniformBuffer.setFloat('enableClouds', setting.enableClouds ? 1 : 0); + this._uniformBuffer.setFloat('hdrExposure', setting.hdrExposure); + // WGSL starts a vec4 member on a 16-byte boundary; the CPU-side + // allocator only aligns to 4, so pad the 13 scalars out to 16 floats + // before the color or skyColor lands 12 bytes short of its slot. + this._uniformBuffer.setFloat('pad0', 0); + this._uniformBuffer.setFloat('pad1', 0); + this._uniformBuffer.setFloat('pad2', 0); + this._uniformBuffer.setColor('skyColor', setting.skyColor); + this._uniformBuffer.apply(); + return this; + } + + public update(): this { + let gpuContext = this._boundCtx!.gpuContext; + let command = gpuContext.beginCommandEncoder(); + gpuContext.computeCommand(command, [this._computeShader]); + gpuContext.endCommandEncoder(command); + return this; + } +} + +/** + * @internal + */ +class TransmittanceTexture2D extends AtmosphericTexture { + constructor(width: number, height: number, ctx?: Context3D) { + super(width, height, AtmosphericScatteringSky_shader.transmittance_cs, null, ctx); + } +} + +/** + * @internal + */ +class MultipleScatteringTexture2D extends AtmosphericTexture { + constructor(width: number, height: number, ctx?: Context3D) { + // 64 z-threads per workgroup reduce the sampled sphere directions + // through workgroup memory, one workgroup per output texel. + super(width, height, AtmosphericScatteringSky_shader.multiscatter_cs, new Vector3(1, 1, 64), ctx); + } + + public updateTransmittance(transmittanceTexture: TransmittanceTexture2D, cloudTexture: CloudNoiseTexture2D) { + this._computeShader.setSamplerTexture(`transmittanceTexture`, transmittanceTexture); + this._computeShader.setSamplerTexture(`cloudTexture`, cloudTexture); + } +} + +/** + * @internal + */ +class SkyViewTexture2D extends AtmosphericTexture { + constructor(width: number, height: number, ctx?: Context3D) { + super(width, height, AtmosphericScatteringSky_shader.skyview_cs, null, ctx); + } + + public updateTextures(transmittanceTexture: TransmittanceTexture2D, multipleScatteringTexture: MultipleScatteringTexture2D, cloudTexture: CloudNoiseTexture2D) { + this._computeShader.setSamplerTexture(`transmittanceTexture`, transmittanceTexture); + this._computeShader.setSamplerTexture(`multipleScatteringTexture`, multipleScatteringTexture); + this._computeShader.setSamplerTexture(`cloudTexture`, cloudTexture); + } +} + +/** + * @internal + */ +class SkyTexture2D extends AtmosphericTexture { + constructor(width: number, height: number, ctx?: Context3D) { + super(width, height, AtmosphericScatteringSky_shader.raymarch_cs, null, ctx); + } + + public updateTextures(transmittanceTexture: TransmittanceTexture2D, multipleScatteringTexture: MultipleScatteringTexture2D, skyViewTexture: SkyViewTexture2D, cloudTexture: CloudNoiseTexture2D) { + this._computeShader.setSamplerTexture(`transmittanceTexture`, transmittanceTexture); + this._computeShader.setSamplerTexture(`multipleScatteringTexture`, multipleScatteringTexture); + this._computeShader.setSamplerTexture(`skyTexture`, skyViewTexture); + this._computeShader.setSamplerTexture(`cloudTexture`, cloudTexture); + } +} + +/** + * @internal + */ +class CloudNoiseTexture2D extends AtmosphericTexture { + constructor(width: number, height: number, ctx?: Context3D) { + super(width, height, AtmosphericScatteringSky_shader.cloud_cs, null, ctx); + // Tiling noise: the setters drop the cached sampler, which the lazy + // getter rebuilds before the bind group is created. + this.addressModeU = GPUAddressMode.repeat; + this.addressModeV = GPUAddressMode.repeat; + } +} diff --git a/packages/atmosphere/tsconfig.json b/packages/atmosphere/tsconfig.json new file mode 100644 index 000000000..066fe090e --- /dev/null +++ b/packages/atmosphere/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ESNext", "DOM"], + "moduleResolution": "Node", + "sourceMap": false, + "resolveJsonModule": true, + "esModuleInterop": true, + "types": ["vite/client", "@webgpu/types"], + // for build + // "noEmit": true, + "declaration": true, + "declarationDir": "dist", + "outDir": "dist", + "skipLibCheck": true, + "noImplicitAny": false, + "noUnusedLocals": false, + "noUnusedParameters":false, + "noImplicitReturns": false, + "strictPropertyInitialization": false, + "strictNullChecks": false, + "strict": false, + "paths": { + "@orillusion/core": ["../../src"], + "@orillusion/*": ["../*"] + }, + "experimentalDecorators": true + } +} diff --git a/packages/atmosphere/vite.config.js b/packages/atmosphere/vite.config.js new file mode 100644 index 000000000..58a478a2e --- /dev/null +++ b/packages/atmosphere/vite.config.js @@ -0,0 +1,27 @@ +import { defineConfig } from 'vite' +const path = require('path') +export default defineConfig({ + resolve: { + alias: { + '@orillusion/core': path.resolve(__dirname, '../../src'), + '@orillusion': path.resolve(__dirname, '../') + } + }, + build: { + target: 'esnext', + lib: { + entry: path.resolve('index.ts'), + name: 'Atmosphere', + fileName: (format) => `atmosphere.${format}.js` + }, + rollupOptions: { + external: ['@orillusion/core'], + output: { + globals: { + '@orillusion/core': 'Orillusion' + }, + name: 'Orillusion.Atmosphere' + } + } + } +}) diff --git a/packages/physics-rapier/Physics.ts b/packages/physics-rapier/Physics.ts index 736999d61..c311caec2 100644 --- a/packages/physics-rapier/Physics.ts +++ b/packages/physics-rapier/Physics.ts @@ -10,6 +10,9 @@ class _Physics { private _eventQueue: RAPIER.EventQueue; private _isInited: boolean = false; private _isStop: boolean = false; + /** Number of completed `world.step()` calls. Lets queries know whether the + * broad-phase BVH has been (re)built since a body was added. */ + private _stepCount: number = 0; private _gravity: Vector3 = new Vector3(0, -9.8, 0); /** Maximum number of internal physics sub-steps per update tick. */ @@ -58,10 +61,11 @@ class _Physics { }); if (options.deterministic) { - // Pin numSolverIterations / numAdditionalFrictionIterations to make - // sim independent of stage 'auto' tuning that can drift between runs. + // Pin the solver iteration counts so the sim is independent of + // stage 'auto' tuning that can drift between runs. + // (`numAdditionalFrictionIterations` was removed in Rapier 0.15; + // friction is now solved inside the main solver loop.) this._world.integrationParameters.numSolverIterations = 4; - this._world.integrationParameters.numAdditionalFrictionIterations = 4; this._world.integrationParameters.numInternalPgsIterations = 1; } @@ -88,6 +92,7 @@ class _Physics { this._world.timestep = dt; this._world.step(this._eventQueue); + this._stepCount++; // Drain begin/end collision events. this._eventQueue.drainCollisionEvents((h1, h2, started) => { @@ -234,6 +239,9 @@ class _Physics { public get eventQueue(): RAPIER.EventQueue { return this._eventQueue; } public get isInited(): boolean { return this._isInited; } + /** Completed simulation steps since `init()`. */ + public get stepCount(): number { return this._stepCount; } + public set isStop(value: boolean) { this._isStop = value; } public get isStop(): boolean { return this._isStop; } diff --git a/packages/physics-rapier/character/CharacterController.ts b/packages/physics-rapier/character/CharacterController.ts index a4d038ff0..a93455f3b 100644 --- a/packages/physics-rapier/character/CharacterController.ts +++ b/packages/physics-rapier/character/CharacterController.ts @@ -21,6 +21,8 @@ export class CharacterController extends ComponentBase { private _controller: RAPIER.KinematicCharacterController; private _bodyInited = false; private _grounded = false; + /** `Physics.stepCount` when our body was created; see `move()`. */ + private _bornStep = 0; /** Collider descriptor (typically a capsule). Set BEFORE `start()`. */ public shape: RAPIER.ColliderDesc; @@ -60,6 +62,7 @@ export class CharacterController extends ComponentBase { } this._controller = cc; + this._bornStep = Physics.stepCount; this._bodyInited = true; this._initResolve(); } @@ -72,13 +75,22 @@ export class CharacterController extends ComponentBase { */ public move(desiredTranslation: Vector3): void { if (!this._bodyInited) return; - - // Refresh the broad-phase / query pipeline. world.step() already - // does this, but Engine3D runs the renderLoop (Physics.update) AFTER - // component onUpdate, so on the first frame computeColliderMovement - // would otherwise see an empty BVH and return the full desired - // translation — character tunnels through static colliders. - Physics.world.updateSceneQueries(); + // Engine3D runs component onUpdate BEFORE the renderLoop that calls + // Physics.update(), so on the frame this controller (and typically the + // whole level) was created, no world.step() has run yet and the + // broad-phase BVH used by computeColliderMovement is empty: the sweep + // finds nothing, returns the full desired translation and the + // character falls straight through the floor. Wait for one step. + if (Physics.stepCount <= this._bornStep) return; + + // Push any CPU-side body pose changes into the colliders before the + // query. world.step() already does this, but Engine3D runs the + // renderLoop (Physics.update) AFTER component onUpdate, so a pose set + // this frame would otherwise not be visible to computeColliderMovement. + // (Rapier ≥0.15 removed `World.updateSceneQueries()` — the query + // pipeline now lives in the broad-phase and is refreshed by `step()`; + // this is the remaining pre-step hook.) + Physics.world.propagateModifiedBodyPositionsToColliders(); this._controller.computeColliderMovement(this._collider, TempPhyMath.toRVec(desiredTranslation)); const m = this._controller.computedMovement(); diff --git a/packages/physics-rapier/package.json b/packages/physics-rapier/package.json index 28e5b45ad..228077d4f 100644 --- a/packages/physics-rapier/package.json +++ b/packages/physics-rapier/package.json @@ -21,7 +21,7 @@ "url": "git+https://github.com/Orillusion/orillusion.git" }, "dependencies": { - "@dimforge/rapier3d-compat": "^0.14.0" + "@dimforge/rapier3d-compat": "^0.19.3" }, "peerDependencies": { "@orillusion/core": ">=0.9.0" diff --git a/samples/atmosphere/Sample_AtmosphericSky.ts b/samples/atmosphere/Sample_AtmosphericSky.ts new file mode 100644 index 000000000..cb9a5e0a4 --- /dev/null +++ b/samples/atmosphere/Sample_AtmosphericSky.ts @@ -0,0 +1,99 @@ +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { createExampleScene, createSceneParam } from "@samples/utils/ExampleScene"; +import { Engine3D, GPUCullMode, MeshRenderer, Object3D, PlaneGeometry, Scene3D, Texture, UnLitMaterial, Vector3 } from "@orillusion/core"; +import { AtmosphericComponent } from "@orillusion/atmosphere"; + +/** + * Physically based atmospheric sky (@orillusion/atmosphere). + * + * Shows the Hillaire LUT chain the package bakes every time a sky parameter + * changes — transmittance, multiple scattering, sky view, cloud noise and the + * final ray-marched panorama — stacked as debug planes next to the skybox. + */ +class Sample_AtmosphericSky { + async run() { + // Every GPU resource below binds to this engine's Context3D, so the + // sample stays valid with more than one Engine3D alive. + const engine = await Engine3D.init({}); + + // The shared example scene installs the *core* AtmosphericComponent by + // default; turn it off so this package's component owns the sky. + const param = createSceneParam(); + param.scene.atmosphericSky = null; + const example = createExampleScene(engine, param); + const scene: Scene3D = example.scene; + const camera = example.camera; + // `fov` is a plain field — the projection matrix is only rebuilt by + // perspective()/updateProjection(), so assigning it alone does nothing + // until the next canvas resize. + camera.fov = 90; + camera.updateProjection(); + + engine.startRenderView(example.view); + + const sky = scene.addComponent(AtmosphericComponent); + // Two-way bind the sun to the example scene's direct light, the way + // createExampleScene wires up the core sky: dragging sunX/sunY in the + // GUI rotates the light, and rotating the light moves the sun. + sky.relativeTransform = example.light.transform; + // The LUT chain is materialized on the first render; force it here so + // the debug planes below can bind the textures synchronously. + (sky as any)._ensureSky(engine.context3D); + + const debugPlanes: Object3D[] = []; + let y = 100; + const addDebugPlane = (texture: Texture, width: number, height: number) => { + const material = new UnLitMaterial(engine.context3D); + material.baseMap = texture; + material.cullMode = GPUCullMode.none; + // The LUTs are linear HDR (rgba16float). Skip UnLit's sRGB->linear + // decode so the plane feeds the global ACES tonemap the same linear + // values the skybox does — otherwise gammaToLiner blows out HDR>1. + material.shader.getDefaultColorShader().setDefine('USE_SRGB_ALBEDO', true); + + const obj = new Object3D(); + const renderer = obj.addComponent(MeshRenderer); + renderer.material = material; + renderer.geometry = new PlaneGeometry(width, height, 1, 1, Vector3.Z_AXIS); + obj.y = y; + y -= height; + scene.addChild(obj); + debugPlanes.push(obj); + }; + + const atmosphere = sky.atmosphericScatteringSky; + addDebugPlane(atmosphere.transmittanceLut, 50, 25); + addDebugPlane(atmosphere.multipleScatteringLut, 25, 25); + addDebugPlane(atmosphere.skyViewLut, 50, 25); + addDebugPlane(atmosphere.cloudNoiseTexture, 25, 25); + addDebugPlane(atmosphere.texture2D, 50, 25); + + // gui + GUIHelp.init(); + GUIHelp.addFolder('AtmosphericSky'); + GUIHelp.add(sky, 'sunX', 0, 1, 0.01); + GUIHelp.add(sky, 'sunY', 0.4, 1.6, 0.01); + GUIHelp.add(sky, 'eyePos', 0, 7000, 1); + GUIHelp.add(sky, 'sunRadius', 0, 1000, 0.01); + GUIHelp.add(sky, 'sunRadiance', 0, 100, 0.01); + GUIHelp.add(sky, 'sunBrightness', 0, 10, 0.01); + GUIHelp.add(sky, 'hdrExposure', 0, 5, 0.01); + GUIHelp.add(sky, 'displaySun'); + GUIHelp.add(sky, 'enableClouds'); + GUIHelp.add(sky, 'showV1'); + GUIHelp.add(sky, 'enable'); + const settings = { displayTextures: true }; + GUIHelp.add(settings, 'displayTextures').onChange((v: boolean) => { + debugPlanes.forEach(obj => obj.transform.enable = v); + }); + GUIHelp.open(); + GUIHelp.endFolder(); + + GUIHelp.addFolder('Camera'); + GUIHelp.add(camera, 'fov', 1, 180, 1).onChange(() => camera.updateProjection()); + GUIHelp.open(); + GUIHelp.endFolder(); + } +} + +new Sample_AtmosphericSky().run(); diff --git a/samples/base/Sample_CatmullRomPath.ts b/samples/base/Sample_CatmullRomPath.ts new file mode 100644 index 000000000..9cc349e7b --- /dev/null +++ b/samples/base/Sample_CatmullRomPath.ts @@ -0,0 +1,137 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { Graphic3D } from '@orillusion/graphic'; +import { + BoxGeometry, CatmullRomCurve3, CatmullRomType, Color, Cylindrical, Engine3D, LitMaterial, MeshRenderer, + Object3D, Scene3D, SphereGeometry, Spherical, Time, UnLitMaterial, Vector3, View3D, +} from '@orillusion/core'; +import { createExampleScene, createSceneParam } from '@samples/utils/ExampleScene'; + +/** + * Math additions demo. + * + * - `CatmullRomCurve3`: red spheres are the control points, the white line is + * the spline through them. Yellow dots are `getSpacedPoints` (equal arc + * length) and cyan dots are `getPoints` (equal parameter) — note how the + * cyan ones bunch up where control points are close. The box travels with + * `getPointAt` (constant speed) and faces along `getTangentAt`. + * - `Spherical` / `Cylindrical`: the green satellite orbits on a sphere, the + * purple one climbs a helix, both driven purely by coordinate conversion. + */ +class Sample_CatmullRomPath { + private scene: Scene3D; + private graphic: Graphic3D; + private curve: CatmullRomCurve3; + private follower: Object3D; + private sat: Object3D; + private heli: Object3D; + private spacedDots: Object3D[] = []; + private paramDots: Object3D[] = []; + private readonly state = { curveType: 'centripetal' as CatmullRomType, tension: 0.5, closed: true, speed: 0.08, constantSpeed: true, length: 0 }; + private u = 0; + private spherical = new Spherical(9, Math.PI / 3, 0); + private cylindrical = new Cylindrical(6, 0, 0); + + async run() { + const engine = await Engine3D.init({ renderLoop: () => this.loop() }); + const param = createSceneParam(); + param.camera.distance = 85; + param.camera.pitch = -35; + const ex = createExampleScene(engine, param); + this.scene = ex.scene; + this.graphic = new Graphic3D(); + this.scene.addChild(this.graphic); + + const control = [ + new Vector3(-30, 2, -10), new Vector3(-24, 10, -6), new Vector3(-20, 3, 0), // three close together + new Vector3(5, 14, 14), new Vector3(28, 4, 6), new Vector3(24, 8, -18), new Vector3(-4, 2, -24), + ]; + this.curve = new CatmullRomCurve3(control, this.state.closed, this.state.curveType, this.state.tension); + + const red = new UnLitMaterial(); red.baseColor = new Color(1, 0.15, 0.1); + const yellow = new UnLitMaterial(); yellow.baseColor = new Color(1, 0.9, 0.2); + const cyan = new UnLitMaterial(); cyan.baseColor = new Color(0.2, 0.9, 1); + control.forEach(p => this.dot(new SphereGeometry(0.9, 16, 16), red, p)); + const small = new SphereGeometry(0.35, 8, 8); + for (let i = 0; i <= 40; i++) { + this.spacedDots.push(this.dot(small, yellow, new Vector3())); + this.paramDots.push(this.dot(small, cyan, new Vector3())); + } + + const mat = new LitMaterial(); mat.baseColor = new Color(0.9, 0.5, 0.1); mat.roughness = 0.5; + this.follower = new Object3D(); + const mr = this.follower.addComponent(MeshRenderer); + mr.geometry = new BoxGeometry(1.6, 1.6, 4); mr.material = mat; + this.scene.addChild(this.follower); + + const green = new LitMaterial(); green.baseColor = new Color(0.2, 0.8, 0.3); + const purple = new LitMaterial(); purple.baseColor = new Color(0.6, 0.3, 0.9); + this.sat = this.dot(new SphereGeometry(1, 24, 24), green, new Vector3()); + this.heli = this.dot(new SphereGeometry(1, 24, 24), purple, new Vector3()); + + const floor = new Object3D(); + const fm = floor.addComponent(MeshRenderer); + fm.geometry = new BoxGeometry(120, 1, 120); + const fmat = new LitMaterial(); fmat.baseColor = new Color(0.45, 0.45, 0.5); fmat.roughness = 0.9; + fm.material = fmat; + floor.y = -1; + this.scene.addChild(floor); + + engine.startRenderView(ex.view); + this.rebuild(); + this.initGUI(); + } + + private dot(geo: any, mat: any, p: Vector3): Object3D { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geo; mr.material = mat; mr.castShadow = false; + o.localPosition = p; + this.scene.addChild(o); + return o; + } + + private rebuild() { + const c = this.curve; + c.closed = this.state.closed; c.curveType = this.state.curveType; c.tension = this.state.tension; + this.graphic.Clear('curve'); + this.graphic.drawLines('curve', c.getPoints(300), new Color(1, 1, 1)); + const spaced = c.getSpacedPoints(40), param = c.getPoints(40); + for (let i = 0; i <= 40; i++) { + this.spacedDots[i].localPosition = new Vector3(spaced[i].x, spaced[i].y + 0.9, spaced[i].z); + this.paramDots[i].localPosition = new Vector3(param[i].x, param[i].y - 0.9, param[i].z); + } + this.state.length = +c.getLength().toFixed(2); + } + + private loop() { + if (!this.curve) return; + const dt = Time.delta * 0.001; + this.u = (this.u + dt * this.state.speed) % 1; + const pos = this.state.constantSpeed ? this.curve.getPointAt(this.u) : this.curve.getPoint(this.u); + const tan = this.state.constantSpeed ? this.curve.getTangentAt(this.u) : this.curve.getTangent(this.u); + this.follower.transform.lookAt(pos, new Vector3(pos.x + tan.x, pos.y + tan.y, pos.z + tan.z)); + + this.spherical.theta += dt * 0.9; + this.spherical.phi = Math.PI / 2 + Math.sin(Time.time * 0.0007) * 0.9; + const s = this.spherical.toVector3(); + this.sat.localPosition = new Vector3(s.x, s.y + 14, s.z); + + this.cylindrical.theta += dt * 1.6; + this.cylindrical.y = 14 + Math.sin(this.cylindrical.theta * 0.25) * 9; + this.heli.localPosition = this.cylindrical.toVector3(); + } + + private initGUI() { + GUIHelp.init(); + const f = GUIHelp.addFolder('CatmullRomCurve3'); + f.add(this.state, 'curveType', ['centripetal', 'chordal', 'catmullrom']).onChange(() => this.rebuild()); + f.add(this.state, 'tension', 0, 1, 0.01).onChange(() => this.rebuild()); + f.add(this.state, 'closed').onChange(() => this.rebuild()); + f.add(this.state, 'constantSpeed'); + f.add(this.state, 'speed', 0, 0.4, 0.005); + f.add(this.state, 'length').listen(); + f.open(); + } +} + +new Sample_CatmullRomPath().run(); diff --git a/samples/fluid/Sample_FluidFLIP.ts b/samples/fluid/Sample_FluidFLIP.ts new file mode 100644 index 000000000..97cca82b7 --- /dev/null +++ b/samples/fluid/Sample_FluidFLIP.ts @@ -0,0 +1,223 @@ +import { + AtmosphericComponent, CameraUtil, Color, ComponentBase, Context3D, DirectLight, Engine3D, FluidDebug, FluidDepthFilter, FluidThicknessMode, + FluidRenderer, HoverCameraController, KelvinUtil, LitMaterial, MeshRenderer, Object3D, PlaneGeometry, + PointerEvent3D, Scene3D, Vector3, View3D, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { FluidSimulatorConfig } from "../compute/fluid/FluidSimulatorConfig"; +import { FluidSimulatorPipeline } from "../compute/fluid/FluidSimulatorPipeline"; +import { createPool } from "./_PoolScene"; + +/** + * Screen-space fluid rendering of a GPU FLIP simulation. The + * simulation's particle position buffer is handed to FluidRenderer with + * setDataBufferGPU, so positions never leave the GPU. + * + * Move the mouse over the water to stir it; drag to orbit the camera. + */ +export class Sample_FluidFLIP { + async run() { + const engine = await Engine3D.init({ + setting: { render: { fluid: true } }, + }); + + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent); + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(60, engine.aspect, 0.1, 1000); + camera.object3D.addComponent(HoverCameraController).setCamera(-35, -30, 45, new Vector3(15, 4, 10)); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const light = new Object3D(); + light.rotationX = 50; + light.rotationY = 30; + const dl = light.addComponent(DirectLight); + dl.lightColor = KelvinUtil.color_temperature_to_rgb(5500); + dl.intensity = 3; + dl.castShadow = true; + scene.addChild(light); + + + const fluidObj = new Object3D(); + const fluid = fluidObj.addComponent(FluidRenderer); + fluid.particleSize = 0.4; + const pool = this.createTank(scene, engine.context3D, fluid.particleSize / 2); + fluid.particleThicknessAlpha = 0.02; + // Particles are only a few pixels wide at this distance; blur over about one and a half + // diameters so the spheres merge into a smooth surface. + fluid.blurDepthFilterSize = 30; + fluid.blurDepthNumIterations = 5; + fluid.depthFilter = FluidDepthFilter.NarrowRange; + fluid.useAnisotropy = true; + // Absorb by the path length through the water (world units) instead of by particle count: + // FLIP particles are unevenly spaced and accumulated thickness shows that as cloudy patches. + fluid.thicknessMode = FluidThicknessMode.Geometric; + fluid.density = 0.15; + // Smooths the sphere bumps of the near and far side that the thickness is taken from. + fluid.blurThicknessFilterSize = 20; + fluid.blurThicknessNumIterations = 3; + fluid.edgeSoftness = 5; + const sim = fluidObj.addComponent(FLIPSimulation); + sim.onReady = (positions, count) => fluid.setDataBufferGPU(positions, count); + scene.addChild(fluidObj); + + // The fluid is drawn in screen space and not written to the G-buffer, so pixel picking + // cannot hit it. The mouse ray is intersected with a plane at about the water surface + // instead; the movement of that point drives the stirring force. Points outside the + // tank, stale points (mouse left the canvas) and oversized steps are dropped: the + // solver applies the velocity to most of the grid and diverges if it gets too large. + const input = engine.inputSystem; + const stirHeight = 5; + const maxStirStep = 3; + const lastPoint = new Vector3(); + const point = new Vector3(); + const velocity = new Vector3(); + let lastTime = -Infinity; + input.addEventListener(PointerEvent3D.POINTER_MOVE, () => { + const now = performance.now(); + const fresh = now - lastTime < 100; + lastTime = -Infinity; + if (input.isMouseDown || sim.paused) return; + + const ray = camera.screenPointToRay(input.mouseX, input.mouseY); + const dir = ray.direction; + const t = Math.abs(dir.y) > 1e-4 ? (stirHeight - ray.origin.y) / dir.y : -1; + if (t <= 0) return; + point.set(ray.origin.x + dir.x * t, stirHeight, ray.origin.z + dir.z * t); + if (point.x < 0 || point.x > 30 || point.z < 0 || point.z > 20) return; + + if (fresh) { + Vector3.sub(point, lastPoint, velocity); + velocity.clampLength(0, maxStirStep); + sim.stir(ray.origin, dir, velocity); + } + lastPoint.copy(point); + lastTime = now; + }, this); + + GUIHelp.init(); + GUIHelp.addFolder('Fluid'); + GUIHelp.add(fluid, 'enable'); + // Hide the pool to look at the fluid's free edges. + GUIHelp.add({ showPool: true }, 'showPool').onChange((v: boolean) => pool.transform.enable = v); + GUIHelp.add(fluid, 'particleSize', 0.05, 2, 0.01); + GUIHelp.add(fluid, 'particleThicknessAlpha', 0, 0.2, 0.002); + GUIHelp.addColor(fluid, 'fluidColor'); + GUIHelp.add(fluid, 'density', 0, 2, 0.01); + GUIHelp.add(fluid, 'refractionStrength', 0, 3, 0.05); + GUIHelp.add(fluid, 'fresnelClamp', 0, 1, 0.01); + GUIHelp.add(fluid, 'specularPower', 1, 1000, 1); + GUIHelp.add(fluid, 'edgeSoftness', 0, 20, 0.5); + GUIHelp.add(fluid, 'blurDepthFilterSize', 0, 60, 1); + GUIHelp.add(fluid, 'blurDepthNumIterations', 0, 10, 1); + GUIHelp.add(fluid, 'blurDepthDepthScale', 0, 30, 0.5); + GUIHelp.add(fluid, 'blurThicknessFilterSize', 0, 40, 1); + GUIHelp.add(fluid, 'blurThicknessNumIterations', 0, 10, 1); + GUIHelp.add(fluid, 'depthFilter', { Bilateral: FluidDepthFilter.Bilateral, NarrowRange: FluidDepthFilter.NarrowRange }); + GUIHelp.add(fluid, 'thicknessMode', { Accumulated: FluidThicknessMode.Accumulated, Geometric: FluidThicknessMode.Geometric }); + GUIHelp.add(fluid, 'useAnisotropy'); + GUIHelp.add(fluid, 'anisotropyMaxRatio', 1, 8, 0.1); + GUIHelp.add(fluid, 'anisotropyMinNeighbors', 0, 40, 1); + GUIHelp.add(fluid, 'anisotropySmoothing', 0, 1, 0.01); + GUIHelp.add(fluid, 'debug'); + GUIHelp.add(fluid, 'debugFeature', { + Depth: FluidDebug.DepthTexture, + DepthBlurred: FluidDebug.DepthBlurredTexture, + Thickness: FluidDebug.ThicknessTexture, + ThicknessBlurred: FluidDebug.ThicknessBlurredTexture, + Normals: FluidDebug.Normals, + }); + GUIHelp.add(sim, 'paused'); + GUIHelp.open(); + GUIHelp.endFolder(); + } + + /** + * Pool around the simulation domain (x 0..30, z 0..20). Particles rest at y >= 0.01, so the + * floor sits one particle radius lower to keep the spheres from poking through it. + */ + private createTank(scene: Scene3D, ctx: Context3D, particleRadius: number): Object3D { + const floorY = -particleRadius - 0.05; + const slab = 0.8; + scene.addChild(this.createMesh(new PlaneGeometry(80, 80), new Color(0.15, 0.15, 0.17), 15, floorY - slab - 0.01, 10)); + return createPool(scene, ctx, { width: 30, depth: 20, wallHeight: 6, wallThickness: slab, tileSize: 0.5, lanes: 4, y: floorY }); + } + + private createMesh(geometry: PlaneGeometry, color: Color, x: number, y: number, z: number): Object3D { + const obj = new Object3D(); + obj.x = x; + obj.y = y; + obj.z = z; + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + const mat = new LitMaterial(); + mat.baseColor = color; + mat.roughness = 0.8; + mat.metallic = 0; + mr.material = mat; + mr.receiveShadow = true; + // Lies just under the pool floor; as a caster it shadows the floor through depth bias. + mr.castShadow = false; + return obj; + } +} + +/** + * Runs the FLIP solver from samples/compute/fluid every frame without + * drawing anything itself. + */ +class FLIPSimulation extends ComponentBase { + public paused = false; + public onReady: (positions: FluidSimulatorPipeline['positionBuffer'], count: number) => void = () => { }; + + private pipeline!: FluidSimulatorPipeline; + + public start(): void { + const config: FluidSimulatorConfig = { + GROUP_SIZE: 128, + XMIN: 0, XMAX: 15, + YMIN: 10, YMAX: 20, + ZMIN: 0, ZMAX: 20, + scaleV: 3, scale: 0, + gridSizeX: 30, gridSizeY: 20, gridSizeZ: 20, + gridResolutionX: 30, gridResolutionY: 20, gridResolutionZ: 20, + initDensity: 20, + NUM: 0, dispatchNUM: 0, + GRIDNUM: 0, dispatchGRID: 0, + CELLNUM: 0, dispatchCELL: 0, + maxDensity: 0, + timeStep: 1.0 / 60.0, + PRESSURE_JACOBI_ITERATIONS: 100, + flipness: 0.95, + }; + const { initDensity, XMIN, XMAX, YMIN, YMAX, ZMIN, ZMAX, scaleV, GROUP_SIZE } = config; + const gx = config.gridResolutionX, gy = config.gridResolutionY, gz = config.gridResolutionZ; + config.scale = Math.pow(scaleV, 1.0 / 3.0); + config.NUM = Math.ceil(initDensity * (XMAX - XMIN) * (YMAX - YMIN) * (ZMAX - ZMIN) * scaleV); + config.dispatchNUM = Math.ceil(config.NUM / GROUP_SIZE); + config.GRIDNUM = (gx + 1) * (gy + 1) * (gz + 1); + config.dispatchGRID = Math.ceil(config.GRIDNUM / GROUP_SIZE); + config.CELLNUM = gx * gy * gz; + config.dispatchCELL = Math.ceil(config.CELLNUM / GROUP_SIZE); + config.maxDensity = config.NUM / (XMAX - XMIN) / (YMAX - YMIN) / (ZMAX - ZMIN); + + this.pipeline = new FluidSimulatorPipeline(config); + this.onReady(this.pipeline.positionBuffer, config.NUM); + } + + /** Push the fluid near a ray with the given velocity. */ + public stir(origin: Vector3, direction: Vector3, velocity: Vector3): void { + this.pipeline?.updateInput(origin, direction, velocity); + } + + public onCompute(_view?: View3D, command?: GPUCommandEncoder): void { + if (this.paused || !this.pipeline || !command) return; + this.pipeline.updateInputData(); + this.pipeline.compute(command); + } +} diff --git a/samples/fluid/Sample_FluidRenderer.ts b/samples/fluid/Sample_FluidRenderer.ts new file mode 100644 index 000000000..ce5128a1f --- /dev/null +++ b/samples/fluid/Sample_FluidRenderer.ts @@ -0,0 +1,233 @@ +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, ComponentBase, DirectLight, Engine3D, + FluidDebug, FluidDepthFilter, FluidRenderer, FluidThicknessMode, HoverCameraController, KelvinUtil, LitMaterial, MeshRenderer, Object3D, + PlaneGeometry, Scene3D, View3D, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { createPool } from "./_PoolScene"; + +/** + * Screen-space fluid rendering of CPU-simulated particles: a block of + * particles drops into a box and sloshes around. A pillar in the box + * checks that opaque geometry clips the fluid. + */ +export class Sample_FluidRenderer { + async run() { + const engine = await Engine3D.init({ + setting: { render: { fluid: true } }, + }); + + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent); + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(60, engine.aspect, 0.1, 500); + camera.object3D.addComponent(HoverCameraController).setCamera(30, -35, 7); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const light = new Object3D(); + light.rotationX = 50; + light.rotationY = 30; + const dl = light.addComponent(DirectLight); + dl.lightColor = KelvinUtil.color_temperature_to_rgb(5500); + dl.intensity = 3; + dl.castShadow = true; + scene.addChild(light); + + // Particles rest at y >= 0.05 with radius 0.08: the floor sits below their lowest point, + // and the ground below the floor slab. + const floorY = -0.05; + const slab = 0.12; + scene.addChild(this.createMesh(new PlaneGeometry(20, 20), new Color(0.15, 0.15, 0.17), 0, floorY - slab - 0.01, 0)); + scene.addChild(this.createMesh(new BoxGeometry(0.6, 2.5, 0.6), new Color(0.92, 0.92, 0.9), 0.8, floorY + 1.25, 0.4)); + const pool = createPool(scene, engine.context3D, { + width: 3.2, depth: 3.2, wallHeight: 0.6, wallThickness: slab, tileSize: 0.1, lanes: 2, x: -1.6, y: floorY, z: -1.6, + }); + + const fluidObj = new Object3D(); + const fluid = fluidObj.addComponent(FluidRenderer); + fluid.particleSize = 0.16; + // Blur over about one particle diameter so the spheres merge into a smooth surface. + fluid.blurDepthFilterSize = 15; + fluid.blurDepthNumIterations = 6; + fluid.depthFilter = FluidDepthFilter.NarrowRange; + fluid.useAnisotropy = true; + fluid.edgeSoftness = 5; + fluid.blurThicknessFilterSize = 10; + fluid.blurThicknessNumIterations = 2; + const sim = fluidObj.addComponent(BoxSloshSimulation, { fluid, count: 6000 }); + scene.addChild(fluidObj); + + GUIHelp.init(); + GUIHelp.addFolder('Fluid'); + GUIHelp.add(fluid, 'enable'); + // Hide the pool to look at the fluid's free edges. + GUIHelp.add({ showPool: true }, 'showPool').onChange((v: boolean) => pool.transform.enable = v); + GUIHelp.add(fluid, 'particleSize', 0.02, 0.5, 0.01); + GUIHelp.add(fluid, 'particleThicknessAlpha', 0, 0.3, 0.005); + GUIHelp.addColor(fluid, 'fluidColor'); + GUIHelp.add(fluid, 'density', 0, 10, 0.1); + GUIHelp.add(fluid, 'refractionStrength', 0, 3, 0.05); + GUIHelp.add(fluid, 'fresnelClamp', 0, 1, 0.01); + GUIHelp.add(fluid, 'specularPower', 1, 1000, 1); + GUIHelp.add(fluid, 'edgeSoftness', 0, 20, 0.5); + GUIHelp.add(fluid, 'minimumThickness', 0, 1, 0.01); + GUIHelp.add(fluid, 'useFixedThickness'); + GUIHelp.add(fluid, 'depthFilter', { Bilateral: FluidDepthFilter.Bilateral, NarrowRange: FluidDepthFilter.NarrowRange }); + GUIHelp.add(fluid, 'thicknessMode', { Accumulated: FluidThicknessMode.Accumulated, Geometric: FluidThicknessMode.Geometric }); + GUIHelp.add(fluid, 'useAnisotropy'); + GUIHelp.add(fluid, 'anisotropyMaxRatio', 1, 8, 0.1); + GUIHelp.add(fluid, 'anisotropyMinNeighbors', 0, 40, 1); + GUIHelp.add(fluid, 'anisotropySmoothing', 0, 1, 0.01); + GUIHelp.add(fluid, 'debug'); + GUIHelp.add(fluid, 'debugFeature', { + Depth: FluidDebug.DepthTexture, + DepthBlurred: FluidDebug.DepthBlurredTexture, + Thickness: FluidDebug.ThicknessTexture, + ThicknessBlurred: FluidDebug.ThicknessBlurredTexture, + Normals: FluidDebug.Normals, + }); + GUIHelp.add(sim, 'paused'); + GUIHelp.addButton('Reset', () => sim.reset()); + GUIHelp.open(); + GUIHelp.endFolder(); + + GUIHelp.addFolder('Depth blur'); + GUIHelp.add(fluid, 'enableBlurDepth'); + GUIHelp.add(fluid, 'blurDepthSizeDivisor', 1, 4, 1); + GUIHelp.add(fluid, 'blurDepthFilterSize', 0, 60, 1); + GUIHelp.add(fluid, 'blurDepthNumIterations', 0, 10, 1); + GUIHelp.add(fluid, 'blurDepthMaxFilterSize', 1, 100, 1); + GUIHelp.add(fluid, 'blurDepthDepthScale', 0, 30, 0.5); + GUIHelp.endFolder(); + + GUIHelp.addFolder('Thickness blur'); + GUIHelp.add(fluid, 'enableBlurThickness'); + GUIHelp.add(fluid, 'blurThicknessSizeDivisor', 1, 4, 1); + GUIHelp.add(fluid, 'blurThicknessFilterSize', 0, 30, 1); + GUIHelp.add(fluid, 'blurThicknessNumIterations', 0, 10, 1); + GUIHelp.endFolder(); + } + + private createMesh(geometry: PlaneGeometry | BoxGeometry, color: Color, x: number, y: number, z: number): Object3D { + const obj = new Object3D(); + obj.x = x; + obj.y = y; + obj.z = z; + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + const mat = new LitMaterial(); + mat.baseColor = color; + mat.roughness = 0.8; + mat.metallic = 0; + mr.material = mat; + mr.castShadow = true; + mr.receiveShadow = true; + return obj; + } +} + +/** + * Minimal particle motion (gravity, damping, box walls, a pillar and + * soft particle spreading on a hash grid). Not a physical fluid + * solver; it only produces liquid-like particle motion to render. + */ +class BoxSloshSimulation extends ComponentBase { + public paused = false; + + private fluid!: FluidRenderer; + private count = 0; + private pos!: Float32Array; // xyzw per particle, the layout FluidRenderer expects by default + private vel!: Float32Array; + private readonly half = 1.6; + private readonly spacing = 0.1; + + public init(param?: { fluid: FluidRenderer; count: number }): void { + if (!param) return; + this.fluid = param.fluid; + this.count = param.count; + this.pos = new Float32Array(this.count * 4); + this.vel = new Float32Array(this.count * 3); + this.reset(); + } + + public reset(): void { + const n = Math.ceil(Math.cbrt(this.count)); + for (let i = 0; i < this.count; i++) { + const x = i % n, y = Math.floor(i / (n * n)), z = Math.floor(i / n) % n; + this.pos[i * 4 + 0] = -this.half + 0.2 + x * this.spacing + Math.random() * 0.01; + this.pos[i * 4 + 1] = 1.0 + y * this.spacing; + this.pos[i * 4 + 2] = -this.half + 0.2 + z * this.spacing + Math.random() * 0.01; + this.pos[i * 4 + 3] = 1; + this.vel[i * 3 + 0] = 2.0; + this.vel[i * 3 + 1] = 0; + this.vel[i * 3 + 2] = 1.0; + } + this.fluid.setDataBuffer(this.pos); + } + + public onUpdate(): void { + if (this.paused || !this.fluid) return; + const dt = 1 / 60; + for (let s = 0; s < 2; s++) this.step(dt / 2); + this.fluid.setDataBuffer(this.pos); + } + + private step(dt: number): void { + const { pos, vel, count, half } = this; + const h = this.spacing; + const cell = new Map(); + const key = (x: number, y: number, z: number) => ((x + 512) * 1024 + (y + 512)) * 1024 + (z + 512); + for (let i = 0; i < count; i++) { + const k = key(Math.floor(pos[i * 4] / h), Math.floor(pos[i * 4 + 1] / h), Math.floor(pos[i * 4 + 2] / h)); + let list = cell.get(k); + if (!list) cell.set(k, list = []); + list.push(i); + } + + for (let i = 0; i < count; i++) { + const px = pos[i * 4], py = pos[i * 4 + 1], pz = pos[i * 4 + 2]; + const cx = Math.floor(px / h), cy = Math.floor(py / h), cz = Math.floor(pz / h); + let fx = 0, fy = 0, fz = 0; + for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) { + const list = cell.get(key(cx + dx, cy + dy, cz + dz)); + if (!list) continue; + for (const j of list) { + if (j === i) continue; + const rx = px - pos[j * 4], ry = py - pos[j * 4 + 1], rz = pz - pos[j * 4 + 2]; + const d2 = rx * rx + ry * ry + rz * rz; + if (d2 >= h * h || d2 < 1e-10) continue; + const d = Math.sqrt(d2); + const push = (h - d) / h * 60; + fx += rx / d * push; fy += ry / d * push; fz += rz / d * push; + } + } + vel[i * 3] = (vel[i * 3] + fx * dt) * 0.995; + vel[i * 3 + 1] = (vel[i * 3 + 1] + (fy - 9.8) * dt) * 0.995; + vel[i * 3 + 2] = (vel[i * 3 + 2] + fz * dt) * 0.995; + } + + const r = h * 0.5; + for (let i = 0; i < count; i++) { + let x = pos[i * 4] + vel[i * 3] * dt; + let y = pos[i * 4 + 1] + vel[i * 3 + 1] * dt; + let z = pos[i * 4 + 2] + vel[i * 3 + 2] * dt; + if (y < r) { y = r; vel[i * 3 + 1] *= -0.3; } + if (x < -half + r) { x = -half + r; vel[i * 3] *= -0.3; } + if (x > half - r) { x = half - r; vel[i * 3] *= -0.3; } + if (z < -half + r) { z = -half + r; vel[i * 3 + 2] *= -0.3; } + if (z > half - r) { z = half - r; vel[i * 3 + 2] *= -0.3; } + // pillar at (0.8, 0.4), half extent 0.3 + const ox = x - 0.8, oz = z - 0.4, e = 0.3 + r; + if (Math.abs(ox) < e && Math.abs(oz) < e && y < 2.5) { + if (e - Math.abs(ox) < e - Math.abs(oz)) { x = 0.8 + Math.sign(ox) * e; vel[i * 3] *= -0.3; } + else { z = 0.4 + Math.sign(oz) * e; vel[i * 3 + 2] *= -0.3; } + } + pos[i * 4] = x; pos[i * 4 + 1] = y; pos[i * 4 + 2] = z; + } + } +} diff --git a/samples/fluid/_PoolScene.ts b/samples/fluid/_PoolScene.ts new file mode 100644 index 000000000..7ec4e19a2 --- /dev/null +++ b/samples/fluid/_PoolScene.ts @@ -0,0 +1,114 @@ +import { BitmapTexture2D, BoxGeometry, Color, Context3D, LitMaterial, MeshRenderer, Object3D, Scene3D } from "@orillusion/core"; + +export type PoolOptions = { + /** Inner size along x. */ + width: number; + /** Inner size along z. */ + depth: number; + /** Wall height above the floor. */ + wallHeight: number; + /** Thickness of the walls and of the floor slab under the inner floor. */ + wallThickness: number; + /** Edge length of one floor tile. */ + tileSize: number; + /** Number of dark lane lines on the floor, running along x. */ + lanes: number; + /** Inner corner of the pool (min x, floor y, min z). */ + x?: number; + y?: number; + z?: number; +}; + +const WALL_COLOR = new Color(0.55, 0.82, 0.88); +const COPING_COLOR = new Color(0.95, 0.95, 0.92); + +/** + * Swimming pool: a mosaic-tiled floor slab with lane lines, light aqua + * walls and a white coping on top. The inner volume starts at (x, y, z); + * the slab and walls reach down to y - wallThickness. + */ +export function createPool(scene: Scene3D, ctx: Context3D, o: PoolOptions): Object3D { + const x0 = o.x ?? 0, y0 = o.y ?? 0, z0 = o.z ?? 0; + const { width: w, depth: d, wallHeight: h, wallThickness: t } = o; + const pool = new Object3D(); + + const floorMat = new LitMaterial(); + floorMat.baseMap = paintFloor(ctx, o); + floorMat.roughness = 0.35; + floorMat.metallic = 0; + pool.addChild(box(new BoxGeometry(w, t, d), floorMat, x0 + w / 2, y0 - t / 2, z0 + d / 2)); + + const wallMat = new LitMaterial(); + wallMat.baseColor = WALL_COLOR; + wallMat.roughness = 0.4; + wallMat.metallic = 0; + const copingMat = new LitMaterial(); + copingMat.baseColor = COPING_COLOR; + copingMat.roughness = 0.6; + copingMat.metallic = 0; + const ch = Math.max(0.02, t * 0.4); + const walls: [number, number, number, number][] = [ + // [size x, size z, center x, center z] + [w + 2 * t, t, x0 + w / 2, z0 - t / 2], + [w + 2 * t, t, x0 + w / 2, z0 + d + t / 2], + [t, d, x0 - t / 2, z0 + d / 2], + [t, d, x0 + w + t / 2, z0 + d / 2], + ]; + for (const [sx, sz, cx, cz] of walls) { + pool.addChild(box(new BoxGeometry(sx, h + t, sz), wallMat, cx, y0 + (h - t) / 2, cz)); + pool.addChild(box(new BoxGeometry(sx + t * 0.3, ch, sz + t * 0.3), copingMat, cx, y0 + h + ch / 2, cz)); + } + scene.addChild(pool); + return pool; +} + +function box(geometry: BoxGeometry, material: LitMaterial, x: number, y: number, z: number): Object3D { + const obj = new Object3D(); + obj.x = x; + obj.y = y; + obj.z = z; + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + mr.material = material; + // Receive only: the thin walls give jagged shadow-map edges on the ground. + mr.receiveShadow = true; + mr.castShadow = false; + return obj; +} + +/** Mosaic tiles with light grout and dark-blue lane lines that end in a T before each wall. */ +function paintFloor(ctx: Context3D, o: PoolOptions): BitmapTexture2D { + const tilesX = Math.round(o.width / o.tileSize); + const tilesZ = Math.round(o.depth / o.tileSize); + const px = Math.max(8, Math.floor(2048 / Math.max(tilesX, tilesZ))); + const canvas = document.createElement('canvas'); + canvas.width = tilesX * px; + canvas.height = tilesZ * px; + const g = canvas.getContext('2d')!; + + g.fillStyle = 'rgb(225, 242, 246)'; + g.fillRect(0, 0, canvas.width, canvas.height); + const grout = Math.max(1, Math.round(px * 0.08)); + for (let i = 0; i < tilesX; i++) { + for (let j = 0; j < tilesZ; j++) { + const k = 0.94 + Math.random() * 0.1; + g.fillStyle = `rgb(${Math.round(110 * k)}, ${Math.round(200 * k)}, ${Math.round(218 * k)})`; + g.fillRect(i * px + grout, j * px + grout, px - 2 * grout, px - 2 * grout); + } + } + + // Lane lines: one tile wide, stopping two tiles short of the end walls, with a T bar. + g.fillStyle = 'rgb(18, 42, 105)'; + const margin = 2 * px; + for (let l = 1; l <= o.lanes; l++) { + const zc = Math.round((l * tilesZ) / (o.lanes + 1)) * px; + g.fillRect(margin, zc - px / 2, canvas.width - 2 * margin, px); + for (const xe of [margin, canvas.width - margin - px]) { + g.fillRect(xe, zc - 1.5 * px, px, 3 * px); + } + } + + const tex = new BitmapTexture2D(true, ctx, 'srgb'); + tex.source = canvas; + return tex; +} diff --git a/samples/loader/Sample_GLTFVariants.ts b/samples/loader/Sample_GLTFVariants.ts new file mode 100644 index 000000000..611337708 --- /dev/null +++ b/samples/loader/Sample_GLTFVariants.ts @@ -0,0 +1,69 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LitMaterial, MaterialVariants, MeshRenderer, Object3D, Scene3D, View3D, +} from '@orillusion/core'; +import { buildVariantsDemoGLB } from '@samples/utils/GLBBuilder'; + +/** + * glTF extension coverage demo — everything on screen comes from a .glb that + * is generated in memory (see `samples/utils/GLBBuilder.ts`): + * + * - KHR_mesh_quantization: the sphere's positions are int16, normals int8 + * and UVs uint16, expanded to float by the loader. + * - KHR_materials_variants: the dropdown switches the sphere between the + * authored material and three variants through `MaterialVariants`. + * - KHR_materials_specular on the default material, KHR_materials_sheen on + * the "Velvet" variant. + * - The yellow ribbon is a NON-indexed mesh with 100 triangles (the loader + * used to build its fallback index buffer as Uint8, wrapping at 255). + */ +class Sample_GLTFVariants { + async run() { + const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 30 } } }); + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent).sunY = 0.6; + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(45, engine.aspect, 0.1, 500); + camera.object3D.addComponent(HoverCameraController).setCamera(20, -12, 16); + + const lightObj = new Object3D(); + lightObj.rotationX = 40; lightObj.rotationY = 140; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5600); + light.intensity = 3.5; light.castShadow = true; + scene.addChild(lightObj); + + const floor = new Object3D(); + const fm = floor.addComponent(MeshRenderer); + fm.geometry = new BoxGeometry(60, 1, 60); + const mat = new LitMaterial(); mat.baseColor = new Color(0.5, 0.5, 0.52); mat.roughness = 0.9; mat.metallic = 0; + fm.material = mat; fm.castShadow = false; + floor.y = -4; + scene.addChild(floor); + + const info = buildVariantsDemoGLB(2, 48); + const url = URL.createObjectURL(info.blob); + const root = await engine.res.loadGltf(url); + scene.addChild(root); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const variants = root.getComponent(MaterialVariants); + GUIHelp.init(); + const f = GUIHelp.addFolder('KHR_materials_variants'); + const state = { variant: '(default)', sphereVertices: info.sphereVertices, ribbonTriangles: info.ribbonTriangles }; + f.add(state, 'variant', ['(default)', ...variants.variantNames]).onChange((v: string) => { + variants.selectVariant(v === '(default)' ? null : v); + }); + f.add(state, 'sphereVertices'); + f.add(state, 'ribbonTriangles'); + f.open(); + } +} + +new Sample_GLTFVariants().run(); diff --git a/samples/material/Sample_Iridescence.ts b/samples/material/Sample_Iridescence.ts new file mode 100644 index 000000000..17e9e68d2 --- /dev/null +++ b/samples/material/Sample_Iridescence.ts @@ -0,0 +1,96 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LitMaterial, MeshRenderer, Object3D, Scene3D, SphereGeometry, TorusGeometry, View3D, +} from '@orillusion/core'; + +/** + * KHR_materials_iridescence demo (thin-film interference). + * + * Top row: film thickness 100 → 800 nm over a dark metal — each thickness + * resonates at different wavelengths, so the hue walks through the rainbow + * and also shifts from the centre of each sphere to its rim (view angle). + * Middle row: the same thickness with film IOR 1.1 → 2.0. Bottom row: the + * base materials without the film. The GUI drives the torus. + */ +class Sample_Iridescence { + private scene: Scene3D; + private hero: LitMaterial; + + async run() { + const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 60 } } }); + this.scene = new Scene3D(); + this.scene.addComponent(AtmosphericComponent).sunY = 0.6; + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(45, engine.aspect, 0.1, 1000); + camera.object3D.addComponent(HoverCameraController).setCamera(15, -12, 50); + + const lightObj = new Object3D(); + lightObj.rotationX = 40; lightObj.rotationY = 140; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5600); + light.intensity = 3.5; + light.castShadow = true; + this.scene.addChild(lightObj); + + this.build(); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + engine.startRenderView(view); + this.initGUI(); + } + + private metal(film: { ior: number, thickness: number } | null): LitMaterial { + const m = new LitMaterial(); + m.baseColor = new Color(0.25, 0.25, 0.27); + m.metallic = 1.0; + m.roughness = 0.25; + if (film) { + m.iridescenceIOR = film.ior; + m.iridescenceThickness = film.thickness; + m.iridescence = 1.0; + } + return m; + } + + private add(geo: any, mat: LitMaterial, x: number, y: number): Object3D { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geo; mr.material = mat; mr.castShadow = true; + o.x = x; o.y = y; + this.scene.addChild(o); + return o; + } + + private build() { + const sphere = new SphereGeometry(2, 48, 48); + for (let i = 0; i < 8; i++) { + this.add(sphere, this.metal({ ior: 1.3, thickness: 100 + i * 100 }), (i - 3.5) * 5, 13); + this.add(sphere, this.metal({ ior: 1.1 + i * 0.13, thickness: 400 }), (i - 3.5) * 5, 7.5); + this.add(sphere, this.metal(null), (i - 3.5) * 5, 2); + } + this.hero = this.metal({ ior: 1.3, thickness: 400 }); + const torus = this.add(new TorusGeometry(4, 1.6, 96, 128), this.hero, 28, 7); + torus.rotationX = 70; + + const floorMat = new LitMaterial(); + floorMat.baseColor = new Color(0.5, 0.5, 0.52); floorMat.roughness = 0.9; floorMat.metallic = 0; + const floor = this.add(new BoxGeometry(140, 1, 80), floorMat, 5, -0.5); + floor.getComponent(MeshRenderer).castShadow = false; + } + + private initGUI() { + GUIHelp.init(); + const f = GUIHelp.addFolder('Iridescence (torus)'); + const s = { factor: 1, ior: 1.3, thickness: 400 }; + f.add(s, 'factor', 0, 1, 0.01).onChange((v: number) => this.hero.iridescence = v); + f.add(s, 'ior', 1, 2.5, 0.01).onChange((v: number) => this.hero.iridescenceIOR = v); + f.add(s, 'thickness', 50, 1200, 1).onChange((v: number) => this.hero.iridescenceThickness = v); + f.open(); + } +} + +new Sample_Iridescence().run(); diff --git a/samples/material/Sample_Sheen.ts b/samples/material/Sample_Sheen.ts new file mode 100644 index 000000000..09fdb3e3c --- /dev/null +++ b/samples/material/Sample_Sheen.ts @@ -0,0 +1,112 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LitMaterial, MeshRenderer, Object3D, Scene3D, SphereGeometry, TorusGeometry, View3D, +} from '@orillusion/core'; + +/** + * KHR_materials_sheen demo. + * + * Top row: the same dark-red base with sheen roughness 0.1 → 1.0 (tight rim + * → broad velvet glow). Middle row: one roughness, five sheen tints over a + * near-black base — the look of satin / velvet / microfibre. Bottom row: + * the same five base materials WITHOUT sheen, for an A/B comparison. + * The GUI drives the big torus on the right. + */ +class Sample_Sheen { + private scene: Scene3D; + private hero: LitMaterial; + + async run() { + const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 60 } } }); + this.scene = new Scene3D(); + this.scene.addComponent(AtmosphericComponent).sunY = 0.6; + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(45, engine.aspect, 0.1, 1000); + camera.object3D.addComponent(HoverCameraController).setCamera(15, -15, 46); + + const lightObj = new Object3D(); + lightObj.rotationX = 40; lightObj.rotationY = 140; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5600); + light.intensity = 3.5; + light.castShadow = true; + light.enableCSM = true; + this.scene.addChild(lightObj); + + this.build(); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + engine.startRenderView(view); + this.initGUI(); + } + + private cloth(base: Color, sheen: Color | null, sheenRoughness: number): LitMaterial { + const m = new LitMaterial(); + m.baseColor = base; + m.roughness = 0.9; + m.metallic = 0.0; + if (sheen) { + m.sheenRoughness = sheenRoughness; + m.sheenColor = sheen; + } + return m; + } + + private add(geo: any, mat: LitMaterial, x: number, y: number, z = 0): Object3D { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geo; mr.material = mat; mr.castShadow = true; + o.x = x; o.y = y; o.z = z; + this.scene.addChild(o); + return o; + } + + private build() { + const sphere = new SphereGeometry(2, 48, 48); + const darkRed = new Color(0.25, 0.02, 0.03); + + // Row 1: roughness sweep. + for (let i = 0; i < 6; i++) { + const r = 0.1 + i * 0.18; + this.add(sphere, this.cloth(darkRed, new Color(1, 0.75, 0.75), r), (i - 2.5) * 5, 13); + } + // Row 2 / 3: tints with and without sheen. + const tints = [new Color(1, 1, 1), new Color(1, 0.4, 0.4), new Color(1, 0.8, 0.3), new Color(0.4, 0.9, 0.6), new Color(0.4, 0.6, 1)]; + const bases = [new Color(0.03, 0.03, 0.03), new Color(0.2, 0.02, 0.02), new Color(0.2, 0.12, 0.02), new Color(0.02, 0.12, 0.05), new Color(0.02, 0.05, 0.2)]; + for (let i = 0; i < 5; i++) { + this.add(sphere, this.cloth(bases[i], tints[i], 0.5), (i - 2) * 5, 7.5); + this.add(sphere, this.cloth(bases[i], null, 0), (i - 2) * 5, 2); + } + // Hero object driven by the GUI. + this.hero = this.cloth(new Color(0.08, 0.02, 0.2), new Color(0.8, 0.6, 1.0), 0.4); + const torus = this.add(new TorusGeometry(4, 1.6, 96, 128), this.hero, 22, 7); + torus.rotationX = 70; + + const floorMat = new LitMaterial(); + floorMat.baseColor = new Color(0.5, 0.5, 0.52); floorMat.roughness = 0.9; floorMat.metallic = 0; + const floor = this.add(new BoxGeometry(120, 1, 80), floorMat, 5, -0.5); + floor.getComponent(MeshRenderer).castShadow = false; + } + + private initGUI() { + GUIHelp.init(); + const f = GUIHelp.addFolder('Sheen (torus)'); + const s = { enable: true, r: 0.8, g: 0.6, b: 1.0, roughness: 0.4 }; + const apply = () => { + this.hero.sheenRoughness = s.roughness; + this.hero.sheenColor = s.enable ? new Color(s.r, s.g, s.b) : new Color(0, 0, 0); + }; + f.add(s, 'enable').onChange(apply); + f.add(s, 'r', 0, 1, 0.01).onChange(apply); + f.add(s, 'g', 0, 1, 0.01).onChange(apply); + f.add(s, 'b', 0, 1, 0.01).onChange(apply); + f.add(s, 'roughness', 0, 1, 0.01).onChange(apply); + f.open(); + } +} + +new Sample_Sheen().run(); diff --git a/samples/pick/Sample_MeshBVHPick.ts b/samples/pick/Sample_MeshBVHPick.ts new file mode 100644 index 000000000..129533564 --- /dev/null +++ b/samples/pick/Sample_MeshBVHPick.ts @@ -0,0 +1,224 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { Stats } from '@orillusion/stats'; +import { + BoxGeometry, ColliderComponent, Color, Engine3D, LitMaterial, MeshBVH, MeshColliderShape, MeshRenderer, + Object3D, PointerEvent3D, Raycaster, Scene3D, SphereGeometry, TorusGeometry, UnLitMaterial, Vector3, View3D, +} from '@orillusion/core'; +import { createExampleScene, createSceneParam } from '@samples/utils/ExampleScene'; +import { GUIUtil } from '@samples/utils/GUIUtil'; + +/** + * MeshBVH picking demo. + * + * A 320k-triangle sphere, a 40k-triangle torus and a few boxes all carry a + * `MeshColliderShape`. Moving the mouse raycasts against the exact triangles + * every frame (bound-mode picking) and drops a marker at the hit point, + * oriented along the interpolated normal; the GUI shows the face index, uv, + * sub-mesh and how many colliders the ray crosses. + * + * Clicking runs a `Raycaster` over the whole scene (no colliders needed) + * and lists every hit along the ray; its BVH mode, side and first-hit-only + * options are in the GUI. A benchmark button fires random rays through both + * the BVH and the brute-force scan, reporting µs per ray and whether the + * results agree. + */ +class Sample_MeshBVHPick { + private scene: Scene3D; + private view: View3D; + private marker: Object3D; + private normalStick: Object3D; + private bigSphere: MeshRenderer; + private readonly raycaster = new Raycaster(); + private readonly stats = { + triangles: 0, bvhNodes: 0, bvhDepth: 0, buildMs: 0, + lastHit: '-', lastDistance: 0, faceIndex: -1, uv: '-', subMesh: -1, collidersOnRay: 0, + rayUseBVH: 'auto', raySide: 'material', rayFirstHitOnly: false, rayHits: '-', rayMs: 0, + benchRays: 2000, bvhUsPerRay: 0, bruteUsPerRay: 0, speedup: 0, mismatches: -1, + }; + + async run() { + const engine = await Engine3D.init({ + setting: { pick: { enable: true, mode: 'bound' }, shadow: { enable: true, shadowBound: 80 } }, + }); + const param = createSceneParam(); + param.camera.distance = 60; + param.camera.pitch = -20; + const ex = createExampleScene(engine, param); + this.scene = ex.scene; + this.view = ex.view; + this.scene.addComponent(Stats); + GUIHelp.init(); + GUIUtil.renderDirLight(ex.light, false); + + this.buildScene(); + engine.startRenderView(this.view); + this.initGUI(); + + this.view.pickFire.addEventListener(PointerEvent3D.PICK_MOVE, this.onPickMove, this); + this.view.pickFire.addEventListener(PointerEvent3D.PICK_CLICK, this.onPickClick, this); + } + + private addPickable(geometry: any, material: LitMaterial, pos: Vector3, scale = 1, name = ''): MeshRenderer { + const obj = new Object3D(); + obj.name = name; + obj.localPosition = pos; + obj.localScale = new Vector3(scale, scale, scale); + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + mr.material = material; + mr.castShadow = true; + // No `shape.mesh`: the collider picks the geometry of the MeshRenderer on the same object. + obj.addComponent(ColliderComponent).shape = new MeshColliderShape(); + this.scene.addChild(obj); + return mr; + } + + private buildScene() { + const mat = (r: number, g: number, b: number) => { const m = new LitMaterial(); m.baseColor = new Color(r, g, b); m.roughness = 0.5; return m; }; + + // 400×400 sphere ≈ 320k triangles — brute force would scan every one per mouse move. + const t0 = performance.now(); + const sphereGeo = new SphereGeometry(10, 400, 400); + this.bigSphere = this.addPickable(sphereGeo, mat(0.3, 0.6, 0.9), new Vector3(0, 10, 0), 1, 'sphere-320k'); + // Prebuild the tree so the first hover doesn't pay for it; the Raycaster's + // 'auto' mode also picks it up. + const bvh = MeshBVH.build(sphereGeo); + this.stats.buildMs = +(performance.now() - t0).toFixed(1); + this.stats.triangles = bvh.triCount; + this.stats.bvhNodes = bvh.nodeCount; + this.stats.bvhDepth = bvh.depth; + + // Torus with a non-uniform-scale-free but rotated transform; ~40k tris. + const torus = this.addPickable(new TorusGeometry(6, 2, 128, 160), mat(0.9, 0.6, 0.2), new Vector3(-24, 6, 0), 1, 'torus'); + torus.object3D.rotationX = 60; + + // Scaled boxes: exercises the world-space distance path under non-unit scale. + const box = new BoxGeometry(1, 1, 1); + for (let i = 0; i < 4; i++) { + const mr = this.addPickable(box, mat(0.5, 0.85, 0.4), new Vector3(20 + i * 7, 3, (i % 2) * 6 - 3), 6, 'box-' + i); + mr.object3D.rotationY = i * 25; + } + + // Floor (also pickable, so clicks on the ground report a hit too). + const floor = this.addPickable(new BoxGeometry(200, 1, 200), mat(0.6, 0.6, 0.62), new Vector3(0, -0.5, 0), 1, 'floor'); + floor.castShadow = false; + + // Hit marker: small sphere + stick pointing along the normal. + this.marker = new Object3D(); + const mm = this.marker.addComponent(MeshRenderer); + mm.geometry = new SphereGeometry(0.35, 12, 12); + const um = new UnLitMaterial(); um.baseColor = new Color(1, 0.1, 0.1); + mm.material = um; + mm.castShadow = false; + // Second, yellow sphere placed 1.5 units along the hit normal: the + // pair reads as a short "normal arrow" without any orientation math. + this.normalStick = new Object3D(); + const sm = this.normalStick.addComponent(MeshRenderer); + sm.geometry = new SphereGeometry(0.22, 10, 10); + const us = new UnLitMaterial(); us.baseColor = new Color(1, 1, 0.2); + sm.material = us; + sm.castShadow = false; + this.marker.transform.enable = false; + this.normalStick.transform.enable = false; + this.scene.addChild(this.marker); + this.scene.addChild(this.normalStick); + } + + private onPickMove(e: PointerEvent3D) { + const d = e.data; + if (!d || !e.target) return; + this.marker.transform.enable = true; + this.normalStick.transform.enable = true; + this.marker.localPosition = d.worldPos; + const n: Vector3 = d.worldNormal; + this.normalStick.localPosition = new Vector3(d.worldPos.x + n.x * 1.5, d.worldPos.y + n.y * 1.5, d.worldPos.z + n.z * 1.5); + this.stats.lastHit = e.target.name || '(unnamed)'; + this.stats.lastDistance = +(d.distance ?? 0).toFixed(2); + this.stats.faceIndex = d.faceIndex ?? -1; + this.stats.uv = d.uv ? `${d.uv.x.toFixed(3)}, ${d.uv.y.toFixed(3)}` : '-'; + this.stats.subMesh = d.subGeometryIndex ?? -1; + this.stats.collidersOnRay = d.hits?.length ?? 0; + } + + private onPickClick(e: PointerEvent3D) { + const mr = e.target?.getComponent(MeshRenderer); + if (mr && mr !== this.bigSphere) (mr.material as LitMaterial).baseColor = new Color(Math.random(), Math.random(), Math.random()); + + // Same click through a Raycaster: every triangle hit along the ray, scene-wide. + const rc = this.raycaster; + rc.useBVH = this.stats.rayUseBVH as any; + rc.side = this.stats.raySide as any; + rc.firstHitOnly = this.stats.rayFirstHitOnly; + rc.filter = r => r.object3D !== this.marker && r.object3D !== this.normalStick; + rc.setFromCamera(this.view.camera, e.mouseX, e.mouseY); + const t0 = performance.now(); + const hits = rc.intersectObject(this.scene); + this.stats.rayMs = +(performance.now() - t0).toFixed(2); + this.stats.rayHits = hits.length + ? hits.map(h => `${h.object3D.name}#${h.faceIndex}@${h.distance.toFixed(1)}${h.frontFace ? '' : '(back)'}`).join(' ') + : '-'; + console.log('[Raycaster]', hits); + } + + private benchmark() { + const bvh = MeshBVH.get(this.bigSphere.geometry); + const n = this.stats.benchRays; + // Random rays aimed at the sphere from a shell around it (local space). + const origins: Vector3[] = [], dirs: Vector3[] = []; + for (let i = 0; i < n; i++) { + const o = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize().multiplyScalar(30); + const jitter = new Vector3(Math.random() * 6 - 3, Math.random() * 6 - 3, Math.random() * 6 - 3); + const d = new Vector3(-o.x + jitter.x, -o.y + jitter.y, -o.z + jitter.z).normalize(); + origins.push(o); dirs.push(d); + } + const bvhT: number[] = [], bvhTri: number[] = []; + let t0 = performance.now(); + for (let i = 0; i < n; i++) { const h = bvh.raycast(origins[i], dirs[i]); bvhT.push(h ? h.t : -1); bvhTri.push(h ? h.triIndex : -1); } + const bvhMs = performance.now() - t0; + let mismatches = 0; + t0 = performance.now(); + for (let i = 0; i < n; i++) { + const h = bvh.raycastBruteForce(origins[i], dirs[i]); + const t = h ? h.t : -1; + if (Math.abs(t - bvhT[i]) > 1e-4) mismatches++; + } + const bruteMs = performance.now() - t0; + this.stats.bvhUsPerRay = +((bvhMs / n) * 1000).toFixed(1); + this.stats.bruteUsPerRay = +((bruteMs / n) * 1000).toFixed(1); + this.stats.speedup = +(bruteMs / Math.max(bvhMs, 1e-6)).toFixed(1); + this.stats.mismatches = mismatches; + console.log(`[MeshBVH] ${n} rays vs ${bvh.triCount} tris: BVH ${bvhMs.toFixed(1)} ms, brute ${bruteMs.toFixed(1)} ms, mismatches ${mismatches}`); + } + + private initGUI() { + const f = GUIHelp.addFolder('MeshBVH'); + f.add(this.stats, 'triangles').listen(); + f.add(this.stats, 'bvhNodes').listen(); + f.add(this.stats, 'bvhDepth').listen(); + f.add(this.stats, 'buildMs').listen(); + f.add(this.stats, 'lastHit').listen(); + f.add(this.stats, 'lastDistance').listen(); + f.add(this.stats, 'faceIndex').listen(); + f.add(this.stats, 'uv').listen(); + f.add(this.stats, 'subMesh').listen(); + f.add(this.stats, 'collidersOnRay').listen(); + f.open(); + const r = GUIHelp.addFolder('Raycaster (click)'); + r.add(this.stats, 'rayUseBVH', ['auto', 'always', 'never']); + r.add(this.stats, 'raySide', ['material', 'front', 'back', 'double']); + r.add(this.stats, 'rayFirstHitOnly'); + r.add(this.stats, 'rayHits').listen(); + r.add(this.stats, 'rayMs').listen(); + r.open(); + const b = GUIHelp.addFolder('Benchmark (sphere)'); + b.add(this.stats, 'benchRays', 100, 20000, 100); + b.add({ run: () => this.benchmark() }, 'run'); + b.add(this.stats, 'bvhUsPerRay').listen(); + b.add(this.stats, 'bruteUsPerRay').listen(); + b.add(this.stats, 'speedup').listen(); + b.add(this.stats, 'mismatches').listen(); + b.open(); + } +} + +new Sample_MeshBVHPick().run(); diff --git a/samples/pick/Sample_SkinnedMeshPick.ts b/samples/pick/Sample_SkinnedMeshPick.ts new file mode 100644 index 000000000..a4bb2afe6 --- /dev/null +++ b/samples/pick/Sample_SkinnedMeshPick.ts @@ -0,0 +1,190 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { Stats } from '@orillusion/stats'; +import { + AnimatorComponent, Color, ComponentBase, Engine3D, MeshDeformer, MeshRenderer, Object3D, Object3DUtil, Raycaster, + RaycastHit, Scene3D, SphereGeometry, UnLitMaterial, Vector3, View3D, +} from '@orillusion/core'; +import { createExampleScene, createSceneParam } from '@samples/utils/ExampleScene'; + +/** + * Picking skinned and morph-target meshes. + * + * Two animated soldiers (glTF skin) and a lion with blend shapes. Every + * frame a `Raycaster` is cast through the mouse position against the + * characters: the GPU deforms these meshes in the vertex shader, so the + * raycaster replays that deformation on the CPU (`MeshDeformer`) and the + * red marker sticks to the surface as drawn, while it animates under a + * still mouse. The blue marker is the same ray against the bind pose + * (`deformation = 'bindPose'`), which is what picking would report without + * CPU deformation. The yellow dot points along the hit normal. + */ +class Sample_SkinnedMeshPick { + private scene: Scene3D; + private view: View3D; + private characters: Object3D; + private soldiers: Object3D[] = []; + private animators: AnimatorComponent[] = []; + private lion: Object3D; + private lionAnimator: AnimatorComponent; + private hitMarker: Object3D; + private normalMarker: Object3D; + private bindMarker: Object3D; + private readonly raycaster = new Raycaster(); + private readonly bindRaycaster = new Raycaster(); + private readonly stats = { + animate: true, clip: 'Run', showBindPose: true, + lastHit: '-', faceIndex: -1, uv: '-', distance: 0, pickMs: 0, deformedVertices: 0, bindPoseOffset: '-', + }; + private readonly morph: { [key: string]: number } = {}; + + async run() { + const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 200 } } }); + const param = createSceneParam(); + param.camera.distance = 150; + param.camera.pitch = -12; + const ex = createExampleScene(engine, param); + this.scene = ex.scene; + this.view = ex.view; + ex.hoverCtrl.setCamera(0, -12, 150, new Vector3(20, 18, 0)); + this.scene.addComponent(Stats); + GUIHelp.init(); + + this.scene.addChild(Object3DUtil.GetSingleCube(400, 1, 400, 0.45, 0.45, 0.48)); + this.characters = new Object3D(); + this.scene.addChild(this.characters); + await this.loadSoldiers(engine); + await this.loadLion(engine); + this.createMarkers(); + this.bindRaycaster.deformation = 'bindPose'; + + engine.startRenderView(this.view); + this.initGUI(); + // Re-pick every frame: the characters move under a still mouse. + this.scene.addComponent(PickEveryFrame).sample = this; + } + + private async loadSoldiers(engine: Engine3D) { + const soldier = await engine.res.loadGltf('gltfs/glb/Soldier.glb'); + soldier.scaleX = soldier.scaleY = soldier.scaleZ = 20; + soldier.rotationY = 200; + soldier.x = -20; + this.characters.addChild(soldier); + const walker = soldier.clone(); + walker.x = 15; + walker.rotationY = 160; + this.characters.addChild(walker); + this.soldiers = [soldier, walker]; + this.animators = this.soldiers.map(s => s.getComponentsInChild(AnimatorComponent)[0]); + this.animators[0].playAnim('Run'); + this.animators[1].playAnim('Walk'); + } + + private async loadLion(engine: Engine3D) { + const lion = await engine.res.loadGltf('gltfs/glb/lion.glb'); + lion.scaleX = lion.scaleY = lion.scaleZ = 0.4; + this.characters.addChild(lion); + this.lion = lion; + // Stand it on the ground at x = 55 using its bounds. + let minY = Infinity, cx = 0, n = 0; + for (const r of lion.getComponentsInChild(MeshRenderer)) { + const b = r.geometry.bounds, m = r.transform.worldMatrix; + for (const p of [b.min, b.max]) { + const w = m.transformPoint(p.clone()); + minY = Math.min(minY, w.y); cx += w.x; n++; + } + } + lion.y -= minY; + lion.x += 55 - cx / n; + this.lionAnimator = lion.addComponent(AnimatorComponent); + for (const key in this.lionAnimator.cloneMorphRenderers()) this.morph[key] = 0; + } + + private createMarkers() { + const dot = (r: number, color: Color) => { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = new SphereGeometry(r, 16, 16); + const m = new UnLitMaterial(); + m.baseColor = color; + mr.material = m; + mr.castShadow = false; + o.transform.enable = false; + this.scene.addChild(o); + return o; + }; + this.hitMarker = dot(1.1, new Color(1, 0.15, 0.1)); + this.normalMarker = dot(0.6, new Color(1, 0.95, 0.2)); + this.bindMarker = dot(0.9, new Color(0.2, 0.5, 1)); + } + + /** Called every frame by PickEveryFrame. */ + public pick() { + const input = this.view.engine3D.inputSystem; + const camera = this.view.camera; + this.raycaster.setFromCamera(camera, input.mouseX, input.mouseY); + const t0 = performance.now(); + const hit = this.raycaster.intersectFirst(this.characters); + this.stats.pickMs = +(performance.now() - t0).toFixed(2); + this.place(hit); + + let bind: RaycastHit = null; + if (this.stats.showBindPose) { + this.bindRaycaster.setFromCamera(camera, input.mouseX, input.mouseY); + bind = this.bindRaycaster.intersectFirst(this.characters); + } + this.bindMarker.transform.enable = !!bind; + if (bind) this.bindMarker.localPosition = bind.point; + this.stats.bindPoseOffset = hit && bind ? Vector3.distance(hit.point, bind.point).toFixed(2) : '-'; + } + + private place(hit: RaycastHit) { + this.hitMarker.transform.enable = this.normalMarker.transform.enable = !!hit; + if (!hit) { + this.stats.lastHit = '-'; + return; + } + this.hitMarker.localPosition = hit.point; + const n = hit.normal; + this.normalMarker.localPosition = new Vector3(hit.point.x + n.x * 3, hit.point.y + n.y * 3, hit.point.z + n.z * 3); + this.stats.lastHit = hit.object3D.name || '(unnamed)'; + this.stats.faceIndex = hit.faceIndex; + this.stats.uv = hit.uv ? `${hit.uv.x.toFixed(3)}, ${hit.uv.y.toFixed(3)}` : '-'; + this.stats.distance = +hit.distance.toFixed(2); + const deformed = MeshDeformer.deform(hit.renderer); + this.stats.deformedVertices = deformed ? deformed.geometry.getAttribute('position').data.length / 3 : 0; + } + + private initGUI() { + const a = GUIHelp.addFolder('Animation'); + a.add(this.stats, 'animate').onChange((v: boolean) => this.animators.forEach(an => an.timeScale = v ? 1 : 0)); + a.add(this.stats, 'clip', ['Idle', 'Walk', 'Run', 'TPose']).onChange((v: string) => this.animators[0].playAnim(v)); + a.open(); + const m = GUIHelp.addFolder('Lion blend shapes'); + for (const key in this.morph) { + m.add(this.morph, key, 0, 1, 0.01).onChange((v: number) => { + this.lionAnimator.updateBlendShape(['blendShape', 'blendShape', key], 'blendShape.blendShape.' + key, v); + }); + } + m.open(); + const p = GUIHelp.addFolder('Pick (mouse)'); + p.add(this.raycaster, 'deformation', ['cpu', 'bindPose', 'skip']); + p.add(this.stats, 'showBindPose'); + p.add(this.stats, 'lastHit').listen(); + p.add(this.stats, 'faceIndex').listen(); + p.add(this.stats, 'uv').listen(); + p.add(this.stats, 'distance').listen(); + p.add(this.stats, 'bindPoseOffset').listen(); + p.add(this.stats, 'deformedVertices').listen(); + p.add(this.stats, 'pickMs').listen(); + p.open(); + } +} + +class PickEveryFrame extends ComponentBase { + public sample: Sample_SkinnedMeshPick; + onUpdate() { + this.sample?.pick(); + } +} + +new Sample_SkinnedMeshPick().run(); diff --git a/samples/post/Sample_Lens.ts b/samples/post/Sample_Lens.ts new file mode 100644 index 000000000..e769da115 --- /dev/null +++ b/samples/post/Sample_Lens.ts @@ -0,0 +1,102 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LensPost, LitMaterial, MeshRenderer, Object3D, PostProcessingComponent, Scene3D, SphereGeometry, View3D, +} from '@orillusion/core'; + +/** + * LensPost demo — vignette, chromatic aberration and film grain. + * + * A grid of high-contrast white/black pillars makes the colour fringing easy + * to see toward the screen edges; the flat sky shows the vignette falloff and + * the grain. Every parameter is on the GUI, plus an on/off toggle that + * attaches / detaches the post. + */ +class Sample_Lens { + private scene: Scene3D; + private post: PostProcessingComponent; + private lens: LensPost; + + async run() { + const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 120 } } }); + this.scene = new Scene3D(); + this.scene.addComponent(AtmosphericComponent).sunY = 0.65; + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(60, engine.aspect, 0.1, 2000); + camera.object3D.addComponent(HoverCameraController).setCamera(30, -18, 70); + + const lightObj = new Object3D(); + lightObj.rotationX = 50; lightObj.rotationY = 130; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5600); + light.intensity = 3; light.castShadow = true; + this.scene.addChild(lightObj); + + this.build(); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + engine.startRenderView(view); + + this.post = this.scene.addComponent(PostProcessingComponent); + this.lens = this.post.addPost(LensPost); + this.lens.vignetteIntensity = 0.55; + this.lens.chromaticAberration = 0.3; + this.lens.grainIntensity = 0.15; + this.initGUI(); + } + + private build() { + const white = new LitMaterial(); white.baseColor = new Color(0.95, 0.95, 0.95); white.roughness = 0.7; white.metallic = 0; + const black = new LitMaterial(); black.baseColor = new Color(0.02, 0.02, 0.02); black.roughness = 0.7; black.metallic = 0; + const accent = new LitMaterial(); accent.baseColor = new Color(0.9, 0.2, 0.1); accent.roughness = 0.4; accent.metallic = 0; + const pillar = new BoxGeometry(3, 1, 3); + for (let x = -7; x <= 7; x++) { + for (let z = -7; z <= 7; z++) { + const h = 4 + ((x * 7 + z * 13) & 7) * 2.2; + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = pillar; + mr.material = (x + z) & 1 ? white : black; + mr.castShadow = true; + o.x = x * 8; o.z = z * 8; o.y = h / 2; o.scaleY = h; + this.scene.addChild(o); + } + } + const ball = new Object3D(); + const bm = ball.addComponent(MeshRenderer); + bm.geometry = new SphereGeometry(6, 48, 48); bm.material = accent; bm.castShadow = true; + ball.y = 26; + this.scene.addChild(ball); + + const floor = new Object3D(); + const fm = floor.addComponent(MeshRenderer); + fm.geometry = new BoxGeometry(400, 1, 400); + const mat = new LitMaterial(); mat.baseColor = new Color(0.5, 0.5, 0.5); mat.roughness = 0.9; mat.metallic = 0; + fm.material = mat; fm.castShadow = false; + floor.y = -0.5; + this.scene.addChild(floor); + } + + private initGUI() { + GUIHelp.init(); + const f = GUIHelp.addFolder('LensPost'); + const state = { enable: true }; + f.add(state, 'enable').onChange((v: boolean) => { + if (v) this.lens = this.post.addPost(LensPost); + else this.post.removePost(LensPost); + }); + const l = this.lens; + f.add(l, 'vignetteIntensity', 0, 1.5, 0.01); + f.add(l, 'vignetteSmoothness', 0, 1, 0.01); + f.add(l, 'vignetteRoundness', 0, 1, 0.01); + f.add(l, 'chromaticAberration', 0, 3, 0.01); + f.add(l, 'grainIntensity', 0, 1, 0.01); + f.add(l, 'grainStatic'); + f.open(); + } +} + +new Sample_Lens().run(); diff --git a/samples/post/Sample_MotionBlur.ts b/samples/post/Sample_MotionBlur.ts new file mode 100644 index 000000000..9b32add45 --- /dev/null +++ b/samples/post/Sample_MotionBlur.ts @@ -0,0 +1,103 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LitMaterial, MeshRenderer, MotionBlurPost, Object3D, PostProcessingComponent, Scene3D, Time, View3D, +} from '@orillusion/core'; + +/** + * MotionBlurPost demo — the camera orbits a field of pillars on its own; + * the faster it turns, the longer the streaks. Drag to look around (the + * blur follows your own camera motion too), and use the GUI to change the + * shutter, sample count and clamp, or to pause the orbit and see the image + * snap back to sharp. + */ +class Sample_MotionBlur { + private scene: Scene3D; + private ctrl: HoverCameraController; + private post: PostProcessingComponent; + private blur: MotionBlurPost; + private readonly state = { enable: true, orbitSpeed: 60, roll: 30 }; + + async run() { + const engine = await Engine3D.init({ + renderLoop: () => this.loop(), + setting: { shadow: { enable: true, shadowBound: 140 } }, + }); + this.scene = new Scene3D(); + this.scene.addComponent(AtmosphericComponent).sunY = 0.65; + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(60, engine.aspect, 0.1, 2000); + this.ctrl = camera.object3D.addComponent(HoverCameraController); + this.ctrl.setCamera(this.state.roll, -14, 75); + + const lightObj = new Object3D(); + lightObj.rotationX = 50; lightObj.rotationY = 130; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5600); + light.intensity = 3; light.castShadow = true; + this.scene.addChild(lightObj); + + this.build(); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + engine.startRenderView(view); + + this.post = this.scene.addComponent(PostProcessingComponent); + this.blur = this.post.addPost(MotionBlurPost); + this.blur.intensity = 1; + this.initGUI(); + } + + private build() { + const palette = [new Color(0.95, 0.95, 0.95), new Color(0.05, 0.05, 0.05), new Color(0.9, 0.25, 0.15), new Color(0.15, 0.4, 0.9), new Color(0.95, 0.8, 0.2)]; + const mats = palette.map(c => { const m = new LitMaterial(); m.baseColor = c; m.roughness = 0.7; m.metallic = 0; return m; }); + const pillar = new BoxGeometry(3, 1, 3); + for (let x = -8; x <= 8; x++) { + for (let z = -8; z <= 8; z++) { + if (Math.abs(x) < 2 && Math.abs(z) < 2) continue; + const h = 5 + ((x * 7 + z * 13) & 7) * 2.5; + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = pillar; + mr.material = mats[Math.abs(x * 3 + z * 5) % mats.length]; + mr.castShadow = true; + o.x = x * 8; o.z = z * 8; o.y = h / 2; o.scaleY = h; + this.scene.addChild(o); + } + } + const floor = new Object3D(); + const fm = floor.addComponent(MeshRenderer); + fm.geometry = new BoxGeometry(400, 1, 400); + const mat = new LitMaterial(); mat.baseColor = new Color(0.5, 0.5, 0.5); mat.roughness = 0.9; mat.metallic = 0; + fm.material = mat; fm.castShadow = false; + floor.y = -0.5; + this.scene.addChild(floor); + } + + private loop() { + if (!this.ctrl) return; + this.state.roll += this.state.orbitSpeed * Time.delta * 0.001; + this.ctrl.roll = this.state.roll; + } + + private initGUI() { + GUIHelp.init(); + const f = GUIHelp.addFolder('MotionBlurPost'); + f.add(this.state, 'enable').onChange((v: boolean) => { + if (v) this.blur = this.post.addPost(MotionBlurPost); + else this.post.removePost(MotionBlurPost); + }); + f.add(this.state, 'orbitSpeed', 0, 240, 1); + const b = this.blur; + f.add(b, 'intensity', 0, 2, 0.01); + f.add(b, 'samples', 2, 32, 1); + f.add(b, 'maxBlurPixels', 0, 200, 1); + f.add(b, 'frameRateIndependent'); + f.open(); + } +} + +new Sample_MotionBlur().run(); diff --git a/samples/post/Sample_Tonemap.ts b/samples/post/Sample_Tonemap.ts new file mode 100644 index 000000000..89330c388 --- /dev/null +++ b/samples/post/Sample_Tonemap.ts @@ -0,0 +1,109 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { + AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, + LitMaterial, MeshRenderer, Object3D, Scene3D, SphereGeometry, TonemapMode, TonemapUtil, View3D, +} from '@orillusion/core'; + +/** + * Tone-mapping comparison. + * + * Six rows of emissive spheres (red, orange, green, cyan, blue, white), each + * row ramping from 0.25× to 32× intensity, above a lit PBR strip. Switch the + * curve in the GUI and watch the bright end of every row: + * None clips hard to pure primaries + * ACES saturated, hue-shifts toward white late + * Reinhard soft roll-off, controlled by whitePoint + * Uncharted2 filmic shoulder, darker mids + * AgX bright saturated colors desaturate smoothly toward white + * Neutral colors under ~0.76 stay as authored, highlights compress + * The GUI also prints what `TonemapUtil.apply` (the CPU mirror of the shader) + * returns for a probe color, so the two can be compared by eye. + */ +class Sample_Tonemap { + private engine: Engine3D; + private scene: Scene3D; + private readonly probe = { input: '(4.00, 1.00, 0.25)', output: '' }; + + async run() { + this.engine = await Engine3D.init({}); + this.scene = new Scene3D(); + const sky = this.scene.addComponent(AtmosphericComponent); + sky.sunY = 0.62; + + const camera = CameraUtil.createCamera3DObject(this.scene); + camera.perspective(50, this.engine.aspect, 0.1, 2000); + camera.object3D.addComponent(HoverCameraController).setCamera(0, -12, 42); + + const lightObj = new Object3D(); + lightObj.rotationX = 45; lightObj.rotationY = 120; + const light = lightObj.addComponent(DirectLight); + light.lightColor = KelvinUtil.color_temperature_to_rgb(5500); + light.intensity = 3; + this.scene.addChild(lightObj); + + this.buildRamp(); + + const view = new View3D(); + view.scene = this.scene; + view.camera = camera; + this.engine.startRenderView(view); + this.initGUI(); + } + + private buildRamp() { + const hues: [number, number, number][] = [ + [1, 0.05, 0.05], [1, 0.45, 0.05], [0.1, 1, 0.1], [0.05, 0.9, 0.9], [0.1, 0.2, 1], [1, 1, 1], + ]; + const steps = 8; // 0.25, 0.5, 1, 2, 4, 8, 16, 32 + const geo = new SphereGeometry(1.1, 32, 32); + for (let row = 0; row < hues.length; row++) { + for (let i = 0; i < steps; i++) { + const intensity = 0.25 * Math.pow(2, i); + const mat = new LitMaterial(); + mat.baseColor = new Color(0, 0, 0, 1); + mat.emissiveColor = new Color(hues[row][0], hues[row][1], hues[row][2], 1); + mat.emissiveIntensity = intensity; + mat.roughness = 1; + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geo; + mr.material = mat; + o.x = (i - (steps - 1) / 2) * 3; + o.y = (hues.length - 1 - row) * 3 + 2; + this.scene.addChild(o); + } + } + // Lit strip: shows how each curve treats ordinary diffuse/specular shading. + const colors = [new Color(0.8, 0.1, 0.1), new Color(0.9, 0.6, 0.1), new Color(0.1, 0.6, 0.2), new Color(0.1, 0.3, 0.8), new Color(0.8, 0.8, 0.8)]; + const box = new BoxGeometry(4.4, 1, 6); + colors.forEach((c, i) => { + const mat = new LitMaterial(); + mat.baseColor = c; mat.roughness = 0.35; mat.metallic = 0.1; + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = box; mr.material = mat; + o.x = (i - 2) * 4.8; o.y = -0.5; + this.scene.addChild(o); + }); + } + + private initGUI() { + GUIHelp.init(); + const tm = this.engine.setting.render.tonemap; + const f = GUIHelp.addFolder('Tonemap'); + const refresh = () => { + const o = TonemapUtil.apply(tm.mode, [4, 1, 0.25], tm.exposure, tm.whitePoint ?? 4); + this.probe.output = `(${o.map(v => v.toFixed(3)).join(', ')})`; + }; + f.add(tm, 'mode', TonemapUtil.MODES).onChange((v: TonemapMode) => { tm.mode = v; refresh(); }); + f.add(tm, 'exposure', 0.05, 8, 0.01).onChange(refresh); + f.add(tm, 'whitePoint', 1, 16, 0.1).onChange(refresh); + f.add(tm, 'enable'); + f.add(this.probe, 'input').listen(); + f.add(this.probe, 'output').listen(); + f.open(); + refresh(); + } +} + +new Sample_Tonemap().run(); diff --git a/samples/render/Sample_LOD.ts b/samples/render/Sample_LOD.ts new file mode 100644 index 000000000..297439ad5 --- /dev/null +++ b/samples/render/Sample_LOD.ts @@ -0,0 +1,151 @@ +import { GUIHelp } from '@orillusion/debug/GUIHelp'; +import { Stats } from '@orillusion/stats'; +import { + BoxGeometry, Color, Engine3D, GeometryBase, LitMaterial, LODGroup, LODMode, + MeshRenderer, Object3D, PlaneGeometry, Scene3D, SphereGeometry, Vector3, View3D, +} from '@orillusion/core'; +import { createExampleScene, createSceneParam } from '@samples/utils/ExampleScene'; +import { GUIUtil } from '@samples/utils/GUIUtil'; + +/** + * LODGroup demo — a 24×24 field of objects, each with three detail levels: + * L0 high-poly sphere (green) 48×48 segments, 4.6k tris + * L1 low-poly sphere (yellow) 8×8 segments, 128 tris + * L2 box impostor (red) 12 tris + * culled beyond the last threshold + * Colors make the active level visible at a glance. Zoom / orbit the camera + * and watch the rings change; the GUI shows live counts per level and lets + * you switch between screen-size and distance metrics, tweak bias / + * hysteresis, or force a level. + */ +class Sample_LOD { + private engine: Engine3D; + private scene: Scene3D; + private view: View3D; + private groups: LODGroup[] = []; + private counts = { L0: 0, L1: 0, L2: 0, culled: 0, triangles: 0 }; + private readonly trisPerLevel = [48 * 48 * 2, 8 * 8 * 2, 12]; + + async run() { + this.engine = await Engine3D.init({ + renderLoop: () => this.loop(), + setting: { shadow: { enable: true, shadowBound: 200, shadowSize: 2048 } }, + }); + + const param = createSceneParam(); + param.camera.distance = 90; + param.camera.pitch = -35; + param.camera.far = 2000; + param.light.castShadow = true; + const ex = createExampleScene(this.engine, param); + ex.hoverCtrl.maxDistance = 1500; + this.scene = ex.scene; + this.view = ex.view; + this.scene.addComponent(Stats); + + this.buildFloor(); + this.buildField(); + + this.engine.startRenderView(this.view); + this.initGUI(ex.light); + } + + private buildFloor() { + const floor = new Object3D(); + const mr = floor.addComponent(MeshRenderer); + mr.geometry = new PlaneGeometry(400, 400); + const mat = new LitMaterial(); + mat.baseColor = new Color(0.55, 0.55, 0.6); + mat.roughness = 0.9; + mr.material = mat; + mr.castShadow = false; + this.scene.addChild(floor); + } + + private buildField() { + // Shared geometries + materials: LOD only toggles visibility, so 576 + // groups cost 3 geometries and 3 materials total. + const geos: GeometryBase[] = [ + new SphereGeometry(1.5, 48, 48), + new SphereGeometry(1.5, 8, 8), + new BoxGeometry(2.4, 2.4, 2.4), + ]; + const colors = [new Color(0.25, 0.85, 0.35), new Color(0.95, 0.85, 0.2), new Color(0.9, 0.3, 0.25)]; + const mats = colors.map(c => { const m = new LitMaterial(); m.baseColor = c; m.roughness = 0.6; return m; }); + + const n = 24, spacing = 6; + for (let ix = 0; ix < n; ix++) { + for (let iz = 0; iz < n; iz++) { + const root = new Object3D(); + root.localPosition = new Vector3((ix - n / 2 + 0.5) * spacing, 1.5, (iz - n / 2 + 0.5) * spacing); + const lod = root.addComponent(LODGroup); + for (let l = 0; l < 3; l++) { + const obj = new Object3D(); + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geos[l]; + mr.material = mats[l]; + mr.castShadow = true; + root.addChild(obj); + // ScreenSize thresholds: sphere diameter as a fraction of viewport height. + lod.addLevel(obj, [0.12, 0.05, 0.015][l]); + } + this.scene.addChild(root); + this.groups.push(lod); + } + } + } + + private loop() { + const c = this.counts; + c.L0 = c.L1 = c.L2 = c.culled = c.triangles = 0; + for (const g of this.groups) { + const l = g.currentLevel; + if (l === LODGroup.CULLED) c.culled++; + else { (l === 0 ? c.L0++ : l === 1 ? c.L1++ : c.L2++); c.triangles += this.trisPerLevel[l]; } + } + } + + private initGUI(light: any) { + GUIHelp.init(); + const f = GUIHelp.addFolder('LOD'); + const state = { + mode: 'ScreenSize', + bias: 1, + hysteresis: 0.1, + cullBeyondLast: true, + forceLevel: 'auto', + }; + // Distance thresholds are only used when the mode is switched. + const distThresholds = [25, 60, 200]; + const sizeThresholds = [0.12, 0.05, 0.015]; + + f.add(state, 'mode', ['ScreenSize', 'Distance']).onChange((v: string) => { + const mode = v === 'Distance' ? LODMode.Distance : LODMode.ScreenSize; + const th = mode === LODMode.Distance ? distThresholds : sizeThresholds; + for (const g of this.groups) { + g.mode = mode; + g.setThresholds(th); + } + }); + f.add(state, 'bias', 0.25, 4, 0.05).onChange((v: number) => this.groups.forEach(g => g.bias = v)); + f.add(state, 'hysteresis', 0, 0.5, 0.01).onChange((v: number) => this.groups.forEach(g => g.hysteresis = v)); + f.add(state, 'cullBeyondLast').onChange((v: boolean) => this.groups.forEach(g => g.cullBeyondLast = v)); + f.add(state, 'forceLevel', ['auto', '0', '1', '2', 'culled']).onChange((v: string) => { + const lvl = v === 'auto' ? null : v === 'culled' ? LODGroup.CULLED : Number(v); + for (const g of this.groups) g.forceLevel = lvl; + }); + f.open(); + + const stats = GUIHelp.addFolder('Live counts'); + stats.add(this.counts, 'L0').listen(); + stats.add(this.counts, 'L1').listen(); + stats.add(this.counts, 'L2').listen(); + stats.add(this.counts, 'culled').listen(); + stats.add(this.counts, 'triangles').listen(); + stats.open(); + + GUIUtil.renderDirLight(light, false); + } +} + +new Sample_LOD().run(); diff --git a/samples/sprite/Sample_Label.ts b/samples/sprite/Sample_Label.ts index ec2f40bab..0810e18c1 100644 --- a/samples/sprite/Sample_Label.ts +++ b/samples/sprite/Sample_Label.ts @@ -62,7 +62,9 @@ class Sample_Label { let camera = CameraUtil.createCamera3DObject(this.scene); camera.perspective(60, this.engine.aspect, 0.1, 5000.0); - camera.object3D.addComponent(HoverCameraController).setCamera(0, -15, 30); + // 10 m is the reference depth for distanceInvariantSize, so the label + // `size` values below are literal world units at this distance. + camera.object3D.addComponent(HoverCameraController).setCamera(0, -15, 10); this.view = new View3D(); this.view.scene = this.scene; diff --git a/samples/utils/GLBBuilder.ts b/samples/utils/GLBBuilder.ts new file mode 100644 index 000000000..7ef7877ed --- /dev/null +++ b/samples/utils/GLBBuilder.ts @@ -0,0 +1,178 @@ +/** + * Tiny in-memory glTF binary (GLB) writer, plus a procedurally generated + * test asset that exercises KHR_mesh_quantization, KHR_materials_specular, + * KHR_materials_sheen and KHR_materials_variants without shipping a file. + */ + +/** Pack a glTF JSON object and its single binary buffer into a .glb Blob. */ +export function buildGLB(json: any, bin: ArrayBuffer): Blob { + const pad4 = (n: number) => (4 - (n % 4)) % 4; + const jsonBytes = new TextEncoder().encode(JSON.stringify(json)); + const jsonPad = pad4(jsonBytes.length), binPad = pad4(bin.byteLength); + const total = 12 + 8 + jsonBytes.length + jsonPad + 8 + bin.byteLength + binPad; + const out = new ArrayBuffer(total); + const dv = new DataView(out); + const u8 = new Uint8Array(out); + let o = 0; + dv.setUint32(o, 0x46546c67, true); o += 4; // 'glTF' + dv.setUint32(o, 2, true); o += 4; + dv.setUint32(o, total, true); o += 4; + dv.setUint32(o, jsonBytes.length + jsonPad, true); o += 4; + dv.setUint32(o, 0x4e4f534a, true); o += 4; // 'JSON' + u8.set(jsonBytes, o); o += jsonBytes.length; + for (let i = 0; i < jsonPad; i++) u8[o++] = 0x20; // space padding + dv.setUint32(o, bin.byteLength + binPad, true); o += 4; + dv.setUint32(o, 0x004e4942, true); o += 4; // 'BIN\0' + u8.set(new Uint8Array(bin), o); + return new Blob([out], { type: 'model/gltf-binary' }); +} + +/** Append typed arrays into one buffer with 4-byte alignment; returns bufferViews. */ +class BinWriter { + private chunks: Uint8Array[] = []; + private length = 0; + public views: { buffer: number; byteOffset: number; byteLength: number }[] = []; + add(data: ArrayBufferView): number { + const pad = (4 - (this.length % 4)) % 4; + if (pad) { this.chunks.push(new Uint8Array(pad)); this.length += pad; } + this.views.push({ buffer: 0, byteOffset: this.length, byteLength: data.byteLength }); + this.chunks.push(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); + this.length += data.byteLength; + return this.views.length - 1; + } + finish(): ArrayBuffer { + const out = new Uint8Array(this.length); + let o = 0; + for (const c of this.chunks) { out.set(c, o); o += c.length; } + return out.buffer; + } +} + +export interface VariantsDemoInfo { + blob: Blob; + /** Vertex count of the quantized sphere. */ + sphereVertices: number; + /** Triangle count of the non-indexed ribbon (deliberately > 85). */ + ribbonTriangles: number; + variantNames: string[]; +} + +/** + * A quantized UV sphere (int16-normalized positions under a ×`radius` node + * scale, int8-normalized normals, uint16-normalized UVs) with three material + * variants, plus a NON-indexed float ribbon mesh that no variant mentions. + */ +export function buildVariantsDemoGLB(radius: number = 2, segments: number = 32): VariantsDemoInfo { + const w = new BinWriter(); + + // ---- quantized sphere ---- + const cols = segments + 1, rows = segments + 1; + const n = cols * rows; + const pos = new Int16Array(n * 3), nor = new Int8Array(n * 3), uv = new Uint16Array(n * 2); + // glTF requires each vertex attribute stride to be a multiple of 4 bytes: + // int8 vec3 → pad to 4 bytes per vertex via byteStride. + const norPadded = new Int8Array(n * 4); + // int16 vec3 = 6 bytes → stride 8. + const posPadded = new Int16Array(n * 4); + for (let y = 0; y < rows; y++) { + for (let x = 0; x < cols; x++) { + const i = y * cols + x; + const theta = (x / segments) * Math.PI * 2, phi = (y / segments) * Math.PI; + const px = Math.sin(phi) * Math.cos(theta), py = Math.cos(phi), pz = Math.sin(phi) * Math.sin(theta); + pos[i * 3] = Math.round(px * 32767); pos[i * 3 + 1] = Math.round(py * 32767); pos[i * 3 + 2] = Math.round(pz * 32767); + nor[i * 3] = Math.round(px * 127); nor[i * 3 + 1] = Math.round(py * 127); nor[i * 3 + 2] = Math.round(pz * 127); + posPadded.set(pos.subarray(i * 3, i * 3 + 3), i * 4); + norPadded.set(nor.subarray(i * 3, i * 3 + 3), i * 4); + uv[i * 2] = Math.round((x / segments) * 65535); uv[i * 2 + 1] = Math.round((y / segments) * 65535); + } + } + const idx: number[] = []; + for (let y = 0; y < segments; y++) { + for (let x = 0; x < segments; x++) { + const a = y * cols + x, b = a + 1, c = a + cols, d = c + 1; + idx.push(a, b, c, b, d, c); + } + } + const indices = new Uint16Array(idx); + const vPos = w.add(posPadded), vNor = w.add(norPadded), vUv = w.add(uv), vIdx = w.add(indices); + + // ---- non-indexed float ribbon: 100 triangles ---- + const tris = 100; + const rp = new Float32Array(tris * 9), rn = new Float32Array(tris * 9); + for (let t = 0; t < tris; t++) { + const x0 = (t - tris / 2) * 0.12, x1 = x0 + 0.1; + const up = t % 2 === 0; + const y0 = -3.2, y1 = -2.9; + // counter-clockwise when seen from +Z + const v = up ? [x0, y0, 0, x1, y0, 0, x0, y1, 0] : [x0, y1, 0, x1, y0, 0, x1, y1, 0]; + rp.set(v, t * 9); + for (let k = 0; k < 3; k++) rn.set([0, 0, 1], t * 9 + k * 3); + } + const vRp = w.add(rp), vRn = w.add(rn); + + const views: any[] = w.views.map(v => ({ ...v })); + views[vPos].byteStride = 8; + views[vNor].byteStride = 4; + + const variantNames = ['Crimson', 'Ocean', 'Velvet']; + const json = { + asset: { version: '2.0', generator: 'orillusion-samples GLBBuilder' }, + extensionsUsed: ['KHR_mesh_quantization', 'KHR_materials_variants', 'KHR_materials_specular', 'KHR_materials_sheen'], + extensionsRequired: ['KHR_mesh_quantization'], + extensions: { KHR_materials_variants: { variants: variantNames.map(name => ({ name })) } }, + scene: 0, + scenes: [{ nodes: [0, 1] }], + nodes: [ + { name: 'QuantizedSphere', mesh: 0, scale: [radius, radius, radius] }, + { name: 'Ribbon', mesh: 1 }, + ], + meshes: [ + { + name: 'SphereMesh', + primitives: [{ + attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, + indices: 3, + material: 0, + extensions: { + KHR_materials_variants: { + mappings: [ + { material: 1, variants: [0] }, + { material: 2, variants: [1] }, + { material: 3, variants: [2] }, + ], + }, + }, + }], + }, + { name: 'RibbonMesh', primitives: [{ attributes: { POSITION: 4, NORMAL: 5 }, material: 4 }] }, + ], + materials: [ + { + name: 'Default_Steel', + pbrMetallicRoughness: { baseColorFactor: [0.6, 0.6, 0.62, 1], metallicFactor: 0.0, roughnessFactor: 0.35 }, + extensions: { KHR_materials_specular: { specularFactor: 0.5, specularColorFactor: [1, 0.5, 0.25] } }, + }, + { name: 'Variant_Crimson', pbrMetallicRoughness: { baseColorFactor: [0.8, 0.05, 0.08, 1], metallicFactor: 0.0, roughnessFactor: 0.4 } }, + { name: 'Variant_Ocean', pbrMetallicRoughness: { baseColorFactor: [0.05, 0.25, 0.8, 1], metallicFactor: 0.6, roughnessFactor: 0.25 } }, + { + name: 'Variant_Velvet', + pbrMetallicRoughness: { baseColorFactor: [0.12, 0.03, 0.2, 1], metallicFactor: 0.0, roughnessFactor: 0.9 }, + extensions: { KHR_materials_sheen: { sheenColorFactor: [0.9, 0.6, 1.0], sheenRoughnessFactor: 0.45 } }, + }, + { name: 'Ribbon_Yellow', doubleSided: true, pbrMetallicRoughness: { baseColorFactor: [0.95, 0.8, 0.1, 1], metallicFactor: 0.0, roughnessFactor: 0.6 } }, + ], + accessors: [ + { bufferView: vPos, componentType: 5122, normalized: true, count: n, type: 'VEC3', min: [-32767, -32767, -32767], max: [32767, 32767, 32767] }, + { bufferView: vNor, componentType: 5120, normalized: true, count: n, type: 'VEC3' }, + { bufferView: vUv, componentType: 5123, normalized: true, count: n, type: 'VEC2' }, + { bufferView: vIdx, componentType: 5123, count: indices.length, type: 'SCALAR' }, + { bufferView: vRp, componentType: 5126, count: tris * 3, type: 'VEC3', min: [-6, -3.2, 0], max: [6, -2.9, 0] }, + { bufferView: vRn, componentType: 5126, count: tris * 3, type: 'VEC3' }, + ], + bufferViews: views, + buffers: [{ byteLength: 0 }], + }; + const bin = w.finish(); + json.buffers[0].byteLength = bin.byteLength; + return { blob: buildGLB(json, bin), sphereVertices: n, ribbonTriangles: tris, variantNames }; +} diff --git a/samples/water/Sample_Lake.ts b/samples/water/Sample_Lake.ts new file mode 100644 index 000000000..398a3847e --- /dev/null +++ b/samples/water/Sample_Lake.ts @@ -0,0 +1,142 @@ +import { + AtmosphericComponent, BitmapTexture2D, CameraUtil, Color, Context3D, DirectLight, Engine3D, HoverCameraController, + KelvinUtil, LitMaterial, Object3D, Scene3D, Vector2, Vector3, View3D, WaterRenderer, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { addPointerRipples, addWaterGUI, floatingBall, heightfieldGeometry, mesh, radialGeometry } from "./WaterSampleUtil"; + +const LAKE_RADIUS = 22; +const LAKE_DEPTH = 4; +const TERRAIN_SIZE = 160; + +/** Distance from the center to the shoreline in the direction `angle`. */ +function shore(angle: number): number { + return LAKE_RADIUS * (1 + 0.22 * Math.sin(2 * angle + 0.6) + 0.12 * Math.sin(3 * angle + 1.9) + 0.07 * Math.sin(5 * angle + 0.3)); +} + +/** Ground height: a bowl down to LAKE_DEPTH inside the shoreline, rising into rolling grass outside. */ +function groundHeight(x: number, z: number): number { + const r = Math.hypot(x, z); + const edge = shore(Math.atan2(z, x)); + const s = r / edge; + if (s < 1) { + // Bed with a few bumps, zero at the shoreline. + const bed = 1 - s * s; + return -LAKE_DEPTH * bed + 0.3 * Math.sin(x * 0.35) * Math.cos(z * 0.29) * bed; + } + const out = r - edge; + const hills = 3 * (Math.sin(x * 0.045 + 1) * Math.cos(z * 0.06) + 1) * smoothstep(6, 30, out); + return Math.min(out * 0.2, 1.5) + hills; +} + +function smoothstep(a: number, b: number, x: number): number { + const t = Math.min(1, Math.max(0, (x - a) / (b - a))); + return t * t * (3 - 2 * t); +} + +/** + * Lake: water with an irregular outline (WaterRenderer.surfaceGeometry) in a + * bowl of terrain. The surface mesh follows the shoreline and reaches a metre + * past it, under the ground; the underwater view, caustics and ripples all + * follow the same outline. + * + * Click the water for a splash or the buoy to push it under, hold Shift and + * move the mouse to drag a trail; the buoy can drift or be dropped (Buoy + * folder). + */ +export class Sample_Lake { + async run() { + const engine = await Engine3D.init({ setting: { render: { water: true } } }); + + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent); + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(60, engine.aspect, 0.1, 2000); + camera.object3D.addComponent(HoverCameraController).setCamera(37.7, -30.3, 19.2, new Vector3(7.48, -0.5, 4.13)); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const light = new Object3D(); + light.rotationX = 45; + light.rotationY = 40; + const dl = light.addComponent(DirectLight); + dl.lightColor = KelvinUtil.color_temperature_to_rgb(5800); + dl.intensity = 3; + dl.castShadow = true; + scene.addChild(light); + + const ground = new LitMaterial(); + ground.baseMap = paintGround(engine.context3D); + ground.roughness = 0.9; + ground.metallic = 0; + scene.addChild(mesh(heightfieldGeometry(TERRAIN_SIZE, 256, groundHeight), ground, 0, 0, 0)); + + const waterObj = new Object3D(); + const water = waterObj.addComponent(WaterRenderer); + // The shoreline plus a metre, hidden under the rising ground. + water.surfaceGeometry = radialGeometry((a) => shore(a) + 1, 56, 320); + water.waves = [ + { direction: new Vector2(1, 0.4), wavelength: 7, steepness: 0.06 }, + { direction: new Vector2(0.6, 1), wavelength: 4.3, steepness: 0.05 }, + { direction: new Vector2(-0.5, 0.8), wavelength: 2.6, steepness: 0.04 }, + { direction: new Vector2(0.9, -0.6), wavelength: 1.8, steepness: 0.03 }, + ]; + // Green, murkier than a pool. + const m = water.waterMaterial; + m.absorptionColor = new Color(0.25, 0.55, 0.42); + m.underwaterColor = new Color(0.05, 0.13, 0.1); + m.density = 0.45; + water.detailScale = 2.2; + water.detailStrength = 0.5; + water.rippleResolution = 384; + scene.addChild(waterObj); + + const buoy = floatingBall(scene, water, 0.4, 4, 3, new Color(0.95, 0.75, 0.15)); + addPointerRipples(engine, camera, water, [buoy]); + + GUIHelp.init(); + addWaterGUI(water); + GUIHelp.addFolder('Buoy'); + GUIHelp.add(buoy, 'drift'); + GUIHelp.addButton('drop', () => buoy.drop(4)); + GUIHelp.endFolder(); + } +} + +/** Ground colors by height: mud and sand under the water, a sandy beach, then grass. */ +function paintGround(ctx: Context3D): BitmapTexture2D { + const size = 1024; + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size; + const g = canvas.getContext('2d')!; + const img = g.createImageData(size, size); + const mix = (a: number[], b: number[], t: number) => a.map((v, i) => v + (b[i] - v) * t); + const mud = [70, 64, 48], sand = [196, 182, 140], grass = [62, 120, 34], dryGrass = [104, 136, 48]; + for (let j = 0; j < size; j++) { + for (let i = 0; i < size; i++) { + const x = (i / size - 0.5) * TERRAIN_SIZE; + const z = (j / size - 0.5) * TERRAIN_SIZE; + const y = groundHeight(x, z); + const noise = 0.92 + 0.16 * Math.random(); + let c: number[]; + if (y < 0.4) { + c = mix(sand, mud, smoothstep(0.2, 3, -y)); + } else { + c = mix(sand, mix(grass, dryGrass, smoothstep(2, 6, y)), smoothstep(0.4, 1.2, y)); + } + const k = (j * size + i) * 4; + img.data[k] = c[0] * noise; + img.data[k + 1] = c[1] * noise; + img.data[k + 2] = c[2] * noise; + img.data[k + 3] = 255; + } + } + g.putImageData(img, 0, 0); + const tex = new BitmapTexture2D(true, ctx, 'srgb'); + tex.source = canvas; + return tex; +} diff --git a/samples/water/Sample_Ocean.ts b/samples/water/Sample_Ocean.ts new file mode 100644 index 000000000..2f46bd5ee --- /dev/null +++ b/samples/water/Sample_Ocean.ts @@ -0,0 +1,96 @@ +import { + AtmosphericComponent, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil, Object3D, Scene3D, + Vector2, Vector3, View3D, WaterRenderer, WaterSpectrum, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { addPointerRipples, addWaterGUI, floatingBall, radialGeometry } from "./WaterSampleUtil"; + +/** Radius of the ocean disc around the buoy. */ +const OCEAN_RADIUS = 3000; + +/** + * Open ocean: long swells over deep water with no bottom in sight. The + * surface is a disc of rings around the buoy the camera orbits, centimetres + * apart near it and growing with distance. Each wave fades out where the + * rings get too coarse for it (WaterRenderer.waveFadeDistance), so the + * distance does not alias. + * + * Ripples are simulated in a 60 m square around the buoy + * (WaterRenderer.rippleArea): click the water to splash, or the buoy to + * push it under. + * + * The waves come from a wind spectrum simulated with FFTs + * (WaterRenderer.spectrum); the Sea folder sets the wind, fetch, wave + * height and how sharp the crests are. Whitecaps leave foam that trails + * behind them. + */ +export class Sample_Ocean { + async run() { + const engine = await Engine3D.init({ setting: { render: { water: true } } }); + + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent); + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(60, engine.aspect, 0.1, 5000); + // Low over the water, looking across toward the sun. + camera.object3D.addComponent(HoverCameraController).setCamera(150, -8, 28, new Vector3(0, 0, 0)); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const light = new Object3D(); + light.rotationX = 30; + light.rotationY = 150; + const dl = light.addComponent(DirectLight); + dl.lightColor = KelvinUtil.color_temperature_to_rgb(5500); + dl.intensity = 3; + scene.addChild(light); + + const waterObj = new Object3D(); + const water = waterObj.addComponent(WaterRenderer); + // 400 rings, 5 cm apart at the center; farther out the spacing is about 1.75% of + // the distance, so a wave gets four vertices per wavelength out to 14 wavelengths. + const growth = 0.0175 * 400; + water.surfaceGeometry = radialGeometry(() => OCEAN_RADIUS, 400, 512, + (t) => (Math.exp(growth * t) - 1) / (Math.exp(growth) - 1)); + // Fade each wave out before the rings get too coarse for it. + water.waveFadeDistance = 14; + // A rough sea from a 12 m/s wind over 100 km of open water, simulated with FFTs. + const spectrum = new WaterSpectrum(); + spectrum.windSpeed = 12; + spectrum.windDirection = new Vector2(1, 0.3); + spectrum.fetch = 100000; + water.spectrum = spectrum; + water.waves = []; + // Clear, deep blue water; nothing below to catch caustics. + const m = water.waterMaterial; + m.absorptionColor = new Color(0.1, 0.4, 0.6); + m.underwaterColor = new Color(0.0, 0.07, 0.14); + m.density = 0.08; + // Wind-roughened: the sky reflection is soft. + m.reflectionRoughness = 0.08; + water.caustics = false; + // Wind chop a few metres long, gentle at this scale. + water.detailScale = 2.5; + water.detailStrength = 0.4; + // A grid over the whole ocean would be metres per cell; ripples need a smaller area. + water.rippleArea = 60; + scene.addChild(waterObj); + + const buoy = floatingBall(scene, water, 1.2, 0, 0, new Color(0.9, 0.2, 0.15)); + addPointerRipples(engine, camera, water, [buoy]); + + GUIHelp.init(); + GUIHelp.addFolder('Sea'); + GUIHelp.add(spectrum, 'windSpeed', 1, 25, 0.1); + GUIHelp.add(spectrum, 'fetch', 1000, 500000, 1000); + GUIHelp.add(spectrum, 'amplitude', 0, 3, 0.01); + GUIHelp.add(spectrum, 'choppiness', 0, 2, 0.01); + GUIHelp.open(); + GUIHelp.endFolder(); + addWaterGUI(water, { waves: false, caustics: false, foam: true }); + } +} diff --git a/samples/water/Sample_Pool.ts b/samples/water/Sample_Pool.ts new file mode 100644 index 000000000..6b73d8fc7 --- /dev/null +++ b/samples/water/Sample_Pool.ts @@ -0,0 +1,140 @@ +import { + AtmosphericComponent, BitmapTexture2D, BoxGeometry, CameraUtil, Color, Context3D, DirectLight, Engine3D, + HoverCameraController, KelvinUtil, LitMaterial, Object3D, PlaneGeometry, Scene3D, Vector2, Vector3, View3D, + WaterRenderer, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; +import { addPointerRipples, addWaterGUI, floatingModel, mesh, solid } from "./WaterSampleUtil"; + +const POOL_WIDTH = 20; +const POOL_LENGTH = 14; +const POOL_DEPTH = 2; + +/** + * Swimming pool: nearly still water over a tiled floor, with refraction, + * absorption, sky reflection and caustics. A rubber duck floats on the + * surface using WaterRenderer.getHeight. + * + * Ripples all go through WaterRenderer.addRipple: click the water for a + * splash or the duck to push it under, hold Shift and move the mouse to + * drag a trail. + */ +export class Sample_Pool { + async run() { + const engine = await Engine3D.init({ setting: { render: { water: true } } }); + + const scene = new Scene3D(); + scene.addComponent(AtmosphericComponent); + + const camera = CameraUtil.createCamera3DObject(scene); + camera.perspective(60, engine.aspect, 0.1, 1000); + camera.object3D.addComponent(HoverCameraController).setCamera(144.6, -26.6, 10.9, new Vector3(0, -1, 0)); + + const view = new View3D(); + view.scene = scene; + view.camera = camera; + engine.startRenderView(view); + + const light = new Object3D(); + light.rotationX = 50; + light.rotationY = 30; + const dl = light.addComponent(DirectLight); + dl.lightColor = KelvinUtil.color_temperature_to_rgb(5500); + dl.intensity = 3; + dl.castShadow = true; + dl.enableCSM = true; + scene.addChild(light); + + createPool(scene, engine.context3D); + + const waterObj = new Object3D(); + const water = waterObj.addComponent(WaterRenderer); + // Slightly larger than the pool: the waves also move the surface sideways, and the + // walls hide the overlap instead of a gap opening along them. + water.width = POOL_WIDTH + 0.6; + water.length = POOL_LENGTH + 0.6; + // Still water: short, low waves, about 1.5 cm high at most. + water.waves = [ + { direction: new Vector2(1, 0.3), wavelength: 4, steepness: 0.025 }, + { direction: new Vector2(0.4, 1), wavelength: 2.6, steepness: 0.02 }, + { direction: new Vector2(-0.7, 0.6), wavelength: 1.7, steepness: 0.015 }, + { direction: new Vector2(0.2, -1), wavelength: 1.1, steepness: 0.012 }, + ]; + water.resolution = 200; + water.waterMaterial.waterDepth = POOL_DEPTH; + // Faint ripples on the surface; the view of the floor stays clear. + water.detailStrength = 0.2; + // From underwater, most of the surface shows the world above. + water.waterMaterial.underwaterClarity = 0.8; + scene.addChild(waterObj); + + const duck = floatingModel(scene, water, await engine.res.loadGltf('PBR/Duck/Duck.gltf'), 1.2, -3, 2); + addPointerRipples(engine, camera, water, [duck]); + + GUIHelp.init(); + addWaterGUI(water); + } +} + +/** Tiled pool around (0, -POOL_DEPTH .. 0, 0) with a white coping and a plain ground. */ +function createPool(scene: Scene3D, ctx: Context3D) { + const t = 0.6; + const wallTop = 0.4; + // Ground around the pool opening (four strips, leaving the pool open). + const groundMat = solid(new Color(0.55, 0.53, 0.5), 0.9); + const G = 80, hw = POOL_WIDTH / 2 + 1.5 * t, hl = POOL_LENGTH / 2 + 1.5 * t; + const side = (G / 2 - hl); + scene.addChild(mesh(new PlaneGeometry(G, side), groundMat, 0, wallTop, -(hl + side / 2))); + scene.addChild(mesh(new PlaneGeometry(G, side), groundMat, 0, wallTop, hl + side / 2)); + scene.addChild(mesh(new PlaneGeometry(G / 2 - hw, 2 * hl), groundMat, -(hw + (G / 2 - hw) / 2), wallTop, 0)); + scene.addChild(mesh(new PlaneGeometry(G / 2 - hw, 2 * hl), groundMat, hw + (G / 2 - hw) / 2, wallTop, 0)); + const tiles = new LitMaterial(); + tiles.baseMap = paintTiles(ctx); + tiles.roughness = 0.7; + tiles.metallic = 0; + scene.addChild(mesh(new BoxGeometry(POOL_WIDTH, t, POOL_LENGTH), tiles, 0, -POOL_DEPTH - t / 2, 0)); + const wall = solid(new Color(0.55, 0.82, 0.88), 0.4); + const h = POOL_DEPTH + wallTop; + const cy = -POOL_DEPTH + h / 2; + scene.addChild(mesh(new BoxGeometry(POOL_WIDTH + 2 * t, h, t), wall, 0, cy, -POOL_LENGTH / 2 - t / 2)); + scene.addChild(mesh(new BoxGeometry(POOL_WIDTH + 2 * t, h, t), wall, 0, cy, POOL_LENGTH / 2 + t / 2)); + scene.addChild(mesh(new BoxGeometry(t, h, POOL_LENGTH), wall, -POOL_WIDTH / 2 - t / 2, cy, 0)); + scene.addChild(mesh(new BoxGeometry(t, h, POOL_LENGTH), wall, POOL_WIDTH / 2 + t / 2, cy, 0)); + const coping = solid(new Color(0.95, 0.95, 0.92), 0.6); + for (const [w, l, x, z] of [ + [POOL_WIDTH + 4 * t, t, 0, -POOL_LENGTH / 2 - t], [POOL_WIDTH + 4 * t, t, 0, POOL_LENGTH / 2 + t], + [t, POOL_LENGTH, -POOL_WIDTH / 2 - t, 0], [t, POOL_LENGTH, POOL_WIDTH / 2 + t, 0], + ]) { + scene.addChild(mesh(new BoxGeometry(w, 0.15, l), coping, x, wallTop + 0.075, z)); + } +} + + +/** Light aqua mosaic with grout and dark lane lines along x. */ +function paintTiles(ctx: Context3D): BitmapTexture2D { + const tile = 0.5; + const tx = Math.round(POOL_WIDTH / tile), tz = Math.round(POOL_LENGTH / tile); + const px = Math.floor(2048 / Math.max(tx, tz)); + const canvas = document.createElement('canvas'); + canvas.width = tx * px; + canvas.height = tz * px; + const g = canvas.getContext('2d')!; + g.fillStyle = 'rgb(225, 242, 246)'; + g.fillRect(0, 0, canvas.width, canvas.height); + const grout = Math.max(1, Math.round(px * 0.08)); + for (let i = 0; i < tx; i++) { + for (let j = 0; j < tz; j++) { + const k = 0.94 + Math.random() * 0.1; + g.fillStyle = `rgb(${Math.round(110 * k)}, ${Math.round(200 * k)}, ${Math.round(218 * k)})`; + g.fillRect(i * px + grout, j * px + grout, px - 2 * grout, px - 2 * grout); + } + } + g.fillStyle = 'rgb(18, 42, 105)'; + for (let l = 1; l <= 3; l++) { + const zc = Math.round((l * tz) / 4) * px; + g.fillRect(2 * px, zc - px / 2, canvas.width - 4 * px, px); + } + const tex = new BitmapTexture2D(true, ctx, 'srgb'); + tex.source = canvas; + return tex; +} diff --git a/samples/water/WaterSampleUtil.ts b/samples/water/WaterSampleUtil.ts new file mode 100644 index 000000000..d90b698e7 --- /dev/null +++ b/samples/water/WaterSampleUtil.ts @@ -0,0 +1,335 @@ +import { + BoundUtil, Camera3D, Color, ComponentBase, Engine3D, GeometryBase, LitMaterial, MeshRenderer, Object3D, PointerEvent3D, + Scene3D, SphereGeometry, Time, Vector3, VertexAttributeName, WaterRenderer, +} from "@orillusion/core"; +import { GUIHelp } from "@orillusion/debug/GUIHelp"; + +/** + * Floats its object on the water. It can drift in a circle, be dropped in or + * pushed under, and starts ripples where it disturbs the surface: a splash on + * entry or when pushed, another as it bobs back up, a wake while it moves. + */ +export class Floater extends ComponentBase { + /** Drift in a circle starting from the initial point. */ + public drift = false; + /** Yaw in degrees that turns the object's front toward +x; it faces where it drifts. */ + public heading = 0; + + private water!: WaterRenderer; + private x = 0; + private z = 0; + private cx = 0; + private cz = 0; + /** Height of the object's origin above the surface. */ + private lift = 0; + private size = 1; + private angle = 0; + /** Height while falling; NaN when floating. */ + private fallY = NaN; + private vy = 0; + private wakeX = 0; + private wakeZ = 0; + /** Bobbing about the resting height after a push: offset and its speed. */ + private bob = 0; + private bobV = 0; + + /** @param size radius of the disturbance, for splash and wake */ + public init(param?: { water: WaterRenderer; x: number; z: number; lift: number; size: number }): void { + if (!param) return; + this.water = param.water; + this.x = this.cx = this.wakeX = param.x; + this.z = this.cz = this.wakeZ = param.z; + this.lift = param.lift; + this.size = param.size; + } + + /** Radius of the disturbance, also what pointer clicks hit. */ + public get radius(): number { + return this.size; + } + + /** Pushes the object under; the water lifts it back, bobbing. */ + public push(): void { + this.bobV = -4; + this.water.addRipple(this.x, this.z, 0.5, this.size * 1.2); + } + + /** Lifts the object this far above the water and lets it fall. */ + public drop(height: number): void { + this.fallY = this.water.getHeight(this.x, this.z) + height; + this.vy = 0; + } + + public onUpdate(): void { + if (!this.water) return; + const dt = Math.min(Time.delta * 0.001, 1 / 30); + if (this.drift) { + // Two metres around (cx - 2, cz) at 0.8 m/s. + this.angle += dt * 0.8 / 2; + this.x = this.cx + 2 * Math.cos(this.angle) - 2; + this.z = this.cz + 2 * Math.sin(this.angle); + // Moving along (-sin, cos) of the angle. + this.transform.rotationY = this.heading - Math.atan2(Math.cos(this.angle), -Math.sin(this.angle)) * 180 / Math.PI; + } + // Buoyancy as a spring toward the resting height, about one bob a second, damped. + if (this.bob !== 0 || this.bobV !== 0) { + const before = this.bob; + this.bobV += (-40 * this.bob - 4 * this.bobV) * dt; + this.bob += this.bobV * dt; + // Breaking back through the surface on the way up throws a smaller ring. + if (before < -this.size * 0.3 && this.bob >= -this.size * 0.3 && this.bobV > 1) { + this.water.addRipple(this.x, this.z, 0.2, this.size); + } + if (Math.abs(this.bob) < 1e-3 && Math.abs(this.bobV) < 1e-2) this.bob = this.bobV = 0; + } + const rest = this.water.getHeight(this.x, this.z) + this.lift + this.bob; + let y = rest; + if (!Number.isNaN(this.fallY)) { + this.vy -= 9.81 * dt; + this.fallY += this.vy * dt; + if (this.fallY > rest) { + y = this.fallY; + } else { + // Splash: deeper the faster it hits. + this.water.addRipple(this.x, this.z, Math.min(0.4, -this.vy * 0.05), this.size); + this.fallY = NaN; + } + } + this.transform.x = this.x; + this.transform.y = y; + this.transform.z = this.z; + // Wake: a small ripple every 0.2 m of travel. + if (Math.hypot(this.x - this.wakeX, this.z - this.wakeZ) > 0.2) { + this.water.addRipple(this.x, this.z, 0.03, this.size * 0.7); + this.wakeX = this.x; + this.wakeZ = this.z; + } + } +} + +/** + * Pointer interaction: a click on a floater pushes it under; elsewhere on + * the water, where the view ray meets the undisturbed surface, it splashes. + * Holding Shift drags a trail of ripples. + */ +export function addPointerRipples(engine: Engine3D, camera: Camera3D, water: WaterRenderer, floaters: Floater[] = [], splash = 0.4, radius = 0.4): void { + let lastTrail: Vector3 | null = null; + const hitWater = (e: PointerEvent3D): Vector3 | null => { + const ray = camera.screenPointToRay(e.mouseX, e.mouseY); + if (ray.direction.y >= 0) return null; + const t = (water.baseHeight - ray.origin.y) / ray.direction.y; + return new Vector3(ray.origin.x + ray.direction.x * t, water.baseHeight, ray.origin.z + ray.direction.z * t); + }; + // The nearest floater the view ray passes through, if any. + const hitFloater = (e: PointerEvent3D): Floater | null => { + const ray = camera.screenPointToRay(e.mouseX, e.mouseY); + let best: Floater | null = null, bestT = Infinity; + for (const f of floaters) { + const c = f.transform.worldPosition; + const ox = ray.origin.x - c.x, oy = ray.origin.y - c.y, oz = ray.origin.z - c.z; + const b = ox * ray.direction.x + oy * ray.direction.y + oz * ray.direction.z; + const disc = b * b - (ox * ox + oy * oy + oz * oz - f.radius * f.radius); + const t = -b - Math.sqrt(Math.max(disc, 0)); + if (disc >= 0 && t > 0 && t < bestT) { + best = f; + bestT = t; + } + } + return best; + }; + engine.inputSystem.addEventListener(PointerEvent3D.POINTER_DOWN, (e: PointerEvent3D) => { + const floater = hitFloater(e); + if (floater) { + floater.push(); + return; + } + const p = hitWater(e); + if (p) water.addRipple(p.x, p.z, splash, radius); + }, null); + engine.inputSystem.addEventListener(PointerEvent3D.POINTER_MOVE, (e: PointerEvent3D) => { + if (!e.shiftKey) { + lastTrail = null; + return; + } + const p = hitWater(e); + if (!p) return; + if (!lastTrail || Vector3.distance(p, lastTrail) > 0.15) { + water.addRipple(p.x, p.z, splash * 0.3, radius * 0.6); + lastTrail = p; + } + }, null); +} + +/** + * A short Water folder: pause and speed, the two water colors (the tint of + * what is seen through it, and its own scattered color), density, overall + * wave height (scales every Gerstner wave), and per sample the caustics + * switch or the whitecap foam. Everything else keeps its default. + */ +export function addWaterGUI(water: WaterRenderer, options: { waves?: boolean; caustics?: boolean; foam?: boolean } = {}): void { + const m = water.waterMaterial; + const steepness = water.waves.map((w) => w.steepness); + const controls = { + paused: false, + speed: water.timeScale, + waveHeight: 1, + }; + const applyTime = () => { water.timeScale = controls.paused ? 0 : controls.speed; }; + GUIHelp.addFolder('Water'); + GUIHelp.add(controls, 'paused').onChange(applyTime); + GUIHelp.add(controls, 'speed', 0, 3, 0.01).onChange(applyTime); + // On the material itself: the color picker writes the edited color back through its setter. + GUIHelp.addColor(m, 'absorptionColor'); + GUIHelp.addColor(m, 'underwaterColor'); + GUIHelp.add(m, 'density', 0, 2, 0.01); + if (options.waves !== false) { + GUIHelp.add(controls, 'waveHeight', 0, 3, 0.01).onChange((v: number) => { + water.waves.forEach((w, i) => { w.steepness = steepness[i] * v; }); + }); + } + if (options.caustics !== false) GUIHelp.add(water, 'caustics'); + if (options.foam) GUIHelp.add(m, 'foamIntensity', 0, 1, 0.01); + GUIHelp.open(); + GUIHelp.endFolder(); +} + +/** + * Flat mesh in the xz plane bounded by a closed curve around the origin: + * rings from the center out to `outline(angle)`, radii spaced by `ringRadius(t)` + * for t from 0 to 1 (default: evenly). + */ +export function radialGeometry( + outline: (angle: number) => number, rings: number, segments: number, + ringRadius: (t: number) => number = (t) => t, +): GeometryBase { + const count = 1 + rings * segments; + const pos = new Float32Array(count * 3); + const nor = new Float32Array(count * 3); + const uv = new Float32Array(count * 2); + nor[1] = 1; + uv[0] = uv[1] = 0.5; + for (let s = 0; s < segments; s++) { + const a = (s / segments) * Math.PI * 2; + const edge = outline(a); + for (let r = 1; r <= rings; r++) { + const i = 1 + (r - 1) * segments + s; + const rr = edge * ringRadius(r / rings); + pos[i * 3] = Math.cos(a) * rr; + pos[i * 3 + 2] = Math.sin(a) * rr; + nor[i * 3 + 1] = 1; + uv[i * 2] = 0.5 + 0.5 * Math.cos(a) * r / rings; + uv[i * 2 + 1] = 0.5 + 0.5 * Math.sin(a) * r / rings; + } + } + const idx: number[] = []; + for (let s = 0; s < segments; s++) idx.push(0, 1 + ((s + 1) % segments), 1 + s); + for (let r = 1; r < rings; r++) { + for (let s = 0; s < segments; s++) { + const a = 1 + (r - 1) * segments + s; + const b = 1 + (r - 1) * segments + ((s + 1) % segments); + idx.push(a, b, a + segments, b, b + segments, a + segments); + } + } + return indexedGeometry(pos, nor, uv, idx); +} + +/** Square grid of `size` world units centered on the origin, raised by `height(x, z)`. */ +export function heightfieldGeometry(size: number, segments: number, height: (x: number, z: number) => number): GeometryBase { + const n = segments + 1; + const pos = new Float32Array(n * n * 3); + const nor = new Float32Array(n * n * 3); + const uv = new Float32Array(n * n * 2); + const step = size / segments; + for (let j = 0; j < n; j++) { + for (let i = 0; i < n; i++) { + const k = j * n + i; + const x = -size / 2 + i * step, z = -size / 2 + j * step; + pos[k * 3] = x; + pos[k * 3 + 1] = height(x, z); + pos[k * 3 + 2] = z; + // Normal from the slope. + const e = step * 0.5; + const dx = (height(x + e, z) - height(x - e, z)) / (2 * e); + const dz = (height(x, z + e) - height(x, z - e)) / (2 * e); + const len = Math.hypot(dx, 1, dz); + nor[k * 3] = -dx / len; + nor[k * 3 + 1] = 1 / len; + nor[k * 3 + 2] = -dz / len; + uv[k * 2] = i / segments; + uv[k * 2 + 1] = j / segments; + } + } + const idx: number[] = []; + for (let j = 0; j < segments; j++) { + for (let i = 0; i < segments; i++) { + const a = j * n + i, b = a + 1, c = a + n, d = c + 1; + idx.push(a, c, b, b, c, d); + } + } + return indexedGeometry(pos, nor, uv, idx); +} + +function indexedGeometry(pos: Float32Array, nor: Float32Array, uv: Float32Array, idx: number[]): GeometryBase { + const g = new GeometryBase(); + g.setIndices(pos.length / 3 > 65535 ? new Uint32Array(idx) : new Uint16Array(idx)); + g.setAttribute(VertexAttributeName.position, pos); + g.setAttribute(VertexAttributeName.normal, nor); + g.setAttribute(VertexAttributeName.uv, uv); + g.setAttribute(VertexAttributeName.TEXCOORD_1, uv); + g.addSubGeometry({ indexStart: 0, indexCount: idx.length, vertexStart: 0, vertexCount: 0, firstStart: 0, index: 0, topology: 0 }); + return g; +} + +export function solid(color: Color, roughness: number): LitMaterial { + const m = new LitMaterial(); + m.baseColor = color; + m.roughness = roughness; + m.metallic = 0; + return m; +} + +export function mesh(geometry: GeometryBase, material: LitMaterial, x: number, y: number, z: number): Object3D { + const obj = new Object3D(); + obj.x = x; + obj.y = y; + obj.z = z; + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + mr.material = material; + mr.receiveShadow = true; + return obj; +} + +/** + * A model floating on the water: scaled to `length` across, centered on a + * holder so clicks and splashes are about its middle, with `draft` of its + * height under water. + */ +export function floatingModel(scene: Scene3D, water: WaterRenderer, model: Object3D, length: number, x: number, z: number, draft = 0.18): Floater { + const holder = new Object3D(); + holder.addChild(model); + scene.addChild(holder); + const raw = BoundUtil.genMeshBounds(model); + const s = length / Math.max(raw.max.x - raw.min.x, raw.max.z - raw.min.z); + model.scaleX *= s; + model.scaleY *= s; + model.scaleZ *= s; + const b = BoundUtil.genMeshBounds(model); + model.x = -(b.min.x + b.max.x) / 2; + model.y = -(b.min.y + b.max.y) / 2; + model.z = -(b.min.z + b.max.z) / 2; + const height = b.max.y - b.min.y; + const radius = Math.max(b.max.x - b.min.x, height, b.max.z - b.min.z) / 2; + return holder.addComponent(Floater, { water, x, z, lift: height * (0.5 - draft), size: radius }); +} + +/** A ball floating on the water, a little under half submerged. */ +export function floatingBall(scene: Scene3D, water: WaterRenderer, radius: number, x: number, z: number, color: Color): Floater { + const ball = new Object3D(); + const mr = ball.addComponent(MeshRenderer); + mr.geometry = new SphereGeometry(radius, 32, 32); + mr.material = solid(color, 0.4); + const floater = ball.addComponent(Floater, { water, x, z, lift: radius * 0.6, size: radius }); + scene.addChild(ball); + return floater; +} diff --git a/src/Engine3D.ts b/src/Engine3D.ts index ff54ccfca..42e1698bb 100644 --- a/src/Engine3D.ts +++ b/src/Engine3D.ts @@ -118,6 +118,8 @@ export class Engine3D { msaa: 0, useOIT: false, decals: false, + water: false, + fluid: false, useStencil: false, gpuCull: false, tonemap: { @@ -129,6 +131,7 @@ export class Engine3D { // encode. exposure: 1.0, mode: 'ACES', + whitePoint: 4.0, }, postProcessing: { bloom: { @@ -171,6 +174,8 @@ export class Engine3D { gtao: { enable: false, darkFactor: 1.0, maxDistance: 5.0, maxPixel: 50.0, rayMarchSegment: 6, multiBounce: false, usePosFloat32: true, blendColor: true, debug: true }, ssr: { enable: false, pixelRatio: 1, fadeEdgeRatio: 0.2, rayMarchRatio: 0.5, fadeDistanceMin: 600, fadeDistanceMax: 2000, roughnessThreshold: 0.5, powDotRN: 0.2, mixThreshold: 0.1, debug: true }, fxaa: { enable: false }, + lens: { enable: false, vignetteIntensity: 0.4, vignetteSmoothness: 0.4, vignetteRoundness: 1.0, vignetteColor: new Color(0, 0, 0, 1), chromaticAberration: 0.0, grainIntensity: 0.0, grainStatic: false }, + motionBlur: { enable: false, intensity: 0.5, samples: 12, maxBlurPixels: 64, frameRateIndependent: true }, skyline: { enable: false, lineColor: new Color(1, 0, 0, 1), @@ -278,6 +283,14 @@ export class Engine3D { private static _rafId: number = 0; private static _time: number = 0; + /** True until the next `_tick` after the loop (re)starts. `Time.time` is + * 0 before the first frame and frozen while every instance is paused, so + * `time - Time.time` on that tick would be the whole page-load / pause + * duration (seconds). Physics, animation and controllers integrate that + * as one giant step — e.g. a character controller tunnels through the + * floor on frame 1. Substitute a nominal 60 Hz delta instead. */ + private static _resetDelta: boolean = true; + private static readonly NOMINAL_DELTA_MS = 1000 / 60; // -------- instance fields -------- public readonly context3D: Context3D; @@ -533,6 +546,7 @@ export class Engine3D { /** Resume every engine instance and restart the shared render loop. */ public static resume() { for (const inst of Engine3D._instances) inst._paused = false; + Engine3D._resetDelta = true; Engine3D._ensureLoop(); } @@ -545,6 +559,7 @@ export class Engine3D { * if it stopped while every instance was paused. */ public resume() { this._paused = false; + if (Engine3D._rafId === 0) Engine3D._resetDelta = true; Engine3D._ensureLoop(); } @@ -578,7 +593,8 @@ export class Engine3D { } // Advance global time once per composite frame. - Time.delta = time - Time.time; + Time.delta = this._resetDelta ? Engine3D.NOMINAL_DELTA_MS : time - Time.time; + this._resetDelta = false; Time.time = time; Time.frame += 1; Interpolator.tick(Time.delta); diff --git a/src/assets/shader/ShaderLib.ts b/src/assets/shader/ShaderLib.ts index ecc9fef86..61b5cfe8e 100644 --- a/src/assets/shader/ShaderLib.ts +++ b/src/assets/shader/ShaderLib.ts @@ -34,6 +34,8 @@ import { Irradiance_frag } from './lighting/Irradiance_frag'; import { BRDF_frag } from './lighting/BRDF_frag'; import { BxDF_frag } from './lighting/BxDF_frag'; import { Clearcoat_frag } from './materials/program/Clearcoat_frag'; +import { Sheen_frag } from './materials/program/Sheen_frag'; +import { Iridescence_frag } from './materials/program/Iridescence_frag'; import { Lit_shader } from './materials/Lit_shader'; import { PBRLItShader } from './materials/PBRLItShader'; import { BxdfDebug_frag } from './materials/program/BxdfDebug_frag'; @@ -128,6 +130,8 @@ export class ShaderLib { ShaderLib.register('ReflectionCG', ReflectionCG); ShaderLib.register('ReflectionShader_shader', ReflectionShader_shader); ShaderLib.register('Clearcoat_frag', Clearcoat_frag); + ShaderLib.register('Sheen_frag', Sheen_frag); + ShaderLib.register('Iridescence_frag', Iridescence_frag); ShaderLib.register('LitShader', Lit_shader); ShaderLib.register('PBRLItShader', PBRLItShader); diff --git a/src/assets/shader/compute/MotionBlur_cs.ts b/src/assets/shader/compute/MotionBlur_cs.ts new file mode 100644 index 000000000..f6ee12547 --- /dev/null +++ b/src/assets/shader/compute/MotionBlur_cs.ts @@ -0,0 +1,79 @@ +/** + * Camera motion blur. Reconstructs each pixel's world position from the + * G-buffer depth, reprojects it with the previous frame's view-projection to + * get a screen-space velocity, and averages the scene color along it. + * + * Camera-driven motion only (the G-buffer carries no per-object velocity); + * sky pixels are left untouched. + * @internal + */ +export let MotionBlur_cs: string = /*wgsl*/` + #include "GlobalUniform" + #include "GBufferStand" + + // Required by the included G-buffer helpers. + const PI: f32 = 3.1415926; + + struct MotionBlurData { + prevViewProj: mat4x4, + // x = velocity scale, y = sample count, z = max blur (pixels), w = unused + params: vec4, + }; + + @group(0) @binding(2) var motionBlurData: MotionBlurData; + @group(0) @binding(3) var inTex: texture_2d; + @group(0) @binding(4) var outTex: texture_storage_2d; + + @compute @workgroup_size(8, 8, 1) + fn CsMain(@builtin(global_invocation_id) gid: vec3) { + let fragCoord = vec2(gid.xy); + let texSize = textureDimensions(inTex).xy; + if (fragCoord.x >= i32(texSize.x) || fragCoord.y >= i32(texSize.y)) { return; } + let center = textureLoad(inTex, fragCoord, 0); + + let scale = motionBlurData.params.x; + let sampleCount = i32(clamp(motionBlurData.params.y, 2.0, 32.0)); + if (scale <= 0.0) { + textureStore(outTex, fragCoord, center); + return; + } + + let fragUV = vec2(fragCoord) / vec2(texSize - 1u); + useNormalMatrixInv(); + let gBuffer = getGBuffer(fragCoord); + if (getRoughnessFromGBuffer(gBuffer) <= 0.0) { + // sky / unwritten pixel + textureStore(outTex, fragCoord, center); + return; + } + + let worldPos = getWorldPositionFromGBuffer(gBuffer, fragUV); + let prevClip = motionBlurData.prevViewProj * vec4(worldPos, 1.0); + if (prevClip.w <= 0.0) { + textureStore(outTex, fragCoord, center); + return; + } + let prevNdc = prevClip.xyz / prevClip.w; + let prevUv = vec2(prevNdc.x * 0.5 + 0.5, -prevNdc.y * 0.5 + 0.5); + + // Velocity in pixels, scaled by the shutter and clamped. + var velocity = (fragUV - prevUv) * vec2(texSize) * scale; + let len = length(velocity); + let maxLen = max(motionBlurData.params.z, 0.0); + if (len < 0.5) { + textureStore(outTex, fragCoord, center); + return; + } + if (len > maxLen) { velocity = velocity * (maxLen / len); } + + // Average along [-v/2, +v/2], centred on the pixel. + var acc = vec3(0.0); + let maxCoord = vec2(texSize) - vec2(1); + for (var i: i32 = 0; i < sampleCount; i = i + 1) { + let t = (f32(i) + 0.5) / f32(sampleCount) - 0.5; + let c = clamp(vec2(round(vec2(fragCoord) + velocity * t)), vec2(0), maxCoord); + acc += textureLoad(inTex, c, 0).rgb; + } + textureStore(outTex, fragCoord, vec4(acc / f32(sampleCount), center.a)); + } +`; diff --git a/src/assets/shader/fluid/FluidAnisotropy_shader.ts b/src/assets/shader/fluid/FluidAnisotropy_shader.ts new file mode 100644 index 000000000..916841cf2 --- /dev/null +++ b/src/assets/shader/fluid/FluidAnisotropy_shader.ts @@ -0,0 +1,418 @@ +import { FluidUniforms_wgsl } from './FluidParticle_shader'; + +/** + * Per-particle ellipsoids from the neighbor distribution (Yu & Turk 2013). + * + * Neighbor search uses a hashed uniform grid with cell size equal to the + * search radius, rebuilt every frame: + * clearCells → countCells → scanBlocks → scanBlockSums → addBlockOffsets → scatter + * which yields the positions sorted by hash bucket, so the neighbor loop + * reads contiguous memory. + * + * computeEllipsoids then gathers neighbors within the radius with weight + * 1 - (d / R)^3, moves the particle toward their weighted mean (Laplacian + * smoothing) and takes the eigen decomposition of their weighted + * covariance. The axes keep the particle volume, with the shortest axis + * at least 1 / maxRatio of the longest; particles with few neighbors stay + * spheres. + * + * Output per particle (4 × vec4f): smoothed center, then the three + * semi-axes scaled to their radius, in the particles' local space. + * + * Params layout (bytes): + * 0 count, stride (floats), position offset (floats), table size : u32 + * 16 cell size, search radius, particle radius, max axis ratio : f32 + * 32 min neighbors, smoothing : f32 + * @internal + */ +export let FluidAnisotropy_wgsl: string = /*wgsl*/ ` +struct AnisoParams { + count: u32, + stride: u32, + offset: u32, + tableSize: u32, + cellSize: f32, + radius: f32, + particleRadius: f32, + maxRatio: f32, + minNeighbors: f32, + smoothing: f32, + pad0: f32, + pad1: f32, +}; + +@group(0) @binding(0) var P: AnisoParams; +@group(0) @binding(1) var particles: array; +@group(0) @binding(2) var cellCount: array>; +@group(0) @binding(3) var cellStart: array; +@group(0) @binding(4) var blockSums: array; +// x = hash bucket, y = rank inside the bucket. +@group(0) @binding(5) var particleCell: array; +@group(0) @binding(6) var sortedPos: array; +@group(0) @binding(7) var ellipsoids: array; + +const SCAN_BLOCK: u32 = 1024u; + +fn position(i: u32) -> vec3f { + let b = i * P.stride + P.offset; + return vec3f(particles[b], particles[b + 1u], particles[b + 2u]); +} + +fn cellOf(p: vec3f) -> vec3i { + return vec3i(floor(p / P.cellSize)); +} + +fn hashCell(c: vec3i) -> u32 { + let h = (bitcast(c.x) * 73856093u) ^ (bitcast(c.y) * 19349663u) ^ (bitcast(c.z) * 83492791u); + return h & (P.tableSize - 1u); +} + +@compute @workgroup_size(256) +fn clearCells(@builtin(global_invocation_id) id: vec3u) { + if (id.x < P.tableSize) { + atomicStore(&cellCount[id.x], 0u); + } +} + +@compute @workgroup_size(256) +fn countCells(@builtin(global_invocation_id) id: vec3u) { + if (id.x >= P.count) { + return; + } + let h = hashCell(cellOf(position(id.x))); + particleCell[id.x] = vec2u(h, atomicAdd(&cellCount[h], 1u)); +} + +var scanShared: array; + +// Inclusive prefix sum of one value per invocation across the workgroup. +fn scanWorkgroup(lid: u32, value: u32) -> u32 { + scanShared[lid] = value; + workgroupBarrier(); + for (var offset = 1u; offset < 256u; offset <<= 1u) { + var add = 0u; + if (lid >= offset) { + add = scanShared[lid - offset]; + } + workgroupBarrier(); + scanShared[lid] += add; + workgroupBarrier(); + } + return scanShared[lid]; +} + +// Exclusive scan of cellCount into cellStart, per block of SCAN_BLOCK buckets. +@compute @workgroup_size(256) +fn scanBlocks(@builtin(local_invocation_id) lid: vec3u, @builtin(workgroup_id) wid: vec3u) { + let base = wid.x * SCAN_BLOCK + lid.x * 4u; + var v = vec4u(0u); + for (var k = 0u; k < 4u; k++) { + if (base + k < P.tableSize) { + v[k] = atomicLoad(&cellCount[base + k]); + } + } + let local = v.x + v.y + v.z + v.w; + let inclusive = scanWorkgroup(lid.x, local); + var run = inclusive - local; + for (var k = 0u; k < 4u; k++) { + if (base + k < P.tableSize) { + cellStart[base + k] = run; + } + run += v[k]; + } + if (lid.x == 255u) { + blockSums[wid.x] = inclusive; + } +} + +// Exclusive scan of the block totals in place (one workgroup, up to SCAN_BLOCK blocks). +@compute @workgroup_size(256) +fn scanBlockSums(@builtin(local_invocation_id) lid: vec3u) { + let blocks = (P.tableSize + SCAN_BLOCK - 1u) / SCAN_BLOCK; + let base = lid.x * 4u; + var v = vec4u(0u); + for (var k = 0u; k < 4u; k++) { + if (base + k < blocks) { + v[k] = blockSums[base + k]; + } + } + let local = v.x + v.y + v.z + v.w; + let inclusive = scanWorkgroup(lid.x, local); + var run = inclusive - local; + for (var k = 0u; k < 4u; k++) { + if (base + k < blocks) { + blockSums[base + k] = run; + } + run += v[k]; + } +} + +@compute @workgroup_size(256) +fn addBlockOffsets(@builtin(global_invocation_id) id: vec3u) { + if (id.x < P.tableSize) { + cellStart[id.x] += blockSums[id.x / SCAN_BLOCK]; + } +} + +@compute @workgroup_size(256) +fn scatter(@builtin(global_invocation_id) id: vec3u) { + if (id.x >= P.count) { + return; + } + let c = particleCell[id.x]; + sortedPos[cellStart[c.x] + c.y] = vec4f(position(id.x), 0.0); +} + +// Eigen decomposition of a symmetric 3x3 matrix by cyclic Jacobi rotations. +// Returns eigenvalues; eigenvectors are written as the columns of vecs. +fn eigenSymmetric(m: mat3x3f, vecs: ptr) -> vec3f { + var a = m; + var v = mat3x3f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); + for (var sweep = 0; sweep < 6; sweep++) { + for (var k = 0; k < 3; k++) { + let p = select(0, 1, k == 2); + let q = select(2, 1, k == 0); + let apq = a[q][p]; + if (abs(apq) < 1e-12) { + continue; + } + let theta = (a[q][q] - a[p][p]) / (2.0 * apq); + let t = select(1.0, -1.0, theta < 0.0) / (abs(theta) + sqrt(theta * theta + 1.0)); + let c = inverseSqrt(t * t + 1.0); + let s = t * c; + var j = mat3x3f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); + j[p][p] = c; + j[q][q] = c; + j[q][p] = s; + j[p][q] = -s; + a = transpose(j) * a * j; + v = v * j; + } + } + *vecs = v; + return vec3f(a[0][0], a[1][1], a[2][2]); +} + +@compute @workgroup_size(128) +fn computeEllipsoids(@builtin(global_invocation_id) id: vec3u) { + let i = id.x; + if (i >= P.count) { + return; + } + let pi = position(i); + let ci = cellOf(pi); + + var wsum = 0.0; + var n = 0.0; + var s1 = vec3f(0.0); + var sxx = 0.0; var sxy = 0.0; var sxz = 0.0; + var syy = 0.0; var syz = 0.0; var szz = 0.0; + for (var dz = -1; dz <= 1; dz++) { + for (var dy = -1; dy <= 1; dy++) { + for (var dx = -1; dx <= 1; dx++) { + let cell = ci + vec3i(dx, dy, dz); + let h = hashCell(cell); + let start = cellStart[h]; + let count = atomicLoad(&cellCount[h]); + for (var k = 0u; k < count; k++) { + let pj = sortedPos[start + k].xyz; + // Skip other cells that share this hash bucket. + if (any(cellOf(pj) != cell)) { + continue; + } + let r = pj - pi; + let d = length(r); + if (d >= P.radius) { + continue; + } + let q = d / P.radius; + let w = 1.0 - q * q * q; + wsum += w; + n += 1.0; + s1 += w * r; + sxx += w * r.x * r.x; sxy += w * r.x * r.y; sxz += w * r.x * r.z; + syy += w * r.y * r.y; syz += w * r.y * r.z; szz += w * r.z * r.z; + } + } + } + } + + // wsum >= 1: the particle itself is always found. + let mean = s1 / wsum; + let center = pi + P.smoothing * mean; + let pr = P.particleRadius; + var a1 = vec3f(pr, 0.0, 0.0); + var a2 = vec3f(0.0, pr, 0.0); + var a3 = vec3f(0.0, 0.0, pr); + + if (n >= P.minNeighbors) { + let cov = mat3x3f( + sxx / wsum - mean.x * mean.x, sxy / wsum - mean.x * mean.y, sxz / wsum - mean.x * mean.z, + sxy / wsum - mean.x * mean.y, syy / wsum - mean.y * mean.y, syz / wsum - mean.y * mean.z, + sxz / wsum - mean.x * mean.z, syz / wsum - mean.y * mean.z, szz / wsum - mean.z * mean.z, + ); + var vecs: mat3x3f; + let vals = eigenSymmetric(cov, &vecs); + // Spread along each axis (standard deviation), longest first. + var sd = sqrt(max(vals, vec3f(0.0))); + var e0 = vecs[0]; + var e1 = vecs[1]; + var e2 = vecs[2]; + if (sd.y > sd.x) { let t = sd.x; sd.x = sd.y; sd.y = t; let tv = e0; e0 = e1; e1 = tv; } + if (sd.z > sd.x) { let t = sd.x; sd.x = sd.z; sd.z = t; let tv = e0; e0 = e2; e2 = tv; } + if (sd.z > sd.y) { let t = sd.y; sd.y = sd.z; sd.z = t; let tv = e1; e1 = e2; e2 = tv; } + if (sd.x > 1e-8) { + sd = max(sd, vec3f(sd.x / P.maxRatio)); + // Keep the volume of a sphere of the particle radius. + let scale = pr / pow(sd.x * sd.y * sd.z, 1.0 / 3.0); + a1 = normalize(e0) * sd.x * scale; + a2 = normalize(e1) * sd.y * scale; + a3 = normalize(e2) * sd.z * scale; + } + } + + ellipsoids[i * 4u] = vec4f(center, 1.0); + ellipsoids[i * 4u + 1u] = vec4f(a1, 0.0); + ellipsoids[i * 4u + 2u] = vec4f(a2, 0.0); + ellipsoids[i * 4u + 3u] = vec4f(a3, 0.0); +} +`; + +/** + * Ellipsoid splatting: same stages as FluidParticle_wgsl, but each particle + * is the ellipsoid from FluidAnisotropy_wgsl. The quad covers the longest + * semi-axis; the fragment shader intersects the view ray with the + * ellipsoid. + * - fsDepth: linear view-space depth of the nearest hit (negated when hidden by the scene). + * - fsThickness: chord length, normalized so a sphere's center gives the thickness alpha. + * - fsBackDepth: far hit, clamped to the opaque scene (see FluidParticle_wgsl). + * @internal + */ +export let FluidEllipsoid_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var ellipsoids: array; +@group(0) @binding(2) var sceneDepth: texture_depth_2d; + +struct VOut { + @builtin(position) pos: vec4f, + @location(0) viewPos: vec3f, + @location(1) @interpolate(flat) center: vec3f, + @location(2) @interpolate(flat) a1: vec3f, + @location(3) @interpolate(flat) a2: vec3f, + @location(4) @interpolate(flat) a3: vec3f, +}; + +struct DepthOut { + @location(0) depth: f32, + @builtin(frag_depth) fragDepth: f32, +}; + +@vertex +fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { + var corners = array( + vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0), + vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0), + ); + let base = ii * 4u; + let center = (u.modelView * vec4f(ellipsoids[base].xyz, 1.0)).xyz; + let a1 = (u.modelView * vec4f(ellipsoids[base + 1u].xyz, 0.0)).xyz; + let a2 = (u.modelView * vec4f(ellipsoids[base + 2u].xyz, 0.0)).xyz; + let a3 = (u.modelView * vec4f(ellipsoids[base + 3u].xyz, 0.0)).xyz; + let extent = max(length(a1), max(length(a2), length(a3))); + let p = center + vec3f(corners[vi] * extent, 0.0); + + var out: VOut; + out.pos = u.proj * vec4f(p, 1.0); + out.viewPos = p; + out.center = center; + out.a1 = a1; + out.a2 = a2; + out.a3 = a3; + return out; +} + +// Ray from the camera through this fragment against the ellipsoid; returns (near, far) or (-1, -1). +fn hitEllipsoid(in: VOut) -> vec2f { + let dir = normalize(in.viewPos); + // Rows of the inverse of [a1 a2 a3]: the axes are orthogonal. + let q1 = in.a1 / dot(in.a1, in.a1); + let q2 = in.a2 / dot(in.a2, in.a2); + let q3 = in.a3 / dot(in.a3, in.a3); + let o = vec3f(dot(q1, -in.center), dot(q2, -in.center), dot(q3, -in.center)); + let d = vec3f(dot(q1, dir), dot(q2, dir), dot(q3, dir)); + let a = dot(d, d); + let b = dot(o, d); + let c = dot(o, o) - 1.0; + let disc = b * b - a * c; + if (disc < 0.0) { + return vec2f(-1.0); + } + let s = sqrt(disc); + return vec2f((-b - s) / a, (-b + s) / a); +} + +fn sceneViewZ(fragXY: vec2f, mapSize: vec2f) -> f32 { + let dim = vec2f(textureDimensions(sceneDepth)); + let p = vec2i(fragXY * dim / mapSize); + let d = textureLoad(sceneDepth, p, 0); + #if USE_LOGDEPTH + return pow(u.camera.y + 1.0, d) - 1.0; + #else + let v = u.projInv * vec4f(0.0, 0.0, d, 1.0); + return v.z / v.w; + #endif +} + +@fragment +fn fsDepth(in: VOut) -> DepthOut { + let t = hitEllipsoid(in); + if (t.y <= 0.0) { + discard; + } + let viewPos = normalize(in.viewPos) * max(t.x, 0.0); + // Hidden by the scene: stored negated, see FluidParticle_wgsl. + let hidden = viewPos.z > sceneViewZ(in.pos.xy, u.size.xy); + let clip = u.proj * vec4f(viewPos, 1.0); + var out: DepthOut; + out.depth = select(viewPos.z, -viewPos.z, hidden); + out.fragDepth = clip.z / clip.w; + return out; +} + +@fragment +fn fsThickness(in: VOut) -> @location(0) f32 { + let t = hitEllipsoid(in); + if (t.y <= 0.0) { + discard; + } + let near = max(t.x, 0.0); + if ((normalize(in.viewPos) * near).z > sceneViewZ(in.pos.xy, u.thickSize.xy)) { + discard; + } + return u.particle.w * (t.y - near) / (2.0 * u.particle.x); +} + +@fragment +fn fsBackDepth(in: VOut) -> DepthOut { + let t = hitEllipsoid(in); + if (t.y <= 0.0) { + discard; + } + let dir = normalize(in.viewPos); + let sceneZ = sceneViewZ(in.pos.xy, u.size.xy); + if ((dir * max(t.x, 0.0)).z > sceneZ) { + discard; + } + var far = dir * t.y; + if (far.z > sceneZ) { + far = far * (sceneZ / far.z); + } + let clip = u.proj * vec4f(far, 1.0); + var out: DepthOut; + out.depth = far.z; + out.fragDepth = clamp(clip.z / clip.w, 0.0, 1.0); + return out; +} +`; diff --git a/src/assets/shader/fluid/FluidParticle_shader.ts b/src/assets/shader/fluid/FluidParticle_shader.ts new file mode 100644 index 000000000..73a2e69f5 --- /dev/null +++ b/src/assets/shader/fluid/FluidParticle_shader.ts @@ -0,0 +1,702 @@ +/** + * Uniforms shared by the fluid particle and debug stages. Layout (bytes): + * 0 modelView : mat4x4f object world → view + * 64 proj : mat4x4f + * 128 projInv : mat4x4f + * 192 particle : vec4f x = radius, y = stride (floats), z = position offset (floats), w = thickness alpha + * 208 camera : vec4f x = near, y = far, z = debug feature + * 224 size : vec4f xy = depth map size, zw = screen size + * 240 thickSize : vec4f xy = thickness map size + * @internal + */ +export let FluidUniforms_wgsl: string = /*wgsl*/ ` +struct FluidUniforms { + modelView: mat4x4f, + proj: mat4x4f, + projInv: mat4x4f, + particle: vec4f, + camera: vec4f, + size: vec4f, + thickSize: vec4f, +}; +`; + +/** + * Sphere-impostor particle stages. Each particle is a camera-facing + * quad; fragments outside the disc are dropped. + * - fsDepth: linear view-space depth of the sphere surface. Fluid hidden + * by the opaque scene is stored negated: the depth filters skip it + * instead of treating it as the fluid's edge. 0 means no fluid. + * - fsThickness: thickness contribution, accumulated with additive blending. + * - fsBackDepth: linear depth of the far side of the sphere, clamped to the + * opaque scene; kept with a "greater" depth test, it gives the far side of + * the fluid volume for geometric thickness. + * @internal + */ +export let FluidParticle_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var particles: array; +@group(0) @binding(2) var sceneDepth: texture_depth_2d; + +struct VOut { + @builtin(position) pos: vec4f, + @location(0) corner: vec2f, + @location(1) center: vec3f, +}; + +struct DepthOut { + @location(0) depth: f32, + @builtin(frag_depth) fragDepth: f32, +}; + +@vertex +fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { + var corners = array( + vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0), + vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0), + ); + let base = ii * u32(u.particle.y) + u32(u.particle.z); + let local = vec3f(particles[base], particles[base + 1u], particles[base + 2u]); + let center = (u.modelView * vec4f(local, 1.0)).xyz; + let corner = corners[vi]; + + var out: VOut; + out.pos = u.proj * vec4f(center + vec3f(corner * u.particle.x, 0.0), 1.0); + out.corner = corner; + out.center = center; + return out; +} + +// View-space depth of the opaque scene under a pixel of a map of size mapSize. +fn sceneViewZ(fragXY: vec2f, mapSize: vec2f) -> f32 { + let dim = vec2f(textureDimensions(sceneDepth)); + let p = vec2i(fragXY * dim / mapSize); + let d = textureLoad(sceneDepth, p, 0); + #if USE_LOGDEPTH + return pow(u.camera.y + 1.0, d) - 1.0; + #else + let v = u.projInv * vec4f(0.0, 0.0, d, 1.0); + return v.z / v.w; + #endif +} + +// View-space point on the visible hemisphere; the camera looks down +z. +fn spherePoint(in: VOut, r2: f32) -> vec3f { + let radius = u.particle.x; + return vec3f(in.center.xy + in.corner * radius, in.center.z - sqrt(1.0 - r2) * radius); +} + +@fragment +fn fsDepth(in: VOut) -> DepthOut { + let r2 = dot(in.corner, in.corner); + if (r2 > 1.0) { + discard; + } + let viewPos = spherePoint(in, r2); + let hidden = viewPos.z > sceneViewZ(in.pos.xy, u.size.xy); + let clip = u.proj * vec4f(viewPos, 1.0); + var out: DepthOut; + out.depth = select(viewPos.z, -viewPos.z, hidden); + out.fragDepth = clip.z / clip.w; + return out; +} + +@fragment +fn fsThickness(in: VOut) -> @location(0) f32 { + let r2 = dot(in.corner, in.corner); + if (r2 > 1.0) { + discard; + } + if (spherePoint(in, r2).z > sceneViewZ(in.pos.xy, u.thickSize.xy)) { + discard; + } + return u.particle.w * sqrt(1.0 - r2); +} + +@fragment +fn fsBackDepth(in: VOut) -> DepthOut { + let r2 = dot(in.corner, in.corner); + if (r2 > 1.0) { + discard; + } + let sceneZ = sceneViewZ(in.pos.xy, u.size.xy); + if (spherePoint(in, r2).z > sceneZ) { + discard; + } + let radius = u.particle.x; + let far = vec3f(in.center.xy + in.corner * radius, min(in.center.z + sqrt(1.0 - r2) * radius, sceneZ)); + let clip = u.proj * vec4f(far, 1.0); + var out: DepthOut; + out.depth = far.z; + out.fragDepth = clamp(clip.z / clip.w, 0.0, 1.0); + return out; +} +`; + +/** + * Geometric thickness: distance between the far side and the near side of + * the fluid volume per pixel, in world units. Unlike accumulated thickness + * it does not depend on how densely the particles sample the volume. + * @internal + */ +export let FluidGeometricThickness_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var frontDepth: texture_2d; +@group(0) @binding(2) var backDepth: texture_2d; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[vi], 0.0, 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + let uv = pos.xy / u.thickSize.xy; + let p = vec2i(uv * vec2f(textureDimensions(frontDepth))); + let front = textureLoad(frontDepth, p, 0).r; + let back = textureLoad(backDepth, p, 0).r; + if (front <= 0.0 || back <= 0.0) { + return 0.0; + } + return max(back - front, 0.0); +} +`; + +/** + * Parameters of one separable blur pass. Layout (bytes): + * 0 dir : vec2f (1,0) horizontal or (0,1) vertical + * 8 dstSize : vec2f size of the target being written + * 16 params : vec4f depth filters: x = projected particle constant, y = max filter size, z = depth threshold, + * w = background clamp offset (narrow-range) + * gaussian: x = filter size + * 32 params2 : vec4f depth filters: x = world size of one target pixel per unit of depth, + * y = largest depth threshold scale at grazing angles + * @internal + */ +export let FluidBlurParams_wgsl: string = /*wgsl*/ ` +struct BlurParams { + dir: vec2f, + dstSize: vec2f, + params: vec4f, + params2: vec4f, +}; + +@group(0) @binding(0) var b: BlurParams; +@group(0) @binding(1) var src: texture_2d; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[vi], 0.0, 1.0); +} + +// Source texel for a target pixel offset by \`offset\` target pixels. +fn srcTexelAt(fragXY: vec2f, offset: vec2f) -> vec2i { + let srcDim = vec2f(textureDimensions(src)); + let q = (fragXY + offset) * srcDim / b.dstSize; + return clamp(vec2i(q), vec2i(0), vec2i(srcDim) - 1); +} + +// Source texel for a target pixel offset by k pixels along the blur direction. +fn srcTexel(fragXY: vec2f, k: i32) -> vec2i { + return srcTexelAt(fragXY, b.dir * f32(k)); +} + +// Depth threshold, widened where the surface is seen at a grazing angle: there a small height +// bump shows up as a depth step of about height / tan(angle). The local depth slope per pixel, +// over the world size of a pixel, estimates 1 / tan(angle). +fn grazingThreshold(fragXY: vec2f, depth: f32) -> f32 { + let k = 2.0; + let x0 = textureLoad(src, srcTexelAt(fragXY, vec2f(-k, 0.0)), 0).r; + let x1 = textureLoad(src, srcTexelAt(fragXY, vec2f(k, 0.0)), 0).r; + let y0 = textureLoad(src, srcTexelAt(fragXY, vec2f(0.0, -k)), 0).r; + let y1 = textureLoad(src, srcTexelAt(fragXY, vec2f(0.0, k)), 0).r; + if (min(min(x0, x1), min(y0, y1)) <= 0.0) { + return b.params.z; + } + let slope = length(vec2f(x1 - x0, y1 - y0)) / (2.0 * k); + let pixelWorld = max(depth * b.params2.x, 1e-6); + return b.params.z * min(1.0 + slope / pixelWorld, b.params2.y); +} +`; + +/** + * Depth-aware (bilateral) blur of the fluid depth map. The radius + * follows the projected particle size; samples are weighted by how + * close their depth is to the center pixel, so separate surfaces are + * not blended together. + * @internal + */ +export let FluidBilateralBlur_wgsl: string = /*wgsl*/ ` +${FluidBlurParams_wgsl} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + let depth = textureLoad(src, srcTexel(pos.xy, 0), 0).r; + if (depth <= 0.0) { + // No fluid (0) or hidden fluid (negative): keep the marker. + return depth; + } + let filterSize = i32(min(b.params.y, ceil(b.params.x / depth))); + let sigma = max(f32(filterSize) / 3.0, 1e-3); + let twoSigma2 = 2.0 * sigma * sigma; + let sigmaDepth = grazingThreshold(pos.xy, depth) / 3.0; + let twoSigmaDepth2 = 2.0 * sigmaDepth * sigmaDepth; + + var sum = 0.0; + var wsum = 0.0; + for (var k = -filterSize; k <= filterSize; k++) { + let s = textureLoad(src, srcTexel(pos.xy, k), 0).r; + if (s <= 0.0) { + continue; + } + let x = f32(k); + let dz = s - depth; + let w = exp(-x * x / twoSigma2) * exp(-dz * dz / twoSigmaDepth2); + sum += s * w; + wsum += w; + } + return sum / wsum; +} +`; + +/** + * Narrow-range filter of the fluid depth map (Truong & Yuksel 2018). + * Only samples within a depth range around the center are averaged. + * The range starts at center ± threshold and widens as in-range samples + * are met walking outward, so it follows sloped surfaces. Samples in + * front of the range (another surface) drop out together with their + * mirrored sample, which keeps the result unbiased; samples behind it, + * or without fluid (0), count at center + clamp offset, which rounds + * free silhouettes off instead of pulling them toward the background. + * Skipped instead, so the surface stays flat up to the geometry: + * - fluid hidden by the scene (negative), where it runs behind an object; + * - samples without fluid whose opaque surface lies within the clamp + * offset behind the center, where the fluid meets a wall or the floor. + * - fs: 1D pass along b.dir, radius from the projected particle size. + * - fs2D: small 2D pass over the ring of radius 1 and 2, run last to + * remove the axis-aligned streaks of the separable passes. + * @internal + */ +export let FluidNarrowRangeFilter_wgsl: string = /*wgsl*/ ` +${FluidBlurParams_wgsl} + +// Linear view depth of the opaque scene (FluidSceneLinearDepth_wgsl). +@group(0) @binding(2) var sceneLinear: texture_2d; + +fn sceneAt(fragXY: vec2f, offset: vec2f) -> f32 { + let dim = vec2f(textureDimensions(sceneLinear)); + let q = (fragXY + offset) * dim / b.dstSize; + return textureLoad(sceneLinear, clamp(vec2i(q), vec2i(0), vec2i(dim) - 1), 0).r; +} + +struct NarrowRange { + low: f32, + high: f32, +}; + +const NR_IN_FRONT: f32 = -1.0; +const NR_HIDDEN: f32 = -2.0; + +// Classifies a sample against a range: returns the depth to use, NR_IN_FRONT for a sample in +// front of the range (drops the pair) or NR_HIDDEN for a sample to skip (see above). +fn classify(s: f32, sceneZ: f32, center: f32, thr: f32, range: ptr, background: f32) -> f32 { + if (s < 0.0) { + return NR_HIDDEN; + } + if (s == 0.0) { + return select(background, NR_HIDDEN, sceneZ - center < b.params.w); + } + if (s < (*range).low) { + return NR_IN_FRONT; + } + if (s > (*range).high) { + return background; + } + (*range).low = min((*range).low, s - thr); + (*range).high = max((*range).high, s + thr); + return s; +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + let depth = textureLoad(src, srcTexel(pos.xy, 0), 0).r; + if (depth <= 0.0) { + return depth; + } + let filterSize = i32(min(b.params.y, ceil(b.params.x / depth))); + let sigma = max(f32(filterSize) / 2.0, 1e-3); + let invTwoSigma2 = 1.0 / (2.0 * sigma * sigma); + let thr = grazingThreshold(pos.xy, depth); + let background = depth + b.params.w; + + var negSide = NarrowRange(depth - thr, depth + thr); + var posSide = NarrowRange(depth - thr, depth + thr); + var sum = depth; + var wsum = 1.0; + for (var r = 1; r <= filterSize; r++) { + let g = exp(-f32(r * r) * invTwoSigma2); + let off = b.dir * f32(r); + let a = classify(textureLoad(src, srcTexel(pos.xy, -r), 0).r, sceneAt(pos.xy, -off), depth, thr, &negSide, background); + let c = classify(textureLoad(src, srcTexel(pos.xy, r), 0).r, sceneAt(pos.xy, off), depth, thr, &posSide, background); + if (a == NR_IN_FRONT || c == NR_IN_FRONT) { + continue; + } + let wa = select(0.0, g, a >= 0.0); + let wc = select(0.0, g, c >= 0.0); + sum += a * wa + c * wc; + wsum += wa + wc; + } + return sum / wsum; +} + +@fragment +fn fs2D(@builtin(position) pos: vec4f) -> @location(0) f32 { + let depth = textureLoad(src, srcTexelAt(pos.xy, vec2f(0.0)), 0).r; + if (depth <= 0.0) { + return depth; + } + let thr = grazingThreshold(pos.xy, depth); + let background = depth + b.params.w; + var range = NarrowRange(depth - thr, depth + thr); + var sum = depth; + var wsum = 1.0; + // Each offset and its mirror form a pair, so one sample in front drops both. + for (var r = 1; r <= 2; r++) { + for (var i = 0; i < 2 * r; i++) { + let o1 = vec2f(f32(r), f32(r - i)); + let o2 = vec2f(f32(r - i), -f32(r)); + for (var k = 0; k < 2; k++) { + let o = select(o1, o2, k == 1); + let g = exp(-dot(o, o) / 8.0); + let a = classify(textureLoad(src, srcTexelAt(pos.xy, -o), 0).r, sceneAt(pos.xy, -o), depth, thr, &range, background); + let c = classify(textureLoad(src, srcTexelAt(pos.xy, o), 0).r, sceneAt(pos.xy, o), depth, thr, &range, background); + if (a == NR_IN_FRONT || c == NR_IN_FRONT) { + continue; + } + let wa = select(0.0, g, a >= 0.0); + let wc = select(0.0, g, c >= 0.0); + sum += a * wa + c * wc; + wsum += wa + wc; + } + } + } + return sum / wsum; +} +`; + +/** + * Linear view depth of the opaque scene at the fluid depth-map size, for + * the narrow-range filter to tell where the fluid meets geometry. + * @internal + */ +export let FluidSceneLinearDepth_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var sceneDepth: texture_depth_2d; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[vi], 0.0, 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + let dim = vec2f(textureDimensions(sceneDepth)); + let d = textureLoad(sceneDepth, vec2i(pos.xy * dim / u.size.xy), 0); + #if USE_LOGDEPTH + return pow(u.camera.y + 1.0, d) - 1.0; + #else + let v = u.projInv * vec4f(0.0, 0.0, d, 1.0); + return v.z / v.w; + #endif +} +`; + +/** + * Gaussian blur of the thickness map. + * @internal + */ +export let FluidGaussianBlur_wgsl: string = /*wgsl*/ ` +${FluidBlurParams_wgsl} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + if (textureLoad(src, srcTexel(pos.xy, 0), 0).r == 0.0) { + return 0.0; + } + let filterSize = i32(b.params.x); + let sigma = max(f32(filterSize) / 3.0, 1e-3); + let twoSigma2 = 2.0 * sigma * sigma; + var sum = 0.0; + var wsum = 0.0; + for (var k = -filterSize; k <= filterSize; k++) { + let x = f32(k); + let w = exp(-x * x / twoSigma2); + sum += textureLoad(src, srcTexel(pos.xy, k), 0).r * w; + wsum += w; + } + return sum / wsum; +} +`; + +/** + * Reconstruct view-space position and normal from a fluid depth map. + * Expects `u: FluidUniforms` and `fluidDepth: texture_2d`. + * @internal + */ +export let FluidSurface_wgsl: string = /*wgsl*/ ` +fn fluidViewPos(p: vec2i) -> vec3f { + let dim = vec2i(textureDimensions(fluidDepth)); + let q = clamp(p, vec2i(0), dim - 1); + let z = textureLoad(fluidDepth, q, 0).r; + if (z <= 0.0) { + // No fluid: a far point, so fluidNormal prefers the other neighbor. + return vec3f(0.0, 0.0, 1e6); + } + let uv = (vec2f(q) + 0.5) / vec2f(dim); + let clip = u.proj * vec4f(0.0, 0.0, z, 1.0); + let ndc = vec4f(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, clip.z / clip.w, 1.0); + let v = u.projInv * ndc; + return v.xyz / v.w; +} + +// Normal facing the camera. For each axis the neighbor with the smaller +// depth step is used, so silhouettes do not bend the normal. +fn fluidNormal(p: vec2i, center: vec3f) -> vec3f { + var ddx = fluidViewPos(p + vec2i(1, 0)) - center; + let ddx2 = center - fluidViewPos(p - vec2i(1, 0)); + if (abs(ddx2.z) < abs(ddx.z)) { + ddx = ddx2; + } + var ddy = fluidViewPos(p + vec2i(0, 1)) - center; + let ddy2 = center - fluidViewPos(p - vec2i(0, 1)); + if (abs(ddy2.z) < abs(ddy.z)) { + ddy = ddy2; + } + var n = normalize(cross(ddx, ddy)); + if (n.z > 0.0) { + n = -n; + } + return n; +} +`; + +/** + * Full-screen debug view selected by `u.camera.z` (FluidDebug): + * depth maps are distance-darkened and slope-shaded, thickness maps + * map to grey, normals map to RGB. Pixels without fluid keep the scene. + * @internal + */ +export let FluidDebugView_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var fluidDepth: texture_2d; +@group(0) @binding(2) var fluidThickness: texture_2d; + +${FluidSurface_wgsl} + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[vi], 0.0, 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let mode = i32(u.camera.z); + let uv = pos.xy / u.size.zw; + let pd = vec2i(uv * vec2f(textureDimensions(fluidDepth))); + let z = textureLoad(fluidDepth, pd, 0).r; + // Derivatives before any discard: they need uniform control flow. + let dz = vec2f(dpdx(z), dpdy(z)); + + if (mode == 2 || mode == 3) { + let pt = vec2i(uv * vec2f(textureDimensions(fluidThickness))); + let t = textureLoad(fluidThickness, pt, 0).r; + if (t <= 0.0) { + discard; + } + return vec4f(vec3f(1.0 - exp(-t)), 1.0); + } + if (z <= 0.0) { + discard; + } + if (mode == 4) { + let n = fluidNormal(pd, fluidViewPos(pd)); + return vec4f(n * 0.5 + 0.5, 1.0); + } + // World size of one screen pixel at depth z (perspective). + let pixelSize = 2.0 * z / (u.proj[1][1] * u.size.w); + let slope = abs(normalize(vec3f(dz, pixelSize)).z); + let c = log2(z + 1.0) / log2(u.camera.y + 1.0); + return vec4f(vec3f((1.0 - c) * (0.2 + 0.8 * slope)), 1.0); +} +`; + +/** + * Shading parameters of the composite stage. Layout (bytes): + * 0 fluidColor : vec4f rgb = absorption color, a = 1 when thickness is geometric (world units) + * 16 light : vec4f xyz = view-space direction toward the light, w = specular power + * 32 params : vec4f x = density, y = refraction strength, z = fresnel clamp, w = minimum thickness + * 48 flags : vec4f x = fixed thickness, y = has environment map, z = environment exposure, + * w = edge fade thickness (0 = off) + * 64 invView : mat4x4f + * @internal + */ +export let FluidShadeUniforms_wgsl: string = /*wgsl*/ ` +struct FluidShade { + fluidColor: vec4f, + light: vec4f, + params: vec4f, + flags: vec4f, + invView: mat4x4f, +}; +`; + +/** + * Final fluid shading, in two entry points sharing group 0: + * - fsColor: shades the surface into the scene color. It reads the scene + * depth (group 1) to drop fluid hidden by opaque geometry and to find + * how far the refracted ray travels before it reaches the scene behind; + * that point is projected back to the screen to sample the scene color. + * Absorption is Beer-Lambert, exp(-density * thickness * (1 - fluidColor)); + * reflection is the environment cube map weighted by Schlick fresnel; + * specular is a Blinn-Phong highlight of one directional light. + * - fsDepth: writes the fluid surface into the scene depth, so transparent + * objects drawn afterwards are clipped by it. + * @internal + */ +export let FluidComposite_wgsl: string = /*wgsl*/ ` +${FluidUniforms_wgsl} +${FluidShadeUniforms_wgsl} + +@group(0) @binding(0) var u: FluidUniforms; +@group(0) @binding(1) var fluidDepth: texture_2d; +@group(0) @binding(2) var fluidThickness: texture_2d; +@group(0) @binding(3) var s: FluidShade; +@group(1) @binding(0) var sceneColor: texture_2d; +@group(1) @binding(1) var linearSampler: sampler; +@group(1) @binding(2) var envMap: texture_cube; +@group(1) @binding(3) var sceneDepth: texture_depth_2d; + +${FluidSurface_wgsl} + +const WATER_ETA: f32 = 1.0 / 1.333; +const WATER_F0: f32 = 0.02; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var p = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(p[vi], 0.0, 1.0); +} + +// Thickness at a screen uv, or -1 where there is no fluid to draw. +fn coveredThickness(uv: vec2f) -> f32 { + let pd = vec2i(uv * vec2f(textureDimensions(fluidDepth))); + if (textureLoad(fluidDepth, pd, 0).r <= 0.0) { + return -1.0; + } + if (s.flags.x > 0.5) { + return s.params.w; + } + let pt = vec2i(uv * vec2f(textureDimensions(fluidThickness))); + let thickness = textureLoad(fluidThickness, pt, 0).r; + return select(-1.0, thickness, thickness > s.params.w); +} + +fn depthPixel(uv: vec2f) -> vec2i { + return vec2i(uv * vec2f(textureDimensions(fluidDepth))); +} + +fn encodeDepth(viewPos: vec3f) -> f32 { + #if USE_LOGDEPTH + return log2(1.0 + viewPos.z) / log2(u.camera.y + 1.0); + #else + let clip = u.proj * vec4f(viewPos, 1.0); + return clip.z / clip.w; + #endif +} + +// View-space depth of the opaque scene at a screen uv. +fn sceneViewZ(uv: vec2f) -> f32 { + let dim = vec2f(textureDimensions(sceneDepth)); + let d = textureLoad(sceneDepth, clamp(vec2i(uv * dim), vec2i(0), vec2i(dim) - 1), 0); + #if USE_LOGDEPTH + return pow(u.camera.y + 1.0, d) - 1.0; + #else + let v = u.projInv * vec4f(0.0, 0.0, d, 1.0); + return v.z / v.w; + #endif +} + +@fragment +fn fsColor(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let uv = pos.xy / u.size.zw; + let thickness = coveredThickness(uv); + if (thickness < 0.0) { + discard; + } + let pd = depthPixel(uv); + let viewPos = fluidViewPos(pd); + let sceneZ = sceneViewZ(uv); + if (viewPos.z >= sceneZ) { + discard; + } + let n = fluidNormal(pd, viewPos); + let rayDir = normalize(viewPos); + + let h = normalize(s.light.xyz - rayDir); + let specular = pow(max(dot(h, n), 0.0), s.light.w); + + // Follow the refracted ray to the depth of the scene behind, project that point back to + // the screen and sample the scene there. Grazing rays are capped so they cannot run off + // across the screen. With geometric thickness the ray also stays within the fluid's + // extent along the view: seen at a grazing angle the scene behind the pixel lies far + // beyond where the refracted ray reaches the bottom, and the long lever would turn small + // normal variations into streaks. + let refr = refract(rayDir, n, WATER_ETA); + var travel = (sceneZ - viewPos.z) / max(refr.z, 0.25); + if (s.fluidColor.a > 0.5) { + travel = min(travel, thickness); + } + let hit = u.proj * vec4f(viewPos + refr * travel * s.params.y, 1.0); + let hitUV = vec2f(hit.x / hit.w * 0.5 + 0.5, 0.5 - hit.y / hit.w * 0.5); + let transmitted = textureSampleLevel(sceneColor, linearSampler, hitUV, 0.0).rgb; + let transmittance = exp(-s.params.x * thickness * (1.0 - s.fluidColor.rgb)); + let refraction = transmitted * transmittance; + + var color = refraction; + if (s.flags.y > 0.5) { + let reflDir = (s.invView * vec4f(reflect(rayDir, n), 0.0)).xyz; + let reflection = textureSampleLevel(envMap, linearSampler, reflDir, 0.0).rgb * s.flags.z; + let fresnel = clamp(WATER_F0 + (1.0 - WATER_F0) * pow(1.0 - max(dot(n, -rayDir), 0.0), 5.0), 0.0, s.params.z); + color = mix(refraction, reflection, fresnel); + } + color += specular; + // Thin rims at free edges: the smoothed surface bends to grazing there and would show a dark + // reflection outline and a hard silhouette, so fade toward the unrefracted background. + if (s.flags.w > 0.0) { + let background = textureSampleLevel(sceneColor, linearSampler, uv, 0.0).rgb; + color = mix(background, color, smoothstep(0.0, s.flags.w, thickness)); + } + return vec4f(color, 1.0); +} + +@fragment +fn fsDepth(@builtin(position) pos: vec4f) -> @builtin(frag_depth) f32 { + let uv = pos.xy / u.size.zw; + if (coveredThickness(uv) < 0.0) { + discard; + } + return encodeDepth(fluidViewPos(depthPixel(uv))); +} +`; diff --git a/src/assets/shader/lighting/BxDF_frag.ts b/src/assets/shader/lighting/BxDF_frag.ts index 0140b55a8..59cb26647 100644 --- a/src/assets/shader/lighting/BxDF_frag.ts +++ b/src/assets/shader/lighting/BxDF_frag.ts @@ -18,6 +18,8 @@ export let BxDF_frag: string = /*wgsl*/ ` #include "Irradiance_frag" #include "ColorUtil_frag" #include "BxdfDebug_frag" + #include "Sheen_frag" + #include "Iridescence_frag" #include "ReflectionCG" //ORI_ShadingInput @@ -57,6 +59,9 @@ export let BxDF_frag: string = /*wgsl*/ ` let iorF0 = pow((materialUniform.ior - 1.0) / max(materialUniform.ior + 1.0, 1e-4), 2.0); let dielectricF0 = vec3(iorF0) * materialUniform.specularColor.rgb; fragData.F0 = mix(dielectricF0, fragData.Albedo.rgb, fragData.Metallic); + #if USE_IRIDESCENCE + fragData.F0 = applyIridescenceF0(fragData.F0, fragData.NoV); + #endif // fragData.F0 = gammaToLiner(fragData.F0); fragData.F = computeFresnelSchlick(fragData.NoV, fragData.F0); @@ -164,6 +169,10 @@ export let BxDF_frag: string = /*wgsl*/ ` var color = vec3f(iblDiffuseResult + indirectionSpec + specColor) ; // var color = vec3f(indirectionDiffuse ) ; + #if USE_SHEEN + color = applySheen(color, start, end); + #endif + var clearCoatColor = vec3(0.0); #if USE_CLEARCOAT let clearCoatBaseColor = vec3(1.0) * materialUniform.baseColor.rgb ; diff --git a/src/assets/shader/materials/WaterShader.ts b/src/assets/shader/materials/WaterShader.ts new file mode 100644 index 000000000..ab085f99a --- /dev/null +++ b/src/assets/shader/materials/WaterShader.ts @@ -0,0 +1,672 @@ +import { WATER_FFT_MIPS, WATER_FFT_SIZE } from '../../../components/renderer/WaterFFT'; + +/** Number of Gerstner waves the water shaders evaluate. */ +export const WATER_MAX_WAVES = 8; + +/** + * Gerstner waves shared by the water surface, the underwater pass and + * WaterRenderer.getHeight on the CPU. A wave is vec4(direction.x, + * direction.z, steepness, wavelength); a wavelength of 0 disables it. + * Phase speed follows deep-water dispersion, c = sqrt(g / k). + * @internal + */ +export let WaterWaves_wgsl: string = /*wgsl*/ ` + const WATER_GRAVITY: f32 = 9.81; + const WATER_PI: f32 = 3.14159265; + + // Adds one wave's displacement and accumulates the surface tangent / binormal. + fn gerstner(wave: vec4, p: vec2, t: f32, tangent: ptr>, binormal: ptr>) -> vec3 { + if (wave.w <= 0.0) { + return vec3(0.0); + } + let k = 2.0 * WATER_PI / wave.w; + let c = sqrt(WATER_GRAVITY / k); + let d = normalize(wave.xy); + let f = k * (dot(d, p) - c * t); + let a = wave.z / k; + let s = sin(f); + let co = cos(f); + *tangent += vec3(-d.x * d.x * wave.z * s, d.x * wave.z * co, -d.x * d.y * wave.z * s); + *binormal += vec3(-d.x * d.y * wave.z * s, d.y * wave.z * co, -d.y * d.y * wave.z * s); + return vec3(d.x * a * co, a * s, d.y * a * co); + } + + const WATER_WAVES: i32 = ${WATER_MAX_WAVES}; + + // Displacement of the undisplaced surface point p (world xz) by the waves. + fn waterWaves(waves: array, ${WATER_MAX_WAVES}>, p: vec2, t: f32, + tangent: ptr>, binormal: ptr>) -> vec3 { + var w = waves; + var d = vec3(0.0); + for (var i = 0; i < WATER_WAVES; i++) { + d += gerstner(w[i], p, t, tangent, binormal); + } + return d; + } + + // Height of the displaced surface above world xz, relative to the undisplaced plane. + // The waves also move points sideways, so the source point is found by fixed-point iteration. + fn waterHeight(waves: array, ${WATER_MAX_WAVES}>, xz: vec2, t: f32) -> f32 { + var tangent = vec3(0.0); + var binormal = vec3(0.0); + var p = xz; + for (var i = 0; i < 4; i++) { + p = xz - waterWaves(waves, p, t, &tangent, &binormal).xz; + } + return waterWaves(waves, p, t, &tangent, &binormal).y; + } + + // Fine ripples on top of the waves, too small to displace the mesh: direction angle, + // wavelength relative to the detail scale, relative steepness, phase. They bend the + // surface normal per pixel and focus the sunlight into caustics. + const WATER_DETAIL_COUNT: i32 = 8; + const WATER_DETAIL = array, 8>( + vec4(0.00, 1.00, 1.0, 0.0), vec4(2.40, 0.73, 1.0, 1.7), + vec4(4.80, 1.31, 0.8, 4.1), vec4(0.92, 0.58, 1.1, 2.9), + vec4(3.32, 0.87, 1.0, 5.3), vec4(5.72, 1.12, 0.9, 0.6), + vec4(1.84, 0.66, 1.1, 3.6), vec4(4.24, 1.47, 0.8, 2.2), + ); + // Shortest detail wavelength relative to the detail scale. + const WATER_DETAIL_SHORTEST: f32 = 0.58; + // Wavelength of the second, coarser octave of surface detail relative to the first. + const WATER_DETAIL_OCTAVE: f32 = 2.3; + // Light path in the water at which the ripples focus sunlight into the sharpest lines; + // their steepness follows from it, so the detail scale changes their size, not the focus. + // Past the bottom of a typical pool, so the caustics there are still soft. + const WATER_DETAIL_FOCUS: f32 = 3.5; + + struct WaterSlope { + // height gradient (x, z) + grad: vec2, + // second derivatives (xx, xz, zz) + hess: vec3, + }; + + // Adds one sinusoidal height term (s / k) * sin(phase): direction d, wavenumber k, steepness s. + fn waterSlopeTerm(slope: ptr, d: vec2, k: f32, s: f32, phase: f32) { + (*slope).grad += s * cos(phase) * d; + (*slope).hess += -s * k * sin(phase) * vec3(d.x * d.x, d.x * d.y, d.y * d.y); + } + + // Adds the fine ripples at xz; scale = their base wavelength, angle turns their directions. + fn waterDetail(slope: ptr, xz: vec2, t: f32, scale: f32, angle: f32) { + // The summed curvature is about steepness * k * sqrt(count / 2), and focuses the light + // where WATER_DETAIL_FOCUS * (1 - 1 / 1.333) times it reaches 1. + let steepness = 1.0 / (WATER_DETAIL_FOCUS * (1.0 - 1.0 / 1.333) * sqrt(f32(WATER_DETAIL_COUNT) * 0.5)); + var detail = WATER_DETAIL; + for (var j = 0; j < WATER_DETAIL_COUNT; j++) { + let r = detail[j]; + let k = 2.0 * WATER_PI / (scale * r.y); + let d = vec2(cos(r.x + angle), sin(r.x + angle)); + waterSlopeTerm(slope, d, k, steepness * r.z / k, k * dot(d, xz) - sqrt(WATER_GRAVITY * k) * t + r.w); + } + } +`; + +/** + * Water surface (WaterMaterial). + * + * Vertex: the mesh is displaced in world space by up to four Gerstner + * waves (WaterWaves_wgsl), so neighbouring water objects line up, each + * fading out with distance from the camera (surface.x), plus the + * interactive ripples (USE_RIPPLES), whose slope also bends the normal per + * pixel. + * + * Fragment: the fine ripples (WaterWaves_wgsl, detail scale and strength) + * bend the normal per pixel, fading where a pixel spans them. + * + * Fragment (front face, seen from above): + * - refraction: the opaque scene behind (scene color pyramid), shifted by + * how far the waves move the refracted ray's landing point on the + * bottom compared with flat water. With USE_SCENEDEPTH the depth is + * that of the scene behind (SceneLinearDepthPass), and the distortion + * fades out toward anything above the water, whose hidden background + * is missing from the capture; without it the bottom is waterDepth + * below the surface; + * - absorption: Beer-Lambert over the refracted path, + * T = exp(-density * length * (1 - absorptionColor)), with the water's + * own color (underwaterColor) scattered in for what is absorbed, as in + * UnderwaterPass; + * - reflection: environment map weighted by Schlick fresnel; + * - specular: Blinn-Phong highlight of the first directional light, + * weighted by Schlick fresnel. + * + * Fragment (back face, seen from below): inside Snell's window the scene + * above, refracted from water into air; outside it total internal + * reflection of the scene below, found by marching the reflected ray + * against the scene depth (USE_SCENEDEPTH) and fading into underwaterColor + * with distance. Absorption from the camera to the surface is left to + * UnderwaterPass. + * @internal + */ +export let WaterShader: string = /*wgsl*/ ` + #include "Common_vert" + #include "UnLit_frag" + #include "ClusterLight" + #include "EnvMap_frag" + + struct MaterialUniform { + absorptionColor: vec4, + underwaterColor: vec4, + waveA: vec4, + waveB: vec4, + waveC: vec4, + waveD: vec4, + waveE: vec4, + waveF: vec4, + waveG: vec4, + waveH: vec4, + rippleX: vec4, + rippleZ: vec4, + rippleBounds: vec4, + // x = distance from the camera, in wavelengths, at which a wave has faded out (0 = never), + // y = undisturbed surface height, z = detail scale, w = detail strength + surface: vec4, + // x = foam intensity, y = reflection roughness, z = subsurface intensity, + // w = clarity of the surface seen from below + look: vec4, + // FFT cascades: patch sizes (xyz), typical crest height (w) + fftPatch: vec4, + density: f32, + refractionStrength: f32, + waterDepth: f32, + specularPower: f32, + waveTime: f32, + fresnelClamp: f32, + specularIntensity: f32, + reflectionIntensity: f32, + }; + + @group(2) @binding(0) + var materialUniform: MaterialUniform; + + @group(1) @binding(auto) + var sceneColorPyramidSampler: sampler; + @group(1) @binding(auto) + var sceneColorPyramid: texture_2d; + + #if USE_SCENEDEPTH + // Linear view depth of the opaque scene (SceneLinearDepthPass), read with textureLoad. + @group(1) @binding(auto) + var sceneLinearDepth: texture_2d; + #endif + + #if USE_FFT + // FFT wave cascades (WaterFFT), each tiled every fftPatch metres: displacement (x, y, z, + // dDx/dz) and slope (dDy/dx, dDy/dz, dDx/dx, dDz/dz); foam over the first patch. + @group(1) @binding(auto) + var fftDisplacement0Sampler: sampler; + @group(1) @binding(auto) + var fftDisplacement0: texture_2d; + @group(1) @binding(auto) + var fftDisplacement1: texture_2d; + @group(1) @binding(auto) + var fftDisplacement2: texture_2d; + @group(1) @binding(auto) + var fftSlope0: texture_2d; + @group(1) @binding(auto) + var fftSlope1: texture_2d; + @group(1) @binding(auto) + var fftSlope2: texture_2d; + @group(1) @binding(auto) + var fftFoam: texture_2d; + + // Mip level of a cascade that keeps the waves the mesh resolves at this distance: down to + // distance / surface.x wavelengths long, against two texels per wave at level 0. + fn fftMeshLod(texel: f32, distance: f32) -> f32 { + let perWave = materialUniform.surface.x; + if (perWave <= 0.0) { + return 0.0; + } + return clamp(log2(distance / perWave / (2.0 * texel)), 0.0, f32(${WATER_FFT_MIPS - 1})); + } + + // Displacement of the undisplaced world point xz by the cascades, without the waves too + // short for the mesh at this distance; the long swells stay however far. + fn fftDisplacement(xz: vec2, distance: f32) -> vec3 { + let p = materialUniform.fftPatch; + let texel = p.xyz / f32(${WATER_FFT_SIZE}); + return textureSampleLevel(fftDisplacement0, fftDisplacement0Sampler, xz / p.x, fftMeshLod(texel.x, distance)).xyz + + textureSampleLevel(fftDisplacement1, fftDisplacement0Sampler, xz / p.y, fftMeshLod(texel.y, distance)).xyz + + textureSampleLevel(fftDisplacement2, fftDisplacement0Sampler, xz / p.z, fftMeshLod(texel.z, distance)).xyz; + } + + // Height gradient of the cascades at the undisplaced point xz, at the mip level matching + // the pixel. What the coarser levels average away comes back as roughness (z). + fn fftSlope(xz: vec2, footprint: f32) -> vec3 { + let p = materialUniform.fftPatch; + let texel = p.xyz / f32(${WATER_FFT_SIZE}); + let lod = clamp(log2(vec3(footprint) / texel), vec3(0.0), vec3(f32(${WATER_FFT_MIPS - 1}))); + let g = textureSampleLevel(fftSlope0, fftDisplacement0Sampler, xz / p.x, lod.x).xy + + textureSampleLevel(fftSlope1, fftDisplacement0Sampler, xz / p.y, lod.y).xy + + textureSampleLevel(fftSlope2, fftDisplacement0Sampler, xz / p.z, lod.z).xy; + return vec3(g, min(lod.y, 1.0) * 0.3 + min(lod.z, 1.0) * 0.6); + } + + // Foam left by the whitecaps at the undisplaced point xz. + fn fftFoamAt(xz: vec2) -> f32 { + return textureSampleLevel(fftFoam, fftDisplacement0Sampler, xz / materialUniform.fftPatch.x, 0.0).r; + } + #endif + + #if USE_FOAM_TEXTURE + // Tileable foam (r): revealed above a threshold that falls as the coverage rises. + @group(1) @binding(auto) + var foamTextureSampler: sampler; + @group(1) @binding(auto) + var foamTexture: texture_2d; + #endif + + #if USE_RIPPLES + // Interactive ripples (WaterRipples): r = height, over the water's local xz bounds. + @group(1) @binding(auto) + var rippleMap: texture_2d; + + // Ripple grid texel coordinates of world xz. + fn rippleCoord(xz: vec2) -> vec2 { + let local = vec2( + dot(materialUniform.rippleX.xy, xz) + materialUniform.rippleX.z, + dot(materialUniform.rippleZ.xy, xz) + materialUniform.rippleZ.z); + let b = materialUniform.rippleBounds; + return (local - b.xy) / (b.zw - b.xy) * vec2(textureDimensions(rippleMap)) - 0.5; + } + + fn rippleTexel(c: vec2) -> f32 { + let size = vec2(textureDimensions(rippleMap)); + return textureLoad(rippleMap, clamp(c, vec2(0), size - 1), 0).r; + } + + // Bilinear height at grid coordinates; none off the grid. + fn rippleHeight(coord: vec2) -> f32 { + let size = vec2(textureDimensions(rippleMap)); + if (any(coord < vec2(-0.5)) || any(coord > size - 0.5)) { + return 0.0; + } + let c = vec2(floor(coord)); + let f = coord - floor(coord); + let top = mix(rippleTexel(c), rippleTexel(c + vec2(1, 0)), f.x); + let bottom = mix(rippleTexel(c + vec2(0, 1)), rippleTexel(c + vec2(1, 1)), f.x); + return mix(top, bottom, f.y); + } + + // World-space height gradient (d/dx, d/dz) of the ripples at world xz. + fn rippleGradient(xz: vec2) -> vec2 { + let coord = rippleCoord(xz); + let b = materialUniform.rippleBounds; + let cell = (b.zw - b.xy) / vec2(textureDimensions(rippleMap)); + let local = vec2( + rippleHeight(coord + vec2(1.0, 0.0)) - rippleHeight(coord - vec2(1.0, 0.0)), + rippleHeight(coord + vec2(0.0, 1.0)) - rippleHeight(coord - vec2(0.0, 1.0))) / (2.0 * cell); + return vec2( + local.x * materialUniform.rippleX.x + local.y * materialUniform.rippleZ.x, + local.x * materialUniform.rippleX.y + local.y * materialUniform.rippleZ.y); + } + #endif + + ${WaterWaves_wgsl} + + const WATER_IOR: f32 = 1.333; + const WATER_F0: f32 = 0.02; + // Far enough that projecting a point along a ray gives the ray's direction on screen. + const WATER_FAR_SAMPLE: f32 = 1000.0; + // Reflection march below the surface: steps, and how far it reaches in world units. + const WATER_MARCH_STEPS: i32 = 24; + const WATER_MARCH_DISTANCE: f32 = 40.0; + // Steps for finding objects above the water along a refraction offset. + const WATER_REFRACT_STEPS: i32 = 8; + // How much the scattered water color follows the light entering the surface: at most this + // much brighter or darker for facing toward or away from the sun, and for the crests. Light + // inside deep water is diffused, so the surface's orientation shows only gently. + const WATER_SCATTER_FACING: f32 = 0.3; + const WATER_SCATTER_CREST: f32 = 0.2; + // Foam: where the waves pinch the surface (Jacobian of the horizontal displacement) below + // the first value it starts, below the second it covers the crest. + const WATER_FOAM_START: f32 = 0.8; + const WATER_FOAM_FULL: f32 = 0.5; + // Foam texture: metres per tile at its two scales, and how deep under the surface the + // bubble layer is seen. + const WATER_FOAM_TILE: f32 = 3.0; + const WATER_FOAM_TILE_LARGE: f32 = 8.5; + const WATER_FOAM_BUBBLE_DEPTH: f32 = 0.25; + const WATER_FOAM_TEXELS: f32 = 512.0; + // Wave height at which the crests let the full subsurface glow through, and its strength. + const WATER_SSS_HEIGHT: f32 = 1.0; + const WATER_SSS: f32 = 2.0; + + // Value noise in [0, 1]. + fn waterHash(p: vec2) -> f32 { + return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); + } + fn waterNoise(p: vec2) -> f32 { + let i = floor(p); + let f = p - i; + let u = f * f * (3.0 - 2.0 * f); + return mix(mix(waterHash(i), waterHash(i + vec2(1.0, 0.0)), u.x), + mix(waterHash(i + vec2(0.0, 1.0)), waterHash(i + vec2(1.0, 1.0)), u.x), u.y); + } + + // A wave with its steepness faded out from half surface.x wavelengths away from the camera to surface.x. + fn fadeWave(wave: vec4, distance: f32) -> vec4 { + let far = materialUniform.surface.x * wave.w; + if (far <= 0.0) { + return wave; + } + return vec4(wave.xy, wave.z * (1.0 - smoothstep(0.5 * far, far, distance)), wave.w); + } + + fn vert(inputData: VertexAttributes) -> VertexOutput { + ORI_Vert(inputData); + var worldPos = ORI_VertexOut.varying_WPos.xyz; + let p = worldPos.xz; + let t = materialUniform.waveTime; + var tangent = vec3(1.0, 0.0, 0.0); + var binormal = vec3(0.0, 0.0, 1.0); + // Waves shorter than the mesh or a pixel resolves would alias; they fade with distance. + let distance = length(worldPos - globalUniform.CameraPos.xyz); + let m = materialUniform; + let waves = array, ${WATER_MAX_WAVES}>( + fadeWave(m.waveA, distance), fadeWave(m.waveB, distance), fadeWave(m.waveC, distance), fadeWave(m.waveD, distance), + fadeWave(m.waveE, distance), fadeWave(m.waveF, distance), fadeWave(m.waveG, distance), fadeWave(m.waveH, distance)); + worldPos += waterWaves(waves, p, t, &tangent, &binormal); + #if USE_FFT + worldPos += fftDisplacement(p, distance); + #endif + // How much the waves pinch the surface here: 1 when flat, toward 0 at sharp crests. + let jacobian = tangent.x * binormal.z - tangent.z * binormal.x; + #if USE_RIPPLES + worldPos.y += rippleHeight(rippleCoord(p)); + #endif + + let viewPos = ORI_MATRIX_V * vec4(worldPos, 1.0); + var clipPos = ORI_MATRIX_P * viewPos; + #if USE_LOGDEPTH + clipPos.z = log2Depth(clipPos.w, globalUniform.near, globalUniform.far); + #endif + ORI_VertexOut.varying_WPos = vec4(worldPos, ORI_VertexOut.varying_WPos.w); + ORI_VertexOut.varying_WNormal = normalize(cross(binormal, tangent)); + ORI_VertexOut.varying_ViewPos = viewPos; + ORI_VertexOut.varying_UV1 = vec2(jacobian, 0.0); + // The undisplaced point, where the fragment looks up the FFT cascades. + ORI_VertexOut.varying_UV0 = p; + ORI_VertexOut.varying_Clip = clipPos; + ORI_VertexOut.member = clipPos; + return ORI_VertexOut; + } + + // Direction toward the first directional light (light data holds the way its rays travel), and its radiance. + fn sunLight(color: ptr>) -> vec3 { + let count = i32(clustersUniform.numLights); + for (var i = 0; i < count; i++) { + let light = lightBuffer[i]; + if (light.lightType == DirectLightType) { + *color = light.lightColor * light.intensity; + return -normalize(light.direction); + } + } + *color = vec3(0.0); + return vec3(0.0, 1.0, 0.0); + } + + fn screenUV(worldPos: vec3) -> vec2 { + let clip = globalUniform.projMat * globalUniform.viewMat * vec4(worldPos, 1.0); + let ndc = clip.xy / max(clip.w, 1e-4); + return clamp(vec2(ndc.x * 0.5 + 0.5, ndc.y * -0.5 + 0.5), vec2(0.002), vec2(0.998)); + } + + #if USE_SCENEDEPTH + fn sceneViewZ(uv: vec2) -> f32 { + let dim = vec2(textureDimensions(sceneLinearDepth)); + return textureLoad(sceneLinearDepth, clamp(vec2(uv * vec2(dim)), vec2(0), dim - 1), 0).r; + } + + // World position of the opaque scene at uv. + fn sceneWorldPos(uv: vec2) -> vec3 { + let ndc = vec2(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0); + let farH = globalUniform.projMatInv * vec4(ndc, 1.0, 1.0); + let ray = farH.xyz / farH.w; + let viewPos = ray * (sceneViewZ(uv) / ray.z); + return (globalUniform.cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; + } + + // Only scene points below the surface can be seen through it. + fn seenThrough(uv: vec2, surfaceY: f32) -> bool { + return sceneWorldPos(uv).y < surfaceY; + } + + // Screen uv and view depth of a world point. + fn projectPoint(worldPos: vec3) -> vec3 { + let viewPos = globalUniform.viewMat * vec4(worldPos, 1.0); + let clip = globalUniform.projMat * viewPos; + let ndc = clip.xy / max(clip.w, 1e-4); + return vec3(ndc.x * 0.5 + 0.5, ndc.y * -0.5 + 0.5, viewPos.z); + } + #endif + + // The scene below reflected by the underside along R, absorbed into underwaterColor over the path. + fn reflectedBelow(worldPos: vec3, R: vec3) -> vec3 { + let deep = materialUniform.underwaterColor.rgb; + #if USE_SCENEDEPTH + var t0 = 0.0; + var t1 = -1.0; + for (var i = 1; i <= WATER_MARCH_STEPS; i++) { + let f = f32(i) / f32(WATER_MARCH_STEPS); + let t = WATER_MARCH_DISTANCE * f * f; + let s = projectPoint(worldPos + R * t); + if (s.z <= 0.0 || any(s.xy < vec2(0.0)) || any(s.xy > vec2(1.0))) { + break; + } + let behind = s.z - sceneViewZ(s.xy); + // Behind the depth by more than the step: the ray passed behind a thin object. + if (behind >= 0.0 && behind < max(1.0, (t - t0) * 2.0)) { + t1 = t; + break; + } + t0 = t; + } + if (t1 < 0.0) { + return deep; + } + for (var i = 0; i < 5; i++) { + let t = 0.5 * (t0 + t1); + let s = projectPoint(worldPos + R * t); + if (s.z >= sceneViewZ(s.xy)) { + t1 = t; + } else { + t0 = t; + } + } + let uv = projectPoint(worldPos + R * t1).xy; + let hit = textureSampleLevel(sceneColorPyramid, sceneColorPyramidSampler, uv, 0.0).rgb; + let transmittance = exp(-materialUniform.density * t1 * (vec3(1.0) - materialUniform.absorptionColor.rgb)); + let edge = min(min(uv.x, 1.0 - uv.x), min(uv.y, 1.0 - uv.y)); + let fade = smoothstep(0.0, 0.05, edge); + return mix(deep, hit * transmittance + deep * (vec3(1.0) - transmittance), fade); + #else + return deep; + #endif + } + + // The surface seen from below: Snell's window, total internal reflection outside it. + // Clarity above 0 eases the index toward 1 and lowers the reflectance: a wider window + // and less of the surface given over to the mirror of the water below. + fn fromBelow(worldPos: vec3, V: vec3, N: vec3) -> vec3 { + let clarity = clamp(materialUniform.look.w, 0.0, 1.0); + let reflected = reflectedBelow(worldPos, reflect(-V, N)); + let refr = refract(-V, N, mix(WATER_IOR, 1.02, clarity)); + if (dot(refr, refr) < 1e-6) { + return reflected; + } + let above = textureSampleLevel(sceneColorPyramid, sceneColorPyramidSampler, + screenUV(worldPos + refr * WATER_FAR_SAMPLE), 0.0).rgb; + // Fresnel on the angle in air: reflectance rises to 1 at the window's edge. + let cosT = clamp(dot(refr, -N), 0.0, 1.0); + let fresnel = (WATER_F0 + (1.0 - WATER_F0) * pow(1.0 - cosT, 5.0)) * (1.0 - 0.6 * clarity); + return mix(above, reflected, fresnel); + } + + // Sum of the wave amplitudes, the highest a crest rises. + fn waveAmplitude() -> f32 { + let m = materialUniform; + return (m.waveA.z * m.waveA.w + m.waveB.z * m.waveB.w + m.waveC.z * m.waveC.w + m.waveD.z * m.waveD.w + + m.waveE.z * m.waveE.w + m.waveF.z * m.waveF.w + m.waveG.z * m.waveG.w + m.waveH.z * m.waveH.w) / (2.0 * WATER_PI); + } + + fn frag() { + let worldPos = ORI_VertexVarying.vWorldPos.xyz; + let V = normalize(globalUniform.CameraPos.xyz - worldPos); + var N = normalize(ORI_VertexVarying.vWorldNormal); + // Fine ripples, per pixel; they fade out where a pixel spans a good part of the shortest one. + let footprint = length(fwidth(worldPos.xz)); + let detailScale = materialUniform.surface.z; + let resolved = 1.0 - smoothstep(0.1, 0.4, footprint / max(detailScale * WATER_DETAIL_SHORTEST, 1e-4)); + var fftRoughness = 0.0; + #if USE_FFT + let fftGrad = fftSlope(ORI_VertexVarying.fragUV0, footprint); + N = normalize(N - vec3(fftGrad.x, 0.0, fftGrad.y)); + fftRoughness = fftGrad.z; + #endif + if (materialUniform.surface.w * resolved > 0.0) { + var detail = WaterSlope(vec2(0.0), vec3(0.0)); + waterDetail(&detail, worldPos.xz, materialUniform.waveTime, detailScale, 0.0); + // A longer, turned octave at half the slope breaks up the pattern of the first. + var coarse = WaterSlope(vec2(0.0), vec3(0.0)); + waterDetail(&coarse, worldPos.xz, materialUniform.waveTime, detailScale * WATER_DETAIL_OCTAVE, 1.1); + detail.grad += coarse.grad * 0.5; + N = normalize(N - vec3(detail.grad.x, 0.0, detail.grad.y) * materialUniform.surface.w * resolved); + } + #if USE_RIPPLES + // Per pixel: the ripples are finer than the mesh. + let rippleSlope = rippleGradient(worldPos.xz); + N = normalize(N - vec3(rippleSlope.x, 0.0, rippleSlope.y)); + #endif + if (!ORI_VertexVarying.face) { + ORI_ShadingInput.BaseColor = vec4(fromBelow(worldPos, V, -N), 1.0); + UnLit(); + return; + } + + let refr = refract(-V, N, 1.0 / WATER_IOR); + let directUV = ORI_VertexVarying.fragCoord.xy / vec2(globalUniform.windowWidth, globalUniform.windowHeight); + // Path of the refracted ray down to the bottom: the depth of the scene behind, below this point. + #if USE_SCENEDEPTH + let depth = max(worldPos.y - sceneWorldPos(directUV).y, 0.0); + #else + let depth = materialUniform.waterDepth; + #endif + let travel = depth / max(-refr.y, 0.2); + // Only the distortion the waves add: where the refracted ray lands relative to where it + // would through flat water. The flat-water shift is left out, so the bottom keeps its + // place on screen and objects above the water hide almost nothing it needs. + let refrFlat = refract(-V, vec3(0.0, 1.0, 0.0), 1.0 / WATER_IOR); + let bottom = screenUV(worldPos + refr * travel); + let bottomFlat = screenUV(worldPos + refrFlat * (depth / max(-refrFlat.y, 0.2))); + let offset = (bottom - bottomFlat) * materialUniform.refractionStrength; + var uv = clamp(directUV + offset, vec2(0.002), vec2(0.998)); + #if USE_SCENEDEPTH + // The captured scene also holds what is above the water (e.g. a floating object's top), + // and what it hides is missing. Find where along twice the offset the first such sample + // is, and use half that distance: the distortion fades to zero at the object's edge, so + // the image stays continuous and never samples the edge itself. + if (!seenThrough(directUV + offset, worldPos.y) || !seenThrough(directUV + offset * 2.0, worldPos.y)) { + var lo = 0.0; + var hi = 2.0; + for (var i = 1; i <= WATER_REFRACT_STEPS; i++) { + let s = 2.0 * f32(i) / f32(WATER_REFRACT_STEPS); + if (!seenThrough(directUV + offset * s, worldPos.y)) { + hi = s; + break; + } + lo = s; + } + for (var i = 0; i < 3; i++) { + let s = 0.5 * (lo + hi); + if (seenThrough(directUV + offset * s, worldPos.y)) { + lo = s; + } else { + hi = s; + } + } + uv = directUV + offset * (0.5 * lo); + } + #endif + var sunColor: vec3; + let L = sunLight(&sunColor); + + let transmitted = textureSampleLevel(sceneColorPyramid, sceneColorPyramidSampler, uv, 0.0).rgb; + let transmittance = exp(-materialUniform.density * travel * (vec3(1.0) - materialUniform.absorptionColor.rgb)); + // What the water absorbs is replaced by its own color scattered toward the eye: brighter + // where the surface takes in more sunlight than flat water would, and in the thin crests. + let facing = clamp((dot(N, L) - L.y) * 2.5, -1.0, 1.0); + let crest = clamp((worldPos.y - materialUniform.surface.y) / max(waveAmplitude() + materialUniform.fftPatch.w, 1e-3), -1.0, 1.0); + let scatter = materialUniform.underwaterColor.rgb + * (1.0 + WATER_SCATTER_FACING * facing) * (1.0 + WATER_SCATTER_CREST * crest); + let refraction = transmitted * transmittance + scatter * (vec3(1.0) - transmittance); + + // A ray reflected below the horizon would meet the next wave, not the dark lower sky; + // turned back up it finds sky about as bright as that wave's face. + let R0 = reflect(-V, N); + let R = vec3(R0.x, abs(R0.y), R0.z); + // Blurred by the roughness finer than the ripples, plus the ripples a pixel averages + // where they fade, so distant reflections soften instead of breaking into patches. + let maxLod = f32(textureNumLevels(prefilterMap)); + let roughness = clamp(materialUniform.look.y + (1.0 - resolved) * materialUniform.surface.w * 0.4 + fftRoughness, 0.0, 1.0); + let reflection = textureSampleLevel(prefilterMap, prefilterMapSampler, R, roughness * maxLod).rgb + * globalUniform.skyExposure * materialUniform.reflectionIntensity; + let cosV = clamp(dot(N, V), 0.0, 1.0); + let fresnel = min(WATER_F0 + (1.0 - WATER_F0) * pow(1.0 - cosV, 5.0), materialUniform.fresnelClamp); + + let H = normalize(L + V); + // Weighted by the water's reflectance toward the sun, a few percent unless grazing. + let sunFresnel = WATER_F0 + (1.0 - WATER_F0) * pow(1.0 - clamp(dot(H, V), 0.0, 1.0), 5.0); + let specular = pow(max(dot(N, H), 0.0), materialUniform.specularPower) + * sunColor * materialUniform.specularIntensity * sunFresnel * step(0.0, dot(N, L)); + + // Sunlight through the thin crests toward the eye when looking toward the sun, tinted by + // the water; only waves of some height let it through. + let toward = pow(clamp(dot(-V, L), 0.0, 1.0), 3.0); + let thin = max(crest, 0.0) * clamp((waveAmplitude() + materialUniform.fftPatch.w) / WATER_SSS_HEIGHT, 0.0, 1.0); + let subsurface = sunColor * materialUniform.absorptionColor.rgb * toward * thin * materialUniform.look.z * WATER_SSS; + + var color = mix(refraction + subsurface, reflection, fresnel) + specular; + + // Whitecaps where the waves pinch the surface, in patches that grow as it pinches harder. + var pinch = smoothstep(WATER_FOAM_START, WATER_FOAM_FULL, ORI_VertexVarying.fragUV1.x); + #if USE_FFT + pinch = max(pinch, fftFoamAt(ORI_VertexVarying.fragUV0)); + #endif + #if USE_FOAM_TEXTURE + if (pinch > 0.0 && materialUniform.look.x > 0.0) { + let coverage = clamp(pinch * materialUniform.look.x, 0.0, 1.0); + let drift = vec2(0.04, 0.03) * materialUniform.waveTime; + let lod = log2(max(footprint * WATER_FOAM_TEXELS / WATER_FOAM_TILE, 1.0)); + let turned = vec2(0.8 * worldPos.x - 0.6 * worldPos.z, 0.6 * worldPos.x + 0.8 * worldPos.z); + let sky = textureSampleLevel(prefilterMap, prefilterMapSampler, vec3(0.0, 1.0, 0.0), maxLod).rgb + * globalUniform.skyExposure; + let lit = sky + sunColor * (0.3 + 0.7 * max(dot(N, L), 0.0)) * 0.35; + // Bubbles a little under the surface, along the view into the water: blurred, tinted. + let under = worldPos.xz + refr.xz / max(-refr.y, 0.3) * WATER_FOAM_BUBBLE_DEPTH; + let bubbles = textureSampleLevel(foamTexture, foamTextureSampler, under / WATER_FOAM_TILE + drift, lod + 2.0).r; + let below = smoothstep(1.0 - coverage, 1.4 - coverage, bubbles); + color = mix(color, lit * mix(materialUniform.absorptionColor.rgb, vec3(1.0), 0.5), below * 0.5); + // The foam on the surface: two scales of the texture, the larger one turned. + let fine = textureSampleLevel(foamTexture, foamTextureSampler, worldPos.xz / WATER_FOAM_TILE + drift, lod).r; + let coarse = textureSampleLevel(foamTexture, foamTextureSampler, turned / WATER_FOAM_TILE_LARGE - drift, + lod - log2(WATER_FOAM_TILE_LARGE / WATER_FOAM_TILE)).r; + let surfaceFoam = smoothstep(1.0 - coverage, 1.25 - coverage, 0.6 * fine + 0.6 * coarse); + color = mix(color, lit * 0.85, surfaceFoam); + } + #else + if (pinch > 0.0 && materialUniform.look.x > 0.0) { + let drift = vec2(0.3, 0.2) * materialUniform.waveTime; + let n = 0.6 * waterNoise(worldPos.xz * 0.9 + drift) + 0.4 * waterNoise(worldPos.xz * 3.1 - drift); + let foam = smoothstep(0.5, 0.65, 0.5 * n + 0.6 * pinch) * materialUniform.look.x; + let sky = textureSampleLevel(prefilterMap, prefilterMapSampler, vec3(0.0, 1.0, 0.0), maxLod).rgb + * globalUniform.skyExposure; + let foamColor = vec3(0.9) * (sky + sunColor * max(dot(N, L), 0.0) * 0.3); + color = mix(color, foamColor, clamp(foam, 0.0, 1.0)); + } + #endif + ORI_ShadingInput.BaseColor = vec4(color, 1.0); + UnLit(); + } +`; diff --git a/src/assets/shader/materials/program/Iridescence_frag.ts b/src/assets/shader/materials/program/Iridescence_frag.ts new file mode 100644 index 000000000..ec89eba3a --- /dev/null +++ b/src/assets/shader/materials/program/Iridescence_frag.ts @@ -0,0 +1,115 @@ +/** + * KHR_materials_iridescence — thin-film interference (soap bubbles, oil + * slicks, beetle shells, anodized metal). Port of Belcour & Barla 2017 as + * used by the Khronos sample viewer and three.js: the film modifies the + * surface Fresnel as a function of view angle, film IOR and thickness. + * + * `materialUniform.iridescence` = (factor, film IOR, film thickness in nm, unused). + * `IridescenceUtil` mirrors this file on the CPU. + * @internal + */ +export let Iridescence_frag: string = /*wgsl*/ ` + #if USE_IRIDESCENCE + fn iriPow2(x: f32) -> f32 { return x * x; } + fn iriPow2v(x: vec3) -> vec3 { return x * x; } + + fn iriSchlickF(f0: f32, cosTheta: f32) -> f32 { + let x = clamp(1.0 - cosTheta, 0.0, 1.0); + let x5 = x * x * x * x * x; + return f0 + (1.0 - f0) * x5; + } + fn iriSchlickV(f0: vec3, cosTheta: f32) -> vec3 { + let x = clamp(1.0 - cosTheta, 0.0, 1.0); + let x5 = x * x * x * x * x; + return f0 + (vec3(1.0) - f0) * x5; + } + + fn iriFresnel0ToIor(f0: vec3) -> vec3 { + let s = sqrt(f0); + return (vec3(1.0) + s) / (vec3(1.0) - s); + } + fn iriIorToFresnel0V(transmittedIor: vec3, incidentIor: f32) -> vec3 { + return iriPow2v((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor))); + } + fn iriIorToFresnel0(transmittedIor: f32, incidentIor: f32) -> f32 { + return iriPow2((transmittedIor - incidentIor) / (transmittedIor + incidentIor)); + } + + // Spectral sensitivity of the CIE XYZ matching functions under a phase shift, in Rec.709. + fn iriEvalSensitivity(OPD: f32, shift: vec3) -> vec3 { + let TWO_PI = 6.28318530718; + let phase = TWO_PI * OPD * 1.0e-9; + let val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + let pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + let vr = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + var xyz = val * sqrt(TWO_PI * vr) * cos(pos * phase + shift) * exp(-iriPow2(phase) * vr); + xyz.x = xyz.x + 9.7470e-14 * sqrt(TWO_PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift.x) * exp(-4.5282e+09 * iriPow2(phase)); + xyz = xyz / 1.0685e-7; + let XYZ_TO_REC709 = mat3x3( + vec3(3.2404542, -0.9692660, 0.0556434), + vec3(-1.5371385, 1.8760108, -0.2040259), + vec3(-0.4985314, 0.0415560, 1.0572252)); + return XYZ_TO_REC709 * xyz; + } + + /// Fresnel reflectance of base + thin film at the given view angle. + fn evalIridescence(outsideIOR: f32, eta2: f32, cosTheta1: f32, thinFilmThickness: f32, baseF0: vec3) -> vec3 { + let PI_ = 3.14159265359; + // Force the film IOR toward the outside IOR as the film vanishes. + let iridescenceIOR = mix(outsideIOR, eta2, smoothstep(0.0, 0.03, thinFilmThickness)); + let sinTheta2Sq = iriPow2(outsideIOR / iridescenceIOR) * (1.0 - iriPow2(cosTheta1)); + let cosTheta2Sq = 1.0 - sinTheta2Sq; + if (cosTheta2Sq < 0.0) { + return vec3(1.0); // total internal reflection + } + let cosTheta2 = sqrt(cosTheta2Sq); + + // First interface (outside → film) + let R0 = iriIorToFresnel0(iridescenceIOR, outsideIOR); + let R12 = iriSchlickF(R0, cosTheta1); + let T121 = 1.0 - R12; + var phi12 = 0.0; + if (iridescenceIOR < outsideIOR) { phi12 = PI_; } + let phi21 = PI_ - phi12; + + // Second interface (film → base) + let baseIOR = iriFresnel0ToIor(clamp(baseF0, vec3(0.0), vec3(0.9999))); + let R1 = iriIorToFresnel0V(baseIOR, iridescenceIOR); + let R23 = iriSchlickV(R1, cosTheta2); + var phi23 = vec3(0.0); + if (baseIOR.x < iridescenceIOR) { phi23.x = PI_; } + if (baseIOR.y < iridescenceIOR) { phi23.y = PI_; } + if (baseIOR.z < iridescenceIOR) { phi23.z = PI_; } + + // Optical path difference and total phase shift + let OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + let phi = vec3(phi21) + phi23; + + // Compound terms + let R123 = clamp(R12 * R23, vec3(1e-5), vec3(0.9999)); + let r123 = sqrt(R123); + let Rs = iriPow2(T121) * R23 / (vec3(1.0) - R123); + + // Reflectance term for m = 0 (DC term amplitude) + var I = vec3(R12) + Rs; + // Reflectance terms for m = 1, 2 (pairs of diracs) + var Cm = Rs - vec3(T121); + Cm = Cm * r123; + I = I + Cm * 2.0 * iriEvalSensitivity(1.0 * OPD, 1.0 * phi); + Cm = Cm * r123; + I = I + Cm * 2.0 * iriEvalSensitivity(2.0 * OPD, 2.0 * phi); + return max(I, vec3(0.0)); + } + + /// F0 with the film applied: the angle-dependent film Fresnel converted + /// back to an equivalent Schlick F0, blended in by the iridescence factor. + fn applyIridescenceF0(baseF0: vec3, NoV: f32) -> vec3 { + let factor = clamp(materialUniform.iridescence.x, 0.0, 1.0); + let fresnel = evalIridescence(1.0, materialUniform.iridescence.y, NoV, materialUniform.iridescence.z, baseF0); + let x = clamp(1.0 - NoV, 0.0, 1.0); + let x5 = clamp(x * x * x * x * x, 0.0, 0.9999); + let filmF0 = clamp((fresnel - vec3(x5)) / (1.0 - x5), vec3(0.0), vec3(1.0)); + return mix(baseF0, filmF0, factor); + } + #endif +`; diff --git a/src/assets/shader/materials/program/Sheen_frag.ts b/src/assets/shader/materials/program/Sheen_frag.ts new file mode 100644 index 000000000..fe9492e62 --- /dev/null +++ b/src/assets/shader/materials/program/Sheen_frag.ts @@ -0,0 +1,113 @@ +/** + * KHR_materials_sheen — a cloth-like retro-reflective lobe layered over the + * base BRDF. Charlie distribution + Neubelt visibility for punctual lights, + * an analytic DG fit for the environment term, and the same energy + * compensation three.js / the Khronos sample viewer use (base layer scaled by + * `1 - 0.157·max(sheenColor)`). + * + * `materialUniform.sheenColor.rgb` = sheen tint (linear), `.a` = sheen roughness. + * @internal + */ +export let Sheen_frag: string = /*wgsl*/ ` + #if USE_SHEEN + // Estevez & Kulla "Production Friendly Microfacet Sheen BRDF". + fn sheenD_Charlie(roughness: f32, NoH: f32) -> f32 { + let alpha = max(roughness * roughness, 0.0049); + let invAlpha = 1.0 / alpha; + let cos2h = NoH * NoH; + let sin2h = max(1.0 - cos2h, 0.0078125); + return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * 3.14159265); + } + + // Neubelt & Pettineo visibility term. + fn sheenV_Neubelt(NoV: f32, NoL: f32) -> f32 { + return clamp(1.0 / (4.0 * (NoL + NoV - NoL * NoV)), 0.0, 1.0); + } + + fn sheenBRDF(L: vec3) -> f32 { + let N = fragData.N; + let V = fragData.V; + let H = normalize(L + V); + let NoL = clamp(dot(N, L), 0.0, 1.0); + let NoV = clamp(dot(N, V), 0.0001, 1.0); + let NoH = clamp(dot(N, H), 0.0, 1.0); + return sheenD_Charlie(materialUniform.sheenColor.a, NoH) * sheenV_Neubelt(NoV, NoL) * NoL; + } + + // Analytic fit of the directional albedo of the sheen lobe + // (https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view). + fn sheenIBL_DG(NoV: f32, roughness: f32) -> f32 { + let r2 = roughness * roughness; + var a = -8.48 * r2 + 14.3 * roughness - 9.95; + var b = 1.97 * r2 - 3.27 * roughness + 0.72; + var extra = 0.1 * (roughness - 0.25); + if (roughness < 0.25) { + a = -339.2 * r2 + 161.4 * roughness - 25.9; + b = 44.0 * r2 - 23.7 * roughness + 3.26; + extra = 0.0; + } + let DG = exp(a * NoV + b) + extra; + return clamp(DG / 3.14159265, 0.0, 1.0); + } + + fn sheenSpotAtt(WP: vec3, light: LightData) -> f32 { + var dir = light.position.xyz - WP; + let dist = length(dir); + if (dist != 0.0) { dir *= 1.0 / dist; } + var atten = 0.0; + if (abs(dist) < light.range * 2.0) { + let angle = acos(dot(-dir, normalize(light.direction))); + atten = 1.0 - smoothstep(0.0, light.range, dist); + atten *= 1.0 / max(light.radius, 0.001); + if (angle < light.outerCutOff) { + if (angle > light.innerCutOff) { + atten *= 1.0 - smoothstep(light.innerCutOff, light.outerCutOff, angle); + } + } else { + atten = 0.0; + } + atten *= sphere_unit(light.range, light.intensity); + } + return atten; + } + + /// Layer sheen over an already-lit base color. + fn applySheen(base: vec3, start: f32, end: f32) -> vec3 { + let sheenColor = materialUniform.sheenColor.rgb; + let WP = ORI_VertexVarying.vWorldPos.xyz; + var sheen = vec3(0.0); + for (var i: i32 = i32(start); i < i32(end); i += 1) { + let light = getLight(i32(i)); + let lightColor = getHDRColor(light.lightColor.rgb, light.linear); + switch (light.lightType) { + case DirectLightType: { + let L = normalize(-light.direction.xyz); + let shadow = directShadowVisibility[(light.castShadow)]; + sheen += sheenBRDF(L) * lightColor * max(0.0, light.intensity) * shadow; + break; + } + case PointLightType: { + let L = normalize(light.position.xyz - WP); + let shadow = pointShadows[i32(light.castShadow)]; + sheen += sheenBRDF(L) * lightColor * pointAtt(WP, light) * shadow; + break; + } + case SpotLightType: { + let L = normalize(light.position.xyz - WP); + let shadow = pointShadows[i32(light.castShadow)]; + sheen += sheenBRDF(L) * lightColor * sheenSpotAtt(WP, light) * shadow; + break; + } + default: { + break; + } + } + } + // Environment: diffuse irradiance × directional albedo of the lobe. + sheen += fragData.Irradiance * sheenIBL_DG(fragData.NoV, materialUniform.sheenColor.a) * fragData.Ao; + + let energyComp = 1.0 - 0.157 * max(sheenColor.r, max(sheenColor.g, sheenColor.b)); + return base * energyComp + sheenColor * sheen; + } + #endif +`; diff --git a/src/assets/shader/materials/uniforms/PhysicMaterialUniform_frag.ts b/src/assets/shader/materials/uniforms/PhysicMaterialUniform_frag.ts index 5f5e77885..6f516a002 100644 --- a/src/assets/shader/materials/uniforms/PhysicMaterialUniform_frag.ts +++ b/src/assets/shader/materials/uniforms/PhysicMaterialUniform_frag.ts @@ -39,6 +39,9 @@ export let PhysicMaterialUniform_frag = /* wgsl */` attenuationColor: vec4, + sheenColor: vec4, + iridescence: vec4, + baseMapOffsetSize:vec4, normalMapOffsetSize:vec4, emissiveMapOffsetSize:vec4, diff --git a/src/assets/shader/post/LensShader.ts b/src/assets/shader/post/LensShader.ts new file mode 100644 index 000000000..81f15049e --- /dev/null +++ b/src/assets/shader/post/LensShader.ts @@ -0,0 +1,69 @@ +/** + * Vignette + chromatic aberration + film grain in one fullscreen pass. + * `LensUtil` mirrors the vignette / aberration math on the CPU. + * @internal + */ +export let LensShader: string = /*wgsl*/ ` + struct FragmentOutput { + @location(auto) o_Target: vec4 + }; + + @group(1) @binding(0) + var baseMapSampler: sampler; + @group(1) @binding(1) + var baseMap: texture_2d; + + struct MaterialUniform { + vignetteColor: vec4, + // x = vignette intensity, y = smoothness, z = roundness, w = aspect (w/h) + vignetteParams: vec4, + // x = chromatic aberration, y = grain intensity, z = grain seed (frame), w = unused + lensParams: vec4, + }; + + @group(2) @binding(0) + var materialUniform: MaterialUniform; + + // Dave Hoskins hash13 — cheap, no visible pattern at pixel frequency. + fn lensHash(p3In: vec3) -> f32 { + var p3 = fract(p3In * 0.1031); + p3 = p3 + dot(p3, p3.zyx + 31.32); + return fract((p3.x + p3.y) * p3.z); + } + + @fragment + fn main(@location(auto) fragUV: vec2, @builtin(position) fragCoord: vec4) -> FragmentOutput { + var uv = fragUV; + uv.y = 1.0 - uv.y; + let centered = uv - vec2(0.5); + + // --- chromatic aberration: split R / B along the radius --- + let ca = materialUniform.lensParams.x; + let center = textureSample(baseMap, baseMapSampler, uv); + var rgb = center.rgb; + if (ca > 0.0) { + // ×0.1: intensity 1 ≈ a 5 % UV shift at the middle of the left/right edge. + let offset = centered * dot(centered, centered) * 0.4 * ca; + rgb.r = textureSample(baseMap, baseMapSampler, uv + offset).r; + rgb.b = textureSample(baseMap, baseMapSampler, uv - offset).b; + } + + // --- film grain: multiplicative so it tracks exposure, tiny additive floor for the darks --- + let grain = materialUniform.lensParams.y; + if (grain > 0.0) { + let n = lensHash(vec3(fragCoord.xy, materialUniform.lensParams.z)) - 0.5; + rgb = max(rgb * (1.0 + n * 2.0 * grain) + vec3(n * grain * 0.04), vec3(0.0)); + } + + // --- vignette --- + let vi = materialUniform.vignetteParams.x; + if (vi > 0.0) { + var d = centered * 2.0 * vi; + d.x = d.x * mix(1.0, materialUniform.vignetteParams.w, materialUniform.vignetteParams.z); + let v = pow(clamp(1.0 - dot(d, d), 0.0, 1.0), materialUniform.vignetteParams.y * 5.0 + 0.01); + rgb = mix(materialUniform.vignetteColor.rgb, rgb, v); + } + + return FragmentOutput(vec4(rgb, center.a)); + } +`; diff --git a/src/assets/shader/post/TonemapShader.ts b/src/assets/shader/post/TonemapShader.ts index d5ec941a1..790dcac28 100644 --- a/src/assets/shader/post/TonemapShader.ts +++ b/src/assets/shader/post/TonemapShader.ts @@ -1,6 +1,9 @@ import { ColorUtil } from "../utils/ColorUtil"; /** + * Final tonemap pass. `mode` selects the curve (see `TonemapUtil.MODE_INDEX`; + * keep the two in sync): 0 None, 1 ACES, 2 Reinhard, 3 Uncharted2, 4 AgX, + * 5 Khronos PBR Neutral. `TonemapUtil.apply` is the CPU mirror of this file. * @internal */ export let TonemapShader: string = /*wgsl*/ ` @@ -18,20 +21,107 @@ export let TonemapShader: string = /*wgsl*/ ` struct MaterialUniform { exposure: f32, mode: f32, + whitePoint: f32, + tonemapPad: f32, }; @group(2) @binding(0) var materialUniform: MaterialUniform; + fn tmReinhard(c: vec3, white: f32) -> vec3 { + let w2 = white * white; + return (c * (vec3(1.0) + c / w2)) / (vec3(1.0) + c); + } + + fn tmHable(x: vec3) -> vec3 { + let A = 0.15; let B = 0.50; let C = 0.10; let D = 0.20; let E = 0.02; let F = 0.30; + return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; + } + + fn tmUncharted2(c: vec3) -> vec3 { + let white = tmHable(vec3(11.2)); + return tmHable(c * 2.0) / white; + } + + // AgX base look — Troy Sobotka's AgX as approximated by Benjamin Wrensch, + // same constants as three.js AgXToneMapping / Blender 4 "AgX Base". + fn tmAgxContrast(x: vec3) -> vec3 { + let x2 = x * x; + let x4 = x2 * x2; + return 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; + } + + fn tmAgX(color: vec3) -> vec3 { + let srgbToRec2020 = mat3x3( + vec3(0.6274, 0.0691, 0.0164), + vec3(0.3293, 0.9195, 0.0880), + vec3(0.0433, 0.0113, 0.8956)); + let rec2020ToSrgb = mat3x3( + vec3(1.6605, -0.1246, -0.0182), + vec3(-0.5876, 1.1329, -0.1006), + vec3(-0.0728, -0.0083, 1.1187)); + let inset = mat3x3( + vec3(0.856627153315983, 0.137318972929847, 0.11189821299995), + vec3(0.0951212405381588, 0.761241990602591, 0.0767994186031903), + vec3(0.0482516061458583, 0.101439036467562, 0.811302368396859)); + let outset = mat3x3( + vec3(1.1271005818144368, -0.1413297634984383, -0.14132976349843826), + vec3(-0.11060664309660323, 1.157823702216272, -0.11060664309660294), + vec3(-0.016493938717834573, -0.016493938717834257, 1.2519364065950405)); + let minEv = -12.47393; + let maxEv = 4.026069; + + var c = srgbToRec2020 * color; + c = inset * c; + c = max(c, vec3(1e-10)); + c = log2(c); + c = (c - vec3(minEv)) / (maxEv - minEv); + c = clamp(c, vec3(0.0), vec3(1.0)); + c = tmAgxContrast(c); + c = outset * c; + c = pow(max(c, vec3(0.0)), vec3(2.2)); + c = rec2020ToSrgb * c; + return clamp(c, vec3(0.0), vec3(1.0)); + } + + // Khronos PBR Neutral (https://github.com/KhronosGroup/ToneMapping). + fn tmNeutral(colorIn: vec3) -> vec3 { + let startCompression = 0.8 - 0.04; + let desaturation = 0.15; + var color = colorIn; + let x = min(color.r, min(color.g, color.b)); + var offset = 0.04; + if (x < 0.08) { offset = x - 6.25 * x * x; } + color = color - vec3(offset); + let peak = max(color.r, max(color.g, color.b)); + if (peak < startCompression) { return color; } + let d = 1.0 - startCompression; + let newPeak = 1.0 - d * d / (peak + d - startCompression); + color = color * (newPeak / peak); + let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0); + return mix(color, vec3(newPeak), g); + } + @fragment fn main(@location(auto) fragUV: vec2) -> FragmentOutput { var uv = fragUV; uv.y = 1.0 - uv.y; let raw = textureSample(baseMap, baseMapSampler, uv); - var rgb = raw.rgb * materialUniform.exposure; - if (materialUniform.mode > 0.5) { + // Negative HDR values (can come out of additive posts) are undefined + // for every curve below; clamp once here. + var rgb = max(raw.rgb, vec3(0.0)) * materialUniform.exposure; + let mode = i32(materialUniform.mode + 0.5); + if (mode == 1) { rgb = ACESToneMapping(rgb, 1.0); + } else if (mode == 2) { + rgb = tmReinhard(rgb, max(materialUniform.whitePoint, 1e-3)); + } else if (mode == 3) { + rgb = tmUncharted2(rgb); + } else if (mode == 4) { + rgb = tmAgX(rgb); + } else if (mode == 5) { + rgb = tmNeutral(rgb); } return FragmentOutput(vec4(rgb, raw.a)); } diff --git a/src/components/BillboardComponent.ts b/src/components/BillboardComponent.ts index fdd16aebe..c5248cd1b 100644 --- a/src/components/BillboardComponent.ts +++ b/src/components/BillboardComponent.ts @@ -54,10 +54,24 @@ export class BillboardComponent extends ComponentBase { if (this.type == BillboardType.BillboardXYZ) { } else if (this.type == BillboardType.BillboardY) { this._cameraPosition.y = 0; + + // A cylindrical billboard has no defined yaw when the camera is + // looking straight up or down. Normalizing that near-zero XZ + // projection amplifies floating-point noise and makes the sprite + // swing between opposite directions as the camera rotates. + // Keep the last valid orientation until a horizontal camera + // direction is available again. + const horizontalLengthSquared = + this._cameraPosition.x * this._cameraPosition.x + + this._cameraPosition.z * this._cameraPosition.z; + if (horizontalLengthSquared <= Vector3.EPSILON * Vector3.EPSILON) return; } this._cameraPosition.normalize(); Vector3.add(this._cameraPosition, this.object3D.localPosition, this._cameraPosition); - this.transform.lookAt(this.object3D.localPosition, this._cameraPosition, camera.transform.up); + // BillboardY must stay locked to the world Y axis. Using the camera's + // up vector introduces roll and becomes unstable at a vertical view. + const up = this.type == BillboardType.BillboardY ? Vector3.Y_AXIS : camera.transform.up; + this.transform.lookAt(this.object3D.localPosition, this._cameraPosition, up); } /** diff --git a/src/components/ColliderComponent.ts b/src/components/ColliderComponent.ts index 31551048a..b8f61c9f1 100644 --- a/src/components/ColliderComponent.ts +++ b/src/components/ColliderComponent.ts @@ -3,7 +3,9 @@ import { Ray } from "../math/Ray"; import { Vector3 } from "../math/Vector3"; import { ComponentBase } from "./ComponentBase"; import { BoxColliderShape } from "./shape/BoxColliderShape"; -import { ColliderShape, HitInfo } from "./shape/ColliderShape"; +import { ColliderShape, ColliderShapeType, HitInfo } from "./shape/ColliderShape"; +import type { MeshColliderShape } from "./shape/MeshColliderShape"; +import { MeshRenderer } from "./renderer/MeshRenderer"; /** * collider component @@ -55,11 +57,31 @@ export class ColliderComponent extends ComponentBase { */ public rayPick(ray: Ray): HitInfo { if (this._enable) { - return this._shape.rayPick(ray, this.transform.worldMatrix); + const shape = this._shape; + if (shape.shapeType === ColliderShapeType.Mesh) { + const meshShape = shape as MeshColliderShape; + if (!meshShape.mesh || !meshShape.renderer) { + // A mesh collider without a mesh picks the geometry drawn by + // this object; knowing the renderer lets skinned / morphed + // meshes be picked as drawn. + const renderer = this._renderer(); + if (!meshShape.mesh) meshShape.mesh = renderer ? renderer.geometry : null; + if (renderer && renderer.geometry === meshShape.mesh) meshShape.renderer = renderer; + } + } + return shape.rayPick(ray, this.transform.worldMatrix); } return null; } + private _renderer(): MeshRenderer { + let renderer: MeshRenderer = null; + this.object3D.components.forEach(c => { + if (!renderer && c instanceof MeshRenderer && c.geometry) renderer = c; + }); + return renderer; + } + public beforeDestroy(force?: boolean) { const view = this.transform.scene3D?.view; if (view?.engine3D?.setting.pick.mode == `pixel`) { diff --git a/src/components/anim/AnimatorComponent.ts b/src/components/anim/AnimatorComponent.ts index c86e7cd6a..ae6c98259 100644 --- a/src/components/anim/AnimatorComponent.ts +++ b/src/components/anim/AnimatorComponent.ts @@ -18,6 +18,12 @@ export class AnimatorComponent extends ComponentBase { public timeScale: number = 1.0; /** GPU buffer mapping joints to their world-matrix indices. */ public jointMatrixIndexTableBuffer: StorageGPUBuffer; + /** + * CPU copy of `jointMatrixIndexTableBuffer`: for each bone ID, the + * global matrix index (`Matrix4.index`) of that bone's world matrix. + * Used by CPU skinning (`MeshDeformer`). + */ + public jointMatrixIndexTable: number[]; /** Whether the blend-shape (morph) animation loops. */ public playBlendShapeLoop: boolean = false; protected inverseBindMatrices: FloatArray[]; @@ -224,6 +230,7 @@ export class AnimatorComponent extends ComponentBase { this._avatar = Engine3D.resFor(ctx).getObj(name) as PrefabAvatarData; let jointMapping = this.buildSkeletonPose(); + this.jointMatrixIndexTable = jointMapping; const jointMatrixIndexTable = new Float32Array(jointMapping); this.jointMatrixIndexTableBuffer = new StorageGPUBuffer(this._avatar.count, 0, jointMatrixIndexTable); } diff --git a/src/components/anim/morphAnim/MorphTargetData.ts b/src/components/anim/morphAnim/MorphTargetData.ts index 52ddda927..e88b64672 100644 --- a/src/components/anim/morphAnim/MorphTargetData.ts +++ b/src/components/anim/morphAnim/MorphTargetData.ts @@ -150,6 +150,27 @@ export class MorphTargetData { this._morphInfluenceArray[index] = value; } + /** Current influence weight of each morph target (read-only view; use `updateInfluence` to change). */ + public get influences(): Float32Array { + return this._morphInfluenceArray; + } + + /** Number of morph targets of the current geometry. */ + public get morphTargetCount(): number { + return this._morphTargetCount; + } + + /** + * Weight of the base position in the blend, as the shader applies it: + * 1 for relative targets, `1 - Σ influences` for absolute ones. + */ + public get baseInfluence(): number { + if (this.morphTargetsRelative) return 1; + let sum = 0; + for (let i = 0; i < this._morphTargetCount; i++) sum += this._morphInfluenceArray[i]; + return 1 - sum; + } + /** Map of blend-shape name to its influence-setter function. */ public get blendShape() { return this._blendTarget; diff --git a/src/components/controller/OrbitController.ts b/src/components/controller/OrbitController.ts index 8a947a0f8..1ba54c433 100644 --- a/src/components/controller/OrbitController.ts +++ b/src/components/controller/OrbitController.ts @@ -6,6 +6,7 @@ import { Vector3Ex } from '../../util/Vector3Ex'; import { clamp } from '../../math/MathUtil'; import { PointerEvent3D } from '../../event/eventConst/PointerEvent3D'; import { CameraType } from '../../core/CameraType'; +import { Spherical } from '../../math/Spherical'; /** * Orbit Camera Controller @@ -317,57 +318,3 @@ export class OrbitController extends ComponentBase { input.removeEventListener(PointerEvent3D.POINTER_UP, this.onPointerUp, this); } } - -/** - * @internal - * Epsilon to test whether numbers are close enough to be considered equal. - */ -const EPS = Math.PI / 180 / 100; -/** - * @internal - */ -class Spherical { - public radius: number; - public phi: number; - public theta: number; - public coords: Vector3; - constructor(radius = 1, phi = 0, theta = 0) { - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle - this.coords = new Vector3() - return this; - } - public set(radius: number, phi: number, theta: number) { - this.radius = radius; - this.phi = phi; - this.theta = theta; - return this; - } - // restrict phi to be between EPS and PI-EPS - public makeSafe(): this { - this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi)); - return this; - } - public setFromVector3(v: Vector3): this { - return this.setCoords(v.x, v.y, v.z); - } - public setCoords(x: number, y: number, z: number): this { - this.radius = Math.sqrt(x * x + y * y + z * z); - if (this.radius === 0) { - this.theta = 0; - this.phi = 0; - } else { - this.theta = Math.atan2(x, z); - this.phi = Math.acos(clamp(y / this.radius, - 1, 1)); - } - return this; - } - public getCoords(): Vector3 { - const sinPhiRadius = Math.sin(this.phi) * this.radius; - this.coords.x = sinPhiRadius * Math.sin(this.theta); - this.coords.y = Math.cos(this.phi) * this.radius; - this.coords.z = sinPhiRadius * Math.cos(this.theta); - return this.coords; - } -} diff --git a/src/components/renderer/FluidRenderer.ts b/src/components/renderer/FluidRenderer.ts new file mode 100644 index 000000000..bdcd259fb --- /dev/null +++ b/src/components/renderer/FluidRenderer.ts @@ -0,0 +1,259 @@ +import { GPUBufferBase } from '../../gfx/graphics/webGpu/core/buffer/GPUBufferBase'; +import { Texture } from '../../gfx/graphics/webGpu/core/texture/Texture'; +import { Color } from '../../math/Color'; +import { Vector3 } from '../../math/Vector3'; +import { ComponentBase } from '../ComponentBase'; + +/** + * Byte layout of one particle inside a particle buffer. + * @group Components + */ +export type FluidDataLayout = { + /** Bytes between two consecutive particles. Default 16 (one vec4f). */ + stride?: number; + /** Byte offset of the xyz position inside a particle. Default 0. */ + positionOffset?: number; +}; + +/** + * Filter that smooths the fluid depth map. + * @group Components + */ +export enum FluidDepthFilter { + /** Separable bilateral filter: spatial gaussian weighted by depth similarity. */ + Bilateral = 0, + /** Narrow-range filter: averages only samples within a depth range that follows the surface; keeps silhouettes and separate layers sharper at larger radii. */ + NarrowRange = 1, +} + +/** + * How the thickness used for light absorption is measured. + * @group Components + */ +export enum FluidThicknessMode { + /** Sum of every particle's contribution along the view ray ({@link FluidRenderer.particleThicknessAlpha} each). Follows the particle density, so uneven sampling shows as uneven absorption. */ + Accumulated = 0, + /** Distance between the near and the far side of the fluid along the view ray, in world units; even inside a still body of fluid. Gaps between separate bodies along the ray count as fluid. */ + Geometric = 1, +} + +/** + * Intermediate image shown instead of the shaded fluid when + * {@link FluidRenderer.debug} is on. + * @group Components + */ +export enum FluidDebug { + /** Linear view-space depth of the particle spheres. */ + DepthTexture = 0, + /** Depth after the bilateral blur. */ + DepthBlurredTexture = 1, + /** Accumulated particle thickness. */ + ThicknessTexture = 2, + /** Thickness after the gaussian blur. */ + ThicknessBlurredTexture = 3, + /** View-space normals reconstructed from the blurred depth. */ + Normals = 4, +} + +/** + * Renders a particle set as a continuous liquid surface (screen-space + * fluid rendering). Particles are drawn as sphere impostors into a + * depth buffer which is then smoothed and shaded in screen space. + * + * Requires `setting.render.fluid = true` so {@link ForwardRendererJob} + * adds {@link FluidPass}. The fluid is drawn after opaque geometry and + * before transparent geometry. + * + * Particle positions are in the local space of the owning Object3D + * (world space when it sits at the origin unscaled); particleSize is + * in world units. They come from either: + * - {@link setDataBuffer}: a CPU `Float32Array`, uploaded when set. + * - {@link setDataBufferGPU}: an existing storage buffer (e.g. written by + * a simulation compute shader), read directly without a copy. + * + * @group Components + */ +export class FluidRenderer extends ComponentBase { + /** Particle diameter in world units. */ + public particleSize: number = 0.1; + /** Thickness one particle adds at its center; the fluid gets more opaque as it grows. */ + public particleThicknessAlpha: number = 0.05; + + /** Width of the depth map in pixels; height follows the screen aspect. null = screen size. */ + public depthMapSize: number | null = null; + /** Width of the thickness map in pixels; height follows the screen aspect. null = screen size. */ + public thicknessMapSize: number | null = null; + + /** Absorption color: light passing through the fluid is tinted toward it. */ + public fluidColor: Color = new Color(0.085, 0.6375, 0.765, 1); + /** Absorption strength; higher makes the fluid more opaque. With {@link FluidThicknessMode.Geometric} it is per world unit of thickness. */ + public density: number = 2; + /** Scale of the refraction offset: 1 follows the refracted ray to the scene behind, 0 disables refraction. */ + public refractionStrength: number = 1; + /** Upper bound of the fresnel reflection weight (0 to 1). */ + public fresnelClamp: number = 1; + /** Specular exponent; higher gives a smaller, sharper highlight. */ + public specularPower: number = 250; + /** Pixels with less thickness show the background. With {@link useFixedThickness}, the thickness used everywhere. */ + public minimumThickness: number = 0; + /** + * Fade the fluid into the background where it is thinner than this many particles + * (particleThicknessAlpha each when accumulated, particleSize each when geometric); + * softens free edges. 0 disables. + */ + public edgeSoftness: number = 0; + + private _thicknessMode: FluidThicknessMode = FluidThicknessMode.Accumulated; + /** How thickness is measured for absorption. */ + public get thicknessMode(): FluidThicknessMode { + return this._thicknessMode; + } + public set thicknessMode(value: FluidThicknessMode) { + // GUI dropdowns hand back option values as strings. + this._thicknessMode = Number(value); + } + /** Skip the thickness pass and use {@link minimumThickness} as a constant thickness. */ + public useFixedThickness: boolean = false; + /** World-space direction the light travels, for the specular highlight. null uses the scene's first DirectLight, or (-2, -1, 1) without one. */ + public dirLight: Vector3 | null = null; + /** Cube map reflected by the fluid. undefined uses the scene's envMap; null disables reflection. */ + public environmentMap: Texture | null | undefined = undefined; + + /** + * Stretch each particle into an ellipsoid along its neighbor distribution, so flat + * regions stay flat and thin sheets stay thin. Adds a neighbor search on the GPU each frame. + */ + public useAnisotropy: boolean = false; + /** Neighbor search radius in world units. null uses 1.5 × particleSize. */ + public anisotropyRadius: number | null = null; + /** Largest ratio between the longest and shortest ellipsoid axis. */ + public anisotropyMaxRatio: number = 4; + /** Particles with fewer neighbors stay spheres (spray, droplets). */ + public anisotropyMinNeighbors: number = 10; + /** How far (0 to 1) each particle moves toward the weighted mean of its neighbors, which smooths the surface. */ + public anisotropySmoothing: number = 0.5; + + /** Smooth the depth map so the spheres merge into one surface. */ + public enableBlurDepth: boolean = true; + private _depthFilter: FluidDepthFilter = FluidDepthFilter.Bilateral; + /** Filter used to smooth the depth map. */ + public get depthFilter(): FluidDepthFilter { + return this._depthFilter; + } + public set depthFilter(value: FluidDepthFilter) { + // GUI dropdowns hand back option values as strings. + this._depthFilter = Number(value); + } + /** Depth blur runs at the depth map size divided by this. */ + public blurDepthSizeDivisor: number = 1; + /** Depth blur radius, relative to the projected particle size. */ + public blurDepthFilterSize: number = 7; + /** Depth blur passes (each is one horizontal + one vertical pass). */ + public blurDepthNumIterations: number = 3; + /** Upper bound of the depth blur radius in pixels. */ + public blurDepthMaxFilterSize: number = 100; + /** Depth range, in particle radii, across which samples are still blended; larger merges more. */ + public blurDepthDepthScale: number = 10; + + /** Smooth the thickness map. */ + public enableBlurThickness: boolean = true; + /** Thickness blur runs at the thickness map size divided by this. */ + public blurThicknessSizeDivisor: number = 1; + /** Thickness blur radius in pixels. */ + public blurThicknessFilterSize: number = 5; + /** Thickness blur passes (each is one horizontal + one vertical pass). */ + public blurThicknessNumIterations: number = 1; + + /** Show the image selected by {@link debugFeature} instead of the fluid. */ + public debug: boolean = false; + + private _debugFeature: FluidDebug = FluidDebug.DepthBlurredTexture; + public get debugFeature(): FluidDebug { + return this._debugFeature; + } + public set debugFeature(value: FluidDebug) { + // GUI dropdowns hand back option values as strings. + this._debugFeature = Number(value); + } + + private _cpuData: Float32Array | null = null; + private _cpuVersion: number = 0; + private _gpuBuffer: GPUBufferBase | null = null; + private _count: number = 0; + private _stride: number = 16; + private _positionOffset: number = 0; + + /** + * Use CPU particle data. The array is uploaded on the next frame; + * call again after modifying it in place to re-upload. + * @param data particle data, laid out as described by `layout` + * @param count number of particles; defaults to as many as `data` holds + * @param layout particle byte layout + */ + public setDataBuffer(data: Float32Array, count?: number, layout?: FluidDataLayout): void { + this._setLayout(layout); + this._cpuData = data; + this._cpuVersion++; + this._gpuBuffer = null; + const capacity = Math.floor((data.byteLength - this._positionOffset - 12) / this._stride) + 1; + this._count = Math.max(0, Math.min(count ?? capacity, capacity)); + } + + /** + * Use a GPU buffer as particle data. The buffer needs `STORAGE` + * usage and is read every frame, so updates made by compute shaders + * show up without further calls. + * @param buffer storage buffer holding the particles + * @param count number of particles to draw + * @param layout particle byte layout + */ + public setDataBufferGPU(buffer: GPUBufferBase, count: number, layout?: FluidDataLayout): void { + this._setLayout(layout); + this._gpuBuffer = buffer; + this._cpuData = null; + this._count = Math.max(0, count | 0); + } + + /** Number of particles drawn. Can be lowered to draw a prefix of the buffer. */ + public get particleCount(): number { + return this._count; + } + public set particleCount(value: number) { + this._count = Math.max(0, value | 0); + } + + /** @internal */ + public get cpuData(): Float32Array | null { + return this._cpuData; + } + + /** @internal Incremented on every {@link setDataBuffer} call. */ + public get cpuVersion(): number { + return this._cpuVersion; + } + + /** @internal */ + public get gpuBuffer(): GPUBufferBase | null { + return this._gpuBuffer; + } + + /** @internal Particle stride in bytes. */ + public get stride(): number { + return this._stride; + } + + /** @internal Position offset in bytes. */ + public get positionOffset(): number { + return this._positionOffset; + } + + private _setLayout(layout?: FluidDataLayout): void { + const stride = layout?.stride ?? 16; + const offset = layout?.positionOffset ?? 0; + if (stride % 4 !== 0 || offset % 4 !== 0 || offset + 12 > stride) { + throw new Error(`FluidRenderer: invalid layout (stride=${stride}, positionOffset=${offset}); both must be multiples of 4 and the xyz position must fit inside the stride.`); + } + this._stride = stride; + this._positionOffset = offset; + } +} diff --git a/src/components/renderer/LODGroup.ts b/src/components/renderer/LODGroup.ts new file mode 100644 index 000000000..e55722be3 --- /dev/null +++ b/src/components/renderer/LODGroup.ts @@ -0,0 +1,361 @@ +import { Camera3D } from '../../core/Camera3D'; +import { CameraType } from '../../core/CameraType'; +import { Object3D } from '../../core/entities/Object3D'; +import { View3D } from '../../core/View3D'; +import { DEGREES_TO_RADIANS } from '../../math/MathUtil'; +import { Vector3 } from '../../math/Vector3'; +import { RegisterComponent } from '../../util/SerializeDecoration'; +import { ComponentBase } from '../ComponentBase'; + +/** + * How `LODGroup` measures "how big this object is on screen". + * @group Components + */ +export enum LODMode { + /** + * Unity-style: the ratio of the group's bounding-sphere diameter to the + * viewport height (0..1). Resolution- and FOV-aware, so a level switches + * at the same *apparent* size regardless of camera lens or distance. + * Level thresholds are that ratio (e.g. 0.5, 0.15, 0.03). + */ + ScreenSize = 0, + /** + * three.js-style: plain world-space distance from the camera to the + * group's bound center. Level thresholds are distances (e.g. 20, 60, 150). + */ + Distance = 1, +} + +/** + * One level of detail: the objects to show and the threshold at which it + * stops being used. + * @group Components + */ +export interface LODLevel { + /** + * Objects that make up this level. They are toggled via `transform.enable` + * (which also covers their children), so a level can be a whole glTF + * sub-tree, not just a single MeshRenderer. + */ + objects: Object3D[]; + /** + * `LODMode.ScreenSize`: the *minimum* screen-relative height this level + * stays visible for. `LODMode.Distance`: the *maximum* distance. + */ + threshold: number; +} + +/** + * Level-of-detail switcher. Registers N sets of objects with a threshold each + * and, every frame, enables exactly one set (or none, when the object is too + * small / far and `cullBeyondLast` is on) based on the view's camera. + * + * Levels are kept sorted from most to least detailed no matter the order + * they were added in, so `addLevel` can be called in any order. + * + * ```ts + * const lod = obj.addComponent(LODGroup); + * lod.addLevel([highMesh], 0.4); // shown while ≥40 % of viewport height + * lod.addLevel([midMesh], 0.12); // 12 %–40 % + * lod.addLevel([lowMesh], 0.03); // 3 %–12 %, below that: culled + * ``` + * @group Components + */ +@RegisterComponent(LODGroup, 'LODGroup') +export class LODGroup extends ComponentBase { + /** `currentLevel` value while every level is hidden. */ + public static readonly CULLED = -1; + + private _mode: LODMode = LODMode.ScreenSize; + + /** + * Global scale on the metric. In `ScreenSize` mode >1 keeps detailed + * levels visible longer (like Unity's `QualitySettings.lodBias`); in + * `Distance` mode the measured distance is divided by it, so the same + * direction applies. + */ + public bias: number = 1; + + /** + * Fraction of the threshold used as a dead-band so a group parked right + * on a boundary does not flicker between two levels. A level is only + * dropped for a coarser one when the metric is past the threshold, and + * only re-promoted when it is past `threshold * (1 + hysteresis)`. + */ + public hysteresis: number = 0.1; + + /** Hide every level once the last threshold is crossed. */ + public cullBeyondLast: boolean = true; + + /** + * Debug/authoring override: `null` = automatic, otherwise the level index + * to force (clamped). `LODGroup.CULLED` forces everything hidden. + */ + public forceLevel: number | null = null; + + /** + * Optional camera override; defaults to the camera of the view that + * updates this component. + */ + public camera: Camera3D | null = null; + + /** + * Bounding-sphere radius (world units) used for `ScreenSize`. `null` + * (default) derives it from the world bounds of every level's objects the + * first time it is needed; call `recalculateBounds()` after changing + * geometry or scale. + */ + public radius: number | null = null; + + private _levels: LODLevel[] = []; + private _currentLevel: number = LODGroup.CULLED; + private _lastMetric: number = 0; + private _hasApplied: boolean = false; + private _autoRadius: number = -1; + private _onLevelChange: ((level: number, previous: number) => void) | null = null; + private static readonly _tmpCenter: Vector3 = new Vector3(); + + /** + * Metric used to pick a level. Thresholds are in the metric's unit, so + * after switching modes hand in matching values via `setThresholds`. + * The level order (finest first) is kept across the switch on purpose: + * re-sorting by the *old* thresholds would reverse it, and the new + * thresholds are assigned by that order. + */ + public get mode(): LODMode { + return this._mode; + } + + public set mode(value: LODMode) { + if (this._mode === value) return; + this._mode = value; + this._hasApplied = false; + } + + /** Levels, most detailed first. Treat as read-only; use `addLevel` / `removeLevel`. */ + public get levels(): ReadonlyArray { + return this._levels; + } + + /** Index into `levels` of the level currently shown, or `LODGroup.CULLED`. */ + public get currentLevel(): number { + return this._currentLevel; + } + + /** Metric (screen-relative height or distance) measured on the last update. */ + public get lastMetric(): number { + return this._lastMetric; + } + + /** Called after the shown level changes. */ + public set onLevelChange(cb: ((level: number, previous: number) => void) | null) { + this._onLevelChange = cb; + } + + /** + * Register a level. Objects are hidden immediately; the right one is + * enabled on the next update. Returns the level's index after sorting. + */ + public addLevel(objects: Object3D | Object3D[], threshold: number): number { + const list = Array.isArray(objects) ? objects.slice() : [objects]; + const level: LODLevel = { objects: list, threshold }; + this._levels.push(level); + this._sortLevels(); + for (const o of list) o.transform.enable = false; + this._autoRadius = -1; + this._hasApplied = false; + return this._levels.indexOf(level); + } + + /** Remove a level (its objects are re-enabled and no longer managed). */ + public removeLevel(index: number): void { + const level = this._levels[index]; + if (!level) return; + this._levels.splice(index, 1); + for (const o of level.objects) o.transform.enable = true; + this._autoRadius = -1; + this._hasApplied = false; + } + + /** + * Change one level's threshold at runtime. Levels are re-sorted, so the + * index of *other* levels may move; to rewrite several thresholds use + * `setThresholds`, which assigns them all before sorting. + */ + public setThreshold(index: number, threshold: number): void { + const level = this._levels[index]; + if (!level) return; + level.threshold = threshold; + this._sortLevels(); + this._hasApplied = false; + } + + /** + * Rewrite every threshold in the current (finest-first) level order, then + * re-sort once. The usual companion of a `mode` switch. + */ + public setThresholds(thresholds: number[]): void { + const n = Math.min(thresholds.length, this._levels.length); + for (let i = 0; i < n; i++) this._levels[i].threshold = thresholds[i]; + this._sortLevels(); + this._hasApplied = false; + } + + /** Forget the cached auto radius; recomputed on next update. */ + public recalculateBounds(): void { + this._autoRadius = -1; + } + + /** + * Compute the metric this group would use for `camera` right now, + * without changing any state. Useful for tooling and tests. + */ + public measure(camera: Camera3D): number { + const center = this._worldCenter(LODGroup._tmpCenter); + const dist = Vector3.distance(center, camera.transform.worldPosition); + if (this.mode === LODMode.Distance) { + return dist / Math.max(this.bias, 1e-6); + } + const r = this._effectiveRadius(); + let h: number; + if (camera.type === CameraType.ortho && camera.frustumSize > 0) { + h = (2 * r) / camera.frustumSize; + } else { + const halfFovTan = Math.tan(camera.fov * 0.5 * DEGREES_TO_RADIANS); + h = r / (Math.max(dist, 1e-6) * halfFovTan); + } + return h * this.bias; + } + + /** + * Pick the level for a metric value, applying hysteresis relative to + * `from` (the level currently shown). Pure function of the inputs. + */ + public selectLevel(metric: number, from: number = this._currentLevel): number { + const n = this._levels.length; + if (n === 0) return LODGroup.CULLED; + if (this.forceLevel != null) { + return this.forceLevel === LODGroup.CULLED ? LODGroup.CULLED : Math.min(Math.max(this.forceLevel, 0), n - 1); + } + // "Passes" = the metric says this level (or a finer one) is allowed. + const passes = (i: number, promote: boolean): boolean => { + let t = this._levels[i].threshold; + if (this.mode === LODMode.ScreenSize) { + if (promote) t *= 1 + this.hysteresis; + return metric >= t; + } else { + if (promote) t /= 1 + this.hysteresis; + return metric <= t; + } + }; + let level = LODGroup.CULLED; + for (let i = 0; i < n; i++) { + // Promoting to a finer level than the current one needs the extra margin. + const promote = from === LODGroup.CULLED ? false : i < from; + if (passes(i, promote)) { level = i; break; } + } + if (level === LODGroup.CULLED && !this.cullBeyondLast) level = n - 1; + return level; + } + + public onUpdate(view?: View3D): void { + const cam = this.camera ?? view?.camera ?? this.transform.view3D?.camera; + if (!cam || this._levels.length === 0) return; + this._lastMetric = this.measure(cam); + this._apply(this.selectLevel(this._lastMetric, this._currentLevel)); + } + + public onEnable(): void { + // Re-apply on (re)enable so a group that was disabled with a stale + // level does not show two levels at once. + this._hasApplied = false; + } + + public destroy(force?: boolean): void { + for (const level of this._levels) for (const o of level.objects) o.transform.enable = true; + this._levels.length = 0; + this._onLevelChange = null; + super.destroy(force); + } + + public cloneTo(obj: Object3D): void { + const c = obj.addComponent(LODGroup); + c.mode = this.mode; + c.bias = this.bias; + c.hysteresis = this.hysteresis; + c.cullBeyondLast = this.cullBeyondLast; + c.forceLevel = this.forceLevel; + c.radius = this.radius; + // Level objects are children of the owner in the common case; map + // them by index into the clone's children, fall back to the originals. + for (const level of this._levels) { + const mapped = level.objects.map(o => { + const i = this.object3D.entityChildren.indexOf(o); + return i >= 0 ? ((obj.entityChildren[i] as Object3D) ?? o) : o; + }); + c.addLevel(mapped, level.threshold); + } + } + + private _apply(level: number): void { + if (this._hasApplied && level === this._currentLevel) return; + const previous = this._currentLevel; + for (let i = 0; i < this._levels.length; i++) { + const show = i === level; + for (const o of this._levels[i].objects) { + if (o.transform.enable !== show) o.transform.enable = show; + } + } + this._currentLevel = level; + this._hasApplied = true; + if (previous !== level) this._onLevelChange?.(level, previous); + } + + private _sortLevels(): void { + // Finest first: ScreenSize = larger threshold first; Distance = smaller first. + if (this._mode === LODMode.Distance) this._levels.sort((a, b) => a.threshold - b.threshold); + else this._levels.sort((a, b) => b.threshold - a.threshold); + } + + private _worldCenter(out: Vector3): Vector3 { + return out.copy(this.transform.worldPosition); + } + + private _effectiveRadius(): number { + if (this.radius != null && this.radius > 0) return this.radius; + if (this._autoRadius < 0) this._autoRadius = this._computeAutoRadius(); + return this._autoRadius; + } + + /** + * Largest distance from the owner's world position to any corner of any + * level object's world AABB. `Entity.bound` is transform-driven, not + * visibility-driven, so hidden levels still report correct bounds. + */ + private _computeAutoRadius(): number { + const origin = this.transform.worldPosition; + let r = 0; + for (const level of this._levels) { + for (const o of level.objects) { + r = Math.max(r, LODGroup._maxCornerDistance(o, origin)); + } + } + return r > 0 ? r : 0.5; + } + + private static _maxCornerDistance(o: Object3D, origin: Vector3): number { + let r = 0; + const b = o.bound; + if (b && b.extents && (b.extents.x > 0 || b.extents.y > 0 || b.extents.z > 0)) { + const c = b.center, e = b.extents; + const dx = Math.max(Math.abs(c.x - e.x - origin.x), Math.abs(c.x + e.x - origin.x)); + const dy = Math.max(Math.abs(c.y - e.y - origin.y), Math.abs(c.y + e.y - origin.y)); + const dz = Math.max(Math.abs(c.z - e.z - origin.z), Math.abs(c.z + e.z - origin.z)); + r = Math.sqrt(dx * dx + dy * dy + dz * dz); + } + for (const child of o.entityChildren) { + r = Math.max(r, LODGroup._maxCornerDistance(child as Object3D, origin)); + } + return r; + } +} diff --git a/src/components/renderer/MaterialVariants.ts b/src/components/renderer/MaterialVariants.ts new file mode 100644 index 000000000..a1bd04158 --- /dev/null +++ b/src/components/renderer/MaterialVariants.ts @@ -0,0 +1,86 @@ +import { Material } from '../../materials/Material'; +import { RegisterComponent } from '../../util/SerializeDecoration'; +import { ComponentBase } from '../ComponentBase'; + +/** + * One renderer's participation in the variant set: the material it was + * authored with, and the material to use for each variant index that maps it. + */ +export interface MaterialVariantBinding { + /** A `MeshRenderer` / `SkinnedMeshRenderer2` — anything with a `material` property. */ + renderer: { material: Material }; + /** Material used when no variant (or a variant that does not mention this primitive) is active. */ + original: Material; + /** Variant index → material. */ + byVariant: Map; +} + +/** + * Runtime switch for glTF `KHR_materials_variants` (product configurators: + * one mesh, several material sets — "red leather", "blue fabric", …). + * The glTF loader adds this component to the root object of any asset that + * declares variants. + * + * ```ts + * const root = await engine.res.loadGltf('shoe.glb'); + * const variants = root.getComponent(MaterialVariants); + * console.log(variants.variantNames); // ['midnight', 'beach', 'street'] + * variants.selectVariant('beach'); + * variants.selectVariant(null); // back to the authored default + * ``` + * @group Components + */ +@RegisterComponent(MaterialVariants, 'MaterialVariants') +export class MaterialVariants extends ComponentBase { + /** Variant names, in the order the asset declares them. */ + public variantNames: string[] = []; + + private _bindings: MaterialVariantBinding[] = []; + private _current: number = -1; + + /** Index of the active variant, or -1 for the authored default materials. */ + public get currentIndex(): number { + return this._current; + } + + /** Name of the active variant, or null for the authored default materials. */ + public get currentVariant(): string | null { + return this._current >= 0 ? this.variantNames[this._current] : null; + } + + /** Renderers that take part in at least one variant. */ + public get bindings(): ReadonlyArray { + return this._bindings; + } + + /** @internal Used by the loader. */ + public addBinding(binding: MaterialVariantBinding): void { + this._bindings.push(binding); + } + + /** + * Activate a variant by name or index; `null` / `-1` restores the + * authored materials. Primitives the variant does not mention fall back + * to their default material, as the extension specifies. + * @returns false when the name / index does not exist (nothing changes). + */ + public selectVariant(variant: string | number | null): boolean { + let index: number; + if (variant === null || variant === -1) index = -1; + else if (typeof variant === 'number') index = variant; + else index = this.variantNames.indexOf(variant); + if (index < -1 || index >= this.variantNames.length || (typeof variant === 'string' && index < 0)) return false; + + for (const b of this._bindings) { + const m = (index >= 0 && b.byVariant.get(index)) || b.original; + if (b.renderer.material !== m) b.renderer.material = m; + } + this._current = index; + return true; + } + + public destroy(force?: boolean): void { + this._bindings.length = 0; + super.destroy(force); + } +} diff --git a/src/components/renderer/WaterFFT.ts b/src/components/renderer/WaterFFT.ts new file mode 100644 index 000000000..4622f8b83 --- /dev/null +++ b/src/components/renderer/WaterFFT.ts @@ -0,0 +1,629 @@ +import { Context3D } from '../../gfx/graphics/webGpu/Context3D'; +import { GPUAddressMode, GPUFilterMode, GPUTextureFormat } from '../../gfx/graphics/webGpu/WebGPUConst'; +import { VirtualTexture } from '../../textures/VirtualTexture'; +import { WaterSpectrum } from './WaterSpectrum'; + +/** Texels per side of each cascade. */ +export const WATER_FFT_SIZE = 256; +const LOG_SIZE = 8; +/** Mip levels of the displacement and slope textures, down to one texel. */ +export const WATER_FFT_MIPS = LOG_SIZE + 1; +/** Side in metres of the patch each cascade tiles the water with. */ +export const WATER_FFT_PATCHES = [256, 40, 6]; +/** + * Shortest wavelength each cascade holds: each keeps the band of the + * spectrum from where the previous one stops to four of its own texels + * per wave, the last one down to two. + */ +export const WATER_FFT_SHORTEST = [10, 1.5, 2 * 6 / WATER_FFT_SIZE]; + +/** Points whose height the CPU can ask for per frame. */ +export const WATER_FFT_MAX_QUERIES = 64; +const STAGING = 3; +/** Read-back heights are kept this long after a point was last asked for. */ +const HEIGHT_KEEP_MS = 2000; + +/** Foam left by whitecaps fades to this fraction after a second. */ +const FOAM_DECAY_PER_SECOND = 0.35; +/** Whitecaps start where the waves pinch the surface below this Jacobian. */ +const FOAM_THRESHOLD = 0.6; + +/** + * GPU simulation of a {@link WaterSpectrum} (Tessendorf): each cascade's + * initial spectrum is evolved in time and turned into the surface with + * inverse FFTs, giving per cascade a displacement texture (x, y, z + * displacement, dDx/dz) and a slope texture (dDy/dx, dDy/dz, dDx/dx, + * dDz/dz), tiled over the water every patch size. Both carry mipmaps, so + * the surface can drop the waves too short for the mesh or the pixel at + * a distance and keep the long ones. Whitecaps, where the + * summed cascades pinch the surface, are added to a foam map that fades + * over time, so foam trails behind the crests that made it. + * @internal + */ +export class WaterFFT { + /** Per cascade: displacement and slope (rgba16float, filterable). */ + public readonly displacement: VirtualTexture[] = []; + public readonly slope: VirtualTexture[] = []; + /** Foam over the first cascade's patch (r = foam, g = Jacobian). */ + public readonly foam: VirtualTexture; + + private _ctx: Context3D; + private _device: GPUDevice; + private _h0: GPUTexture[] = []; + private _fieldsA: GPUTexture[] = []; + private _fieldsB: GPUTexture[] = []; + private _scratch: GPUTexture; + private _foamNext: VirtualTexture; + private _uniform: GPUBuffer; + private _pipelines: Record = {}; + private _groups: Record & { mip?: { group: GPUBindGroup; size: number }[] } = {}; + private _shapeKey = ''; + private _sampler: GPUSampler; + private _queryPoints: GPUBuffer; + private _queryHeights: GPUBuffer; + private _staging: { buffer: GPUBuffer; state: 'free' | 'copied' | 'mapping'; points: Float32Array }[] = []; + /** Heights read back, kept until not asked for again for a while. */ + private _heights: { x: number; z: number; h: number; time: number }[] = []; + + constructor(ctx: Context3D) { + this._ctx = ctx; + const device = this._device = ctx.device as GPUDevice; + const N = WATER_FFT_SIZE; + const internal = (label: string) => device.createTexture({ + label, size: [N, N, 1], format: 'rgba32float', + usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING, + }); + const visible = (mips: number) => { + const usage = GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING + | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST; + const t = new VirtualTexture(N, N, GPUTextureFormat.rgba16float, false, usage, 1, 0, mips, ctx); + // Tiled every patch: plain repeat (the default mirrors), blended between mips. + t.addressModeU = GPUAddressMode.repeat; + t.addressModeV = GPUAddressMode.repeat; + t.mipmapFilter = GPUFilterMode.linear; + return t; + }; + for (let c = 0; c < WATER_FFT_PATCHES.length; c++) { + this._h0.push(internal(`WaterFFT:h0:${c}`)); + this._fieldsA.push(internal(`WaterFFT:A:${c}`)); + this._fieldsB.push(internal(`WaterFFT:B:${c}`)); + this.displacement.push(visible(WATER_FFT_MIPS)); + this.slope.push(visible(WATER_FFT_MIPS)); + } + this._scratch = internal('WaterFFT:scratch'); + this.foam = visible(1); + this._foamNext = visible(1); + this._sampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear', addressModeU: 'repeat', addressModeV: 'repeat' }); + // Uniform slots, 256 bytes apart: init and evolve per cascade, the two FFT directions, foam. + this._uniform = device.createBuffer({ + label: 'WaterFFT:Uniforms', size: 256 * UNIFORM_SLOTS, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + device.queue.writeBuffer(this._uniform, SLOT_FFT_ROWS * 256, new Float32Array([0, 0, 0, 0])); + device.queue.writeBuffer(this._uniform, SLOT_FFT_COLUMNS * 256, new Float32Array([1, 0, 0, 0])); + this._queryPoints = device.createBuffer({ + label: 'WaterFFT:QueryPoints', size: WATER_FFT_MAX_QUERIES * 8, + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, + }); + this._queryHeights = device.createBuffer({ + label: 'WaterFFT:QueryHeights', size: WATER_FFT_MAX_QUERIES * 4, + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC, + }); + for (let i = 0; i < STAGING; i++) { + this._staging.push({ + buffer: device.createBuffer({ label: `WaterFFT:Readback:${i}`, size: WATER_FFT_MAX_QUERIES * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }), + state: 'free', points: new Float32Array(0), + }); + } + this._createPipelines(); + this._createBindGroups(); + } + + /** + * Height of the cascades above world (x, z), read back from an earlier + * frame at the nearest point asked for within a metre; null if none. + */ + public heightAt(x: number, z: number): number | null { + let best = 1, found: number | null = null; + for (const e of this._heights) { + const d = Math.hypot(e.x - x, e.z - z); + if (d < best) { + best = d; + found = e.h; + } + } + return found; + } + + /** + * Computes the heights at these world xz points (x, z pairs, up to + * {@link WATER_FFT_MAX_QUERIES}) for reading back once submitted + * ({@link readBack}). + */ + public queryHeights(command: GPUCommandEncoder, points: number[]): void { + const count = Math.min(points.length >> 1, WATER_FFT_MAX_QUERIES); + const slot = this._staging.find((s) => s.state === 'free'); + if (count === 0 || !slot) return; + const data = new Float32Array(points.slice(0, count * 2)); + this._device.queue.writeBuffer(this._queryPoints, 0, data); + this._device.queue.writeBuffer(this._uniform, SLOT_QUERY * 256, new Float32Array([ + WATER_FFT_PATCHES[0], WATER_FFT_PATCHES[1], WATER_FFT_PATCHES[2], count, + ])); + const pass = command.beginComputePass({ label: 'WaterFFT:query' }); + pass.setPipeline(this._pipelines.query); + pass.setBindGroup(0, this._groups.query[0]); + pass.dispatchWorkgroups(Math.ceil(count / 64)); + pass.end(); + command.copyBufferToBuffer(this._queryHeights, 0, slot.buffer, 0, count * 4); + slot.state = 'copied'; + slot.points = data; + } + + /** Starts reading back the heights computed in work submitted since the last call. */ + public readBack(): void { + for (const slot of this._staging) { + if (slot.state !== 'copied') continue; + slot.state = 'mapping'; + slot.buffer.mapAsync(GPUMapMode.READ).then(() => { + const heights = new Float32Array(slot.buffer.getMappedRange().slice(0)); + slot.buffer.unmap(); + // Update the points asked for again, add new ones, forget those not asked for in a while. + const now = performance.now(); + const kept = this._heights.filter((e) => now - e.time < HEIGHT_KEEP_MS); + for (let i = 0; i < slot.points.length >> 1; i++) { + const x = slot.points[i * 2], z = slot.points[i * 2 + 1]; + const same = kept.find((e) => Math.abs(e.x - x) < 0.01 && Math.abs(e.z - z) < 0.01); + if (same) { + same.h = heights[i]; + same.time = now; + } else { + kept.push({ x, z, h: heights[i], time: now }); + } + } + this._heights = kept; + slot.state = 'free'; + }, () => { + slot.state = 'free'; + }); + } + } + + /** + * Advances the waves to `time` seconds and the foam by `dt`. + * The initial spectrum is rebuilt whenever its shape changes. + */ + public step(command: GPUCommandEncoder, spectrum: WaterSpectrum, time: number, dt: number): void { + const device = this._device; + const N = WATER_FFT_SIZE; + const cascades = WATER_FFT_PATCHES.length; + const groups = N / 8; + if (spectrum.shapeKey !== this._shapeKey) { + this._shapeKey = spectrum.shapeKey; + const dir = spectrum.windDirection; + for (let c = 0; c < cascades; c++) { + const kMin = c === 0 ? 0 : 2 * Math.PI / WATER_FFT_SHORTEST[c - 1]; + const kMax = 2 * Math.PI / WATER_FFT_SHORTEST[c]; + device.queue.writeBuffer(this._uniform, (SLOT_INIT + c) * 256, new Float32Array([ + WATER_FFT_PATCHES[c], kMin, kMax, spectrum.seed, + spectrum.windSpeed, spectrum.fetch, Math.atan2(dir.y, dir.x), spectrum.amplitude, + ])); + } + const pass = command.beginComputePass({ label: 'WaterFFT:init' }); + pass.setPipeline(this._pipelines.init); + for (let c = 0; c < cascades; c++) { + pass.setBindGroup(0, this._groups.init[c]); + pass.dispatchWorkgroups(groups, groups); + } + pass.end(); + } + + for (let c = 0; c < cascades; c++) { + device.queue.writeBuffer(this._uniform, (SLOT_EVOLVE + c) * 256, + new Float32Array([WATER_FFT_PATCHES[c], time, spectrum.choppiness, 0])); + } + const decay = Math.pow(FOAM_DECAY_PER_SECOND, Math.max(dt, 0)); + device.queue.writeBuffer(this._uniform, SLOT_FOAM * 256, new Float32Array([ + WATER_FFT_PATCHES[0], WATER_FFT_PATCHES[1], WATER_FFT_PATCHES[2], 0, + decay, FOAM_THRESHOLD, 2.5, 0, + ])); + + const pass = command.beginComputePass({ label: 'WaterFFT' }); + pass.setPipeline(this._pipelines.evolve); + for (let c = 0; c < cascades; c++) { + pass.setBindGroup(0, this._groups.evolve[c]); + pass.dispatchWorkgroups(groups, groups); + } + // Rows then columns of each field texture, through the scratch texture and back. + pass.setPipeline(this._pipelines.fft); + for (const g of this._groups.fft) { + pass.setBindGroup(0, g); + pass.dispatchWorkgroups(N); + } + pass.setPipeline(this._pipelines.assemble); + for (let c = 0; c < cascades; c++) { + pass.setBindGroup(0, this._groups.assemble[c]); + pass.dispatchWorkgroups(groups, groups); + } + // Mip levels of the displacement and slope textures, each from the one above. + pass.setPipeline(this._pipelines.mip); + for (const g of this._groups.mip) { + pass.setBindGroup(0, g.group); + pass.dispatchWorkgroups(Math.ceil(g.size / 8), Math.ceil(g.size / 8)); + } + pass.setPipeline(this._pipelines.foam); + pass.setBindGroup(0, this._groups.foam[0]); + pass.dispatchWorkgroups(groups, groups); + pass.end(); + command.copyTextureToTexture( + { texture: this._foamNext.getGPUTexture() as GPUTexture }, + { texture: this.foam.getGPUTexture() as GPUTexture }, [N, N, 1]); + } + + public destroy(): void { + [...this._h0, ...this._fieldsA, ...this._fieldsB, this._scratch].forEach((t) => t.destroy()); + [...this.displacement, ...this.slope, this.foam, this._foamNext].forEach((t) => t.destroy()); + this._uniform.destroy(); + this._queryPoints.destroy(); + this._queryHeights.destroy(); + this._staging.forEach((s) => s.buffer.destroy()); + } + + private _createPipelines(): void { + const device = this._device; + const make = (name: string, code: string) => { + this._pipelines[name] = device.createComputePipeline({ + label: `WaterFFT:${name}`, layout: 'auto', + compute: { module: device.createShaderModule({ label: `WaterFFT:${name}`, code: COMMON_WGSL + code }), entryPoint: 'main' }, + }); + }; + make('init', INIT_WGSL); + make('evolve', EVOLVE_WGSL); + make('fft', FFT_WGSL); + make('assemble', ASSEMBLE_WGSL); + make('foam', FOAM_WGSL); + make('query', QUERY_WGSL); + make('mip', MIP_WGSL); + } + + private _createBindGroups(): void { + const device = this._device; + const buffer = (slot: number) => ({ buffer: this._uniform, offset: slot * 256, size: 64 }); + // Level 0 only: storage bindings take one level, and the passes here read full detail. + const view = (t: GPUTexture | VirtualTexture, level = 0) => + (t instanceof VirtualTexture ? t.getGPUTexture() as GPUTexture : t).createView({ baseMipLevel: level, mipLevelCount: 1 }); + const group = (name: string, entries: GPUBindingResource[]) => device.createBindGroup({ + layout: this._pipelines[name].getBindGroupLayout(0), + entries: entries.map((resource, binding) => ({ binding, resource })), + }); + this._groups.init = []; + this._groups.evolve = []; + this._groups.assemble = []; + this._groups.fft = []; + for (let c = 0; c < WATER_FFT_PATCHES.length; c++) { + this._groups.init.push(group('init', [buffer(SLOT_INIT + c), view(this._h0[c])])); + this._groups.evolve.push(group('evolve', [buffer(SLOT_EVOLVE + c), view(this._h0[c]), view(this._fieldsA[c]), view(this._fieldsB[c])])); + for (const fields of [this._fieldsA[c], this._fieldsB[c]]) { + this._groups.fft.push(group('fft', [buffer(SLOT_FFT_ROWS), view(fields), view(this._scratch)])); + this._groups.fft.push(group('fft', [buffer(SLOT_FFT_COLUMNS), view(this._scratch), view(fields)])); + } + this._groups.assemble.push(group('assemble', [view(this._fieldsA[c]), view(this._fieldsB[c]), view(this.displacement[c]), view(this.slope[c])])); + } + this._groups.mip = []; + for (const t of [...this.displacement, ...this.slope]) { + for (let level = 1; level < WATER_FFT_MIPS; level++) { + this._groups.mip.push({ group: group('mip', [view(t, level - 1), view(t, level)]), size: WATER_FFT_SIZE >> level }); + } + } + this._groups.query = [group('query', [ + buffer(SLOT_QUERY), this._sampler, + view(this.displacement[0]), view(this.displacement[1]), view(this.displacement[2]), + { buffer: this._queryPoints }, { buffer: this._queryHeights }, + ])]; + this._groups.foam = [group('foam', [ + buffer(SLOT_FOAM), this._sampler, + view(this.displacement[0]), view(this.slope[0]), view(this.displacement[1]), view(this.slope[1]), + view(this.displacement[2]), view(this.slope[2]), view(this.foam), view(this._foamNext), + ])]; + } +} + +const SLOT_INIT = 0; +const SLOT_EVOLVE = 3; +const SLOT_FFT_ROWS = 6; +const SLOT_FFT_COLUMNS = 7; +const SLOT_FOAM = 8; +const SLOT_QUERY = 9; +const UNIFORM_SLOTS = 10; + +const COMMON_WGSL = /* wgsl */` +const N: u32 = ${WATER_FFT_SIZE}u; +const LOG_N: u32 = ${LOG_SIZE}u; +const G: f32 = 9.81; +const PI: f32 = 3.14159265; + +// Wavenumber of texel n of a patch of the given size, the zero frequency at the center. +fn wavenumber(n: vec2i, extent: f32) -> vec2f { + return 2.0 * PI * (vec2f(n) - f32(N / 2u)) / extent; +} + +fn cmul(a: vec2f, b: vec2f) -> vec2f { + return vec2f(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); +} + +// i * a +fn mulI(a: vec2f) -> vec2f { + return vec2f(-a.y, a.x); +} +`; + +const INIT_WGSL = /* wgsl */` +struct Init { + // x = patch size, y = smallest wavenumber kept, z = largest, w = seed + extent: vec4f, + // x = wind speed, y = fetch, z = wind angle, w = amplitude + wind: vec4f, +}; +@group(0) @binding(0) var u: Init; +@group(0) @binding(1) var h0: texture_storage_2d; + +fn hash(v: vec3u) -> f32 { + var x = v.x * 1664525u + v.y * 1013904223u + v.z * 2654435769u; + x ^= x >> 16u; + x *= 2246822519u; + x ^= x >> 13u; + x *= 3266489917u; + x ^= x >> 16u; + return f32(x) / 4294967295.0; +} + +// Two independent standard normal numbers for texel n (Box-Muller). +fn gauss(n: vec2i) -> vec2f { + let s = u32(u.extent.w) * 7919u + u32(u.extent.x * 16.0); + let u1 = max(hash(vec3u(vec2u(n), s)), 1e-7); + let u2 = hash(vec3u(vec2u(n), s + 1u)); + let r = sqrt(-2.0 * log(u1)); + return r * vec2f(cos(2.0 * PI * u2), sin(2.0 * PI * u2)); +} + +// JONSWAP frequency spectrum for the wind speed and fetch. +fn jonswap(omega: f32) -> f32 { + let wind = max(u.wind.x, 0.1); + let fetch = max(u.wind.y, 1.0); + let alpha = 0.076 * pow(wind * wind / (fetch * G), 0.22); + let peak = 22.0 * pow(G * G / (wind * fetch), 1.0 / 3.0); + let sigma = select(0.09, 0.07, omega <= peak); + let r = exp(-(omega - peak) * (omega - peak) / (2.0 * sigma * sigma * peak * peak)); + return alpha * G * G / pow(omega, 5.0) * exp(-1.25 * pow(peak / omega, 4.0)) * pow(3.3, r); +} + +// Complex amplitude scale of the wave with wavenumber k: from the spectrum around k, +// spread toward the wind (none against it), within this cascade's band. +fn amplitude(k: vec2f) -> f32 { + let kl = length(k); + if (kl < max(u.extent.y, 1e-6) || kl >= u.extent.z) { + return 0.0; + } + let omega = sqrt(G * kl); + let c = cos(atan2(k.y, k.x) - u.wind.z); + let spread = select(0.0, 2.0 / PI * c * c, c > 0.0); + let dk = 2.0 * PI / u.extent.x; + // Energy per wavenumber area: S(omega) D(theta) domega/dk / k. + let energy = jonswap(omega) * spread * (G / (2.0 * omega)) / kl; + // The height at k sums this wave and the conjugate of the one at -k, and the two normal + // numbers add a factor 2: a quarter of the energy each keeps the variance at E dk^2. + // Ripples under a centimetre or so carry no energy. + return sqrt(max(energy * dk * dk * 0.25, 0.0)) * exp(-kl * kl * 1e-4) * u.wind.w; +} + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let n = vec2i(id.xy); + let k = wavenumber(n, u.extent.x); + let a = gauss(n) * amplitude(k); + // The wave running the other way, -k, sits at texel N - n. + let b = gauss((vec2i(i32(N)) - n) % vec2i(i32(N))) * amplitude(-k); + // Stored: h0(k) and the conjugate of h0(-k). + textureStore(h0, n, vec4f(a, b.x, -b.y)); +} +`; + +const EVOLVE_WGSL = /* wgsl */` +struct Evolve { + // x = patch size, y = time, z = choppiness + p: vec4f, +}; +@group(0) @binding(0) var u: Evolve; +@group(0) @binding(1) var h0: texture_2d; +@group(0) @binding(2) var fieldsA: texture_storage_2d; +@group(0) @binding(3) var fieldsB: texture_storage_2d; + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let n = vec2i(id.xy); + let k = wavenumber(n, u.p.x); + let kl = length(k); + if (kl < 1e-6) { + textureStore(fieldsA, n, vec4f(0.0)); + textureStore(fieldsB, n, vec4f(0.0)); + return; + } + let s = textureLoad(h0, n, 0); + let phase = sqrt(G * kl) * u.p.y; + let e = vec2f(cos(phase), sin(phase)); + // Height spectrum at this time: a wave running along k plus one along -k. + let h = cmul(s.xy, e) + cmul(s.zw, vec2f(e.x, -e.y)); + let kn = k / kl; + let chop = u.p.z; + // Horizontal displacement toward the crests, i k/|k| h, and the derivatives. + let dx = mulI(h) * kn.x * chop; + let dz = mulI(h) * kn.y * chop; + let dydx = mulI(h) * k.x; + let dydz = mulI(h) * k.y; + let dxdx = -h * kn.x * k.x * chop; + let dzdz = -h * kn.y * k.y * chop; + let dxdz = -h * kn.x * k.y * chop; + // Two real fields per complex transform: A + iB gives A in the real part, B in the imaginary. + textureStore(fieldsA, n, vec4f(dx + mulI(dz), h + mulI(dxdz))); + textureStore(fieldsB, n, vec4f(dydx + mulI(dydz), dxdx + mulI(dzdz))); +} +`; + +const FFT_WGSL = /* wgsl */` +struct Fft { + // x = 1 for columns + p: vec4f, +}; +@group(0) @binding(0) var u: Fft; +@group(0) @binding(1) var src: texture_2d; +@group(0) @binding(2) var dst: texture_storage_2d; + +// Two halves, read from one and written to the other each stage. +var buf: array; + +// w times each of the two complex numbers in v. +fn cmul2(w: vec2f, v: vec4f) -> vec4f { + return vec4f(cmul(w, v.xy), cmul(w, v.zw)); +} + +// Inverse FFT of one row (or column), radix 2, one invocation per element. +@compute @workgroup_size(${WATER_FFT_SIZE}) +fn main(@builtin(local_invocation_id) lid: vec3u, @builtin(workgroup_id) wid: vec3u) { + let j = lid.x; + let line = wid.x; + let vertical = u.p.x > 0.5; + let at = select(vec2i(i32(j), i32(line)), vec2i(i32(line), i32(j)), vertical); + buf[reverseBits(j) >> (32u - LOG_N)] = textureLoad(src, at, 0); + workgroupBarrier(); + var cur = 0u; + for (var s = 0u; s < LOG_N; s++) { + let size = 2u << s; + let half = size >> 1u; + let pos = j % size; + var v: vec4f; + if (pos < half) { + let angle = 2.0 * PI * f32(pos) / f32(size); + v = buf[cur + j] + cmul2(vec2f(cos(angle), sin(angle)), buf[cur + j + half]); + } else { + let angle = 2.0 * PI * f32(pos - half) / f32(size); + v = buf[cur + j - half] - cmul2(vec2f(cos(angle), sin(angle)), buf[cur + j]); + } + buf[(N - cur) + j] = v; + cur = N - cur; + workgroupBarrier(); + } + textureStore(dst, at, buf[cur + j]); +} +`; + +const ASSEMBLE_WGSL = /* wgsl */` +@group(0) @binding(0) var fieldsA: texture_2d; +@group(0) @binding(1) var fieldsB: texture_2d; +@group(0) @binding(2) var displacement: texture_storage_2d; +@group(0) @binding(3) var slope: texture_storage_2d; + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let n = vec2i(id.xy); + // The spectrum's zero frequency sits at the center: undo that shift. + let s = select(1.0, -1.0, ((n.x + n.y) & 1) == 1); + let a = textureLoad(fieldsA, n, 0) * s; + let b = textureLoad(fieldsB, n, 0) * s; + // x = Dx, y = Dy (height), z = Dz, w = dDx/dz + textureStore(displacement, n, vec4f(a.x, a.z, a.y, a.w)); + // dDy/dx, dDy/dz, dDx/dx, dDz/dz + textureStore(slope, n, b); +} +`; + +const FOAM_WGSL = /* wgsl */` +struct Foam { + // patch sizes of the three cascades + patches: vec4f, + // x = fraction kept per step, y = Jacobian below which whitecaps form, z = how fast they whiten + p: vec4f, +}; +@group(0) @binding(0) var u: Foam; +@group(0) @binding(1) var linearRepeat: sampler; +@group(0) @binding(2) var displacement0: texture_2d; +@group(0) @binding(3) var slope0: texture_2d; +@group(0) @binding(4) var displacement1: texture_2d; +@group(0) @binding(5) var slope1: texture_2d; +@group(0) @binding(6) var displacement2: texture_2d; +@group(0) @binding(7) var slope2: texture_2d; +@group(0) @binding(8) var previous: texture_2d; +@group(0) @binding(9) var next: texture_storage_2d; + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let n = vec2i(id.xy); + // This texel's point of the first cascade's patch; the others tile it too. + let p = (vec2f(n) + 0.5) / f32(N) * u.patches.x; + let uv1 = p / u.patches.y; + let uv2 = p / u.patches.z; + let s = textureSampleLevel(slope0, linearRepeat, p / u.patches.x, 0.0) + + textureSampleLevel(slope1, linearRepeat, uv1, 0.0) + + textureSampleLevel(slope2, linearRepeat, uv2, 0.0); + let dxdz = textureSampleLevel(displacement0, linearRepeat, p / u.patches.x, 0.0).w + + textureSampleLevel(displacement1, linearRepeat, uv1, 0.0).w + + textureSampleLevel(displacement2, linearRepeat, uv2, 0.0).w; + // How much the waves squeeze the surface together: below the threshold, whitecaps. + let jacobian = (1.0 + s.z) * (1.0 + s.w) - dxdz * dxdz; + let fresh = clamp((u.p.y - jacobian) * u.p.z, 0.0, 1.0); + let foam = max(textureLoad(previous, n, 0).r * u.p.x, fresh); + textureStore(next, n, vec4f(foam, jacobian, 0.0, 1.0)); +} +`; + +const QUERY_WGSL = /* wgsl */` +struct Query { + // xyz = patch sizes of the three cascades, w = points + p: vec4f, +}; +@group(0) @binding(0) var u: Query; +@group(0) @binding(1) var linearRepeat: sampler; +@group(0) @binding(2) var displacement0: texture_2d; +@group(0) @binding(3) var displacement1: texture_2d; +@group(0) @binding(4) var displacement2: texture_2d; +@group(0) @binding(5) var points: array; +@group(0) @binding(6) var heights: array; + +fn displaced(p: vec2f) -> vec3f { + return textureSampleLevel(displacement0, linearRepeat, p / u.p.x, 0.0).xyz + + textureSampleLevel(displacement1, linearRepeat, p / u.p.y, 0.0).xyz + + textureSampleLevel(displacement2, linearRepeat, p / u.p.z, 0.0).xyz; +} + +// Height of the surface above each point: the waves also move the water sideways, so +// the undisplaced point that lands there is found by fixed-point iteration. +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) id: vec3u) { + let i = id.x; + if (i >= u32(u.p.w)) { + return; + } + let xz = points[i]; + var p = xz; + for (var it = 0; it < 4; it++) { + p = xz - displaced(p).xz; + } + heights[i] = displaced(p).y; +} +`; + +const MIP_WGSL = /* wgsl */` +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var dst: texture_storage_2d; + +// One mip level: the average of the four texels above each. +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let size = textureDimensions(dst); + if (any(id.xy >= size)) { + return; + } + let c = vec2i(id.xy) * 2; + let v = textureLoad(src, c, 0) + textureLoad(src, c + vec2i(1, 0), 0) + + textureLoad(src, c + vec2i(0, 1), 0) + textureLoad(src, c + vec2i(1, 1), 0); + textureStore(dst, vec2i(id.xy), v * 0.25); +} +`; diff --git a/src/components/renderer/WaterFoamTexture.ts b/src/components/renderer/WaterFoamTexture.ts new file mode 100644 index 000000000..a4fcd7a9b --- /dev/null +++ b/src/components/renderer/WaterFoamTexture.ts @@ -0,0 +1,97 @@ +import { Context3D } from '../../gfx/graphics/webGpu/Context3D'; +import { BitmapTexture2D } from '../../textures/BitmapTexture2D'; + +const SIZE = 512; +const BUBBLES = 6000; + +const cache = new WeakMap(); + +/** + * Tileable sea foam (r = foam): bubbles of many sizes packed into clusters, + * each drawn as a bright rim around a clear inside, brightest where the + * clusters are densest. Water shading reveals it above a threshold that + * falls as the foam coverage rises, so thin foam shows the densest + * clusters first. Generated once per context. + * @internal + */ +export function waterFoamTexture(ctx: Context3D): BitmapTexture2D { + let texture = cache.get(ctx); + if (!texture) { + texture = new BitmapTexture2D(true, ctx); + texture.source = paintFoam(); + cache.set(ctx, texture); + } + return texture; +} + +function paintFoam(): HTMLCanvasElement { + const random = mulberry32(7); + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = SIZE; + const g = canvas.getContext('2d')!; + g.fillStyle = 'black'; + g.fillRect(0, 0, SIZE, SIZE); + + // Where the foam gathers: tileable value noise, three octaves. + const lattice = new Float32Array(32 * 32).map(() => random()); + const cluster = (x: number, y: number) => { + let v = 0, amp = 0.5, freq = 4; + for (let o = 0; o < 3; o++) { + v += amp * tileNoise(lattice, 32, x / SIZE * freq, y / SIZE * freq, freq); + amp *= 0.5; + freq *= 2; + } + return v / 0.875; + }; + + g.globalCompositeOperation = 'lighter'; + let placed = 0; + for (let tries = 0; placed < BUBBLES && tries < BUBBLES * 20; tries++) { + const x = random() * SIZE; + const y = random() * SIZE; + const density = cluster(x, y); + if (random() > density * density * 1.6) continue; + placed++; + // Many small bubbles, few large ones. + const r = 1.2 + 10 * Math.pow(random(), 3); + const bright = 0.25 + 0.6 * density; + // Wrapped copies near the edges keep the texture tileable. + for (const ox of [-SIZE, 0, SIZE]) { + for (const oy of [-SIZE, 0, SIZE]) { + const cx = x + ox, cy = y + oy; + if (cx < -r || cx > SIZE + r || cy < -r || cy > SIZE + r) continue; + const rim = g.createRadialGradient(cx, cy, r * 0.45, cx, cy, r); + rim.addColorStop(0, 'rgba(255,255,255,0)'); + rim.addColorStop(0.75, `rgba(255,255,255,${bright * 0.55})`); + rim.addColorStop(1, 'rgba(255,255,255,0)'); + g.fillStyle = rim; + g.beginPath(); + g.arc(cx, cy, r, 0, Math.PI * 2); + g.fill(); + } + } + } + return canvas; +} + +// Smooth value noise on a periodic lattice of the given period. +function tileNoise(lattice: Float32Array, n: number, x: number, y: number, period: number): number { + const xi = Math.floor(x), yi = Math.floor(y); + const fx = x - xi, fy = y - yi; + const at = (i: number, j: number) => lattice[(((j % period) + period) % period % n) * n + (((i % period) + period) % period % n)]; + const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy); + const top = at(xi, yi) + (at(xi + 1, yi) - at(xi, yi)) * sx; + const bottom = at(xi, yi + 1) + (at(xi + 1, yi + 1) - at(xi, yi + 1)) * sx; + return top + (bottom - top) * sy; +} + +// Small seeded random generator, so every run paints the same foam. +function mulberry32(seed: number): () => number { + return () => { + seed |= 0; + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} diff --git a/src/components/renderer/WaterFootprint.ts b/src/components/renderer/WaterFootprint.ts new file mode 100644 index 000000000..5481c68b0 --- /dev/null +++ b/src/components/renderer/WaterFootprint.ts @@ -0,0 +1,193 @@ +import { GeometryBase } from '../../core/geometry/GeometryBase'; +import { VertexAttributeName } from '../../core/geometry/VertexAttributeName'; + +/** Texels of the footprint mask along the longer side. */ +const MASK_SIZE = 1024; + +/** + * Where a {@link WaterRenderer} with a custom surface mesh has water: the + * mesh's triangles projected onto its local xz plane, rasterized once into + * a mask over their bounds. Point tests on the CPU read the mask; the GPU + * gets the same mask as a texture. + * @internal + */ +export class WaterFootprint { + /** Local xz bounds: min x, min z, max x, max z. */ + public readonly bounds: [number, number, number, number]; + /** Mask size in texels; rows run along local z. */ + public readonly maskWidth: number; + public readonly maskHeight: number; + /** Number of triangles rasterized. */ + public readonly triangleCount: number; + + /** 255 on water. */ + private _mask: Uint8Array; + private _maskTexture: GPUTexture | null = null; + private _maskView: GPUTextureView | null = null; + + constructor(geometry: GeometryBase) { + const pos = geometry.getAttribute(VertexAttributeName.position).data as Float32Array; + const idx = geometry.getAttribute(VertexAttributeName.indices).data as Uint16Array | Uint32Array; + this.triangleCount = Math.floor(idx.length / 3); + let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity; + for (let i = 0; i < this.triangleCount * 3; i++) { + const v = idx[i] * 3; + minX = Math.min(minX, pos[v]); maxX = Math.max(maxX, pos[v]); + minZ = Math.min(minZ, pos[v + 2]); maxZ = Math.max(maxZ, pos[v + 2]); + } + if (this.triangleCount === 0) minX = minZ = maxX = maxZ = 0; + this.bounds = [minX, minZ, maxX, maxZ]; + const w = Math.max(maxX - minX, 1e-6), h = Math.max(maxZ - minZ, 1e-6); + this.maskWidth = Math.max(16, Math.round(MASK_SIZE * Math.min(1, w / h))); + this.maskHeight = Math.max(16, Math.round(MASK_SIZE * Math.min(1, h / w))); + this._mask = new Uint8Array(this.maskWidth * this.maskHeight); + this._rasterize(pos, idx); + } + + /** True when local (x, z) lies on the mesh, to the precision of the mask. */ + public contains(x: number, z: number): boolean { + const [minX, minZ, maxX, maxZ] = this.bounds; + if (x < minX || x > maxX || z < minZ || z > maxZ) return false; + const i = Math.min(this.maskWidth - 1, Math.floor((x - minX) / Math.max(maxX - minX, 1e-6) * this.maskWidth)); + const j = Math.min(this.maskHeight - 1, Math.floor((z - minZ) / Math.max(maxZ - minZ, 1e-6) * this.maskHeight)); + return this._mask[j * this.maskWidth + i] > 0; + } + + /** The mask as an r8unorm texture, uploaded on first use. */ + public getMaskView(device: GPUDevice): GPUTextureView { + if (!this._maskView) { + this._maskTexture = device.createTexture({ + label: 'WaterFootprint:Mask', + size: [this.maskWidth, this.maskHeight, 1], + format: 'r8unorm', + usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, + }); + device.queue.writeTexture({ texture: this._maskTexture }, this._mask, + { bytesPerRow: this.maskWidth }, [this.maskWidth, this.maskHeight, 1]); + this._maskView = this._maskTexture.createView(); + } + return this._maskView; + } + + public destroy(): void { + this._maskTexture?.destroy(); + this._maskTexture = null; + this._maskView = null; + } + + // Marks every texel whose center lies in a triangle (edges included, so neighbours leave no cracks). + private _rasterize(pos: Float32Array, idx: Uint16Array | Uint32Array): void { + const [minX, minZ, maxX, maxZ] = this.bounds; + const W = this.maskWidth, H = this.maskHeight; + const sx = W / Math.max(maxX - minX, 1e-6), sz = H / Math.max(maxZ - minZ, 1e-6); + const mask = this._mask; + for (let t = 0; t < this.triangleCount; t++) { + // Corners in texel units, texel centers at integers. + const a = idx[t * 3] * 3, b = idx[t * 3 + 1] * 3, c = idx[t * 3 + 2] * 3; + const ax = (pos[a] - minX) * sx - 0.5, az = (pos[a + 2] - minZ) * sz - 0.5; + const bx = (pos[b] - minX) * sx - 0.5, bz = (pos[b + 2] - minZ) * sz - 0.5; + const cx = (pos[c] - minX) * sx - 0.5, cz = (pos[c + 2] - minZ) * sz - 0.5; + const area = (bx - ax) * (cz - az) - (bz - az) * (cx - ax); + if (area === 0) continue; + const sign = area > 0 ? 1 : -1; + const i0 = Math.max(0, Math.ceil(Math.min(ax, bx, cx))), i1 = Math.min(W - 1, Math.floor(Math.max(ax, bx, cx))); + const j0 = Math.max(0, Math.ceil(Math.min(az, bz, cz))), j1 = Math.min(H - 1, Math.floor(Math.max(az, bz, cz))); + for (let j = j0; j <= j1; j++) { + for (let i = i0; i <= i1; i++) { + const e0 = ((bx - ax) * (j - az) - (bz - az) * (i - ax)) * sign; + const e1 = ((cx - bx) * (j - bz) - (cz - bz) * (i - bx)) * sign; + const e2 = ((ax - cx) * (j - cz) - (az - cz) * (i - cx)) * sign; + if (e0 >= 0 && e1 >= 0 && e2 >= 0) mask[j * W + i] = 255; + } + } + } + } +} + +/** + * WGSL for the passes that test points against water footprints. Expects + * `p.waters[i]` with `invWorld: mat4x4f`, `bounds: vec4f` (local min x, min z, + * max x, max z) and `mask: vec4f` (x = 1 when the footprint has a mask), and + * binds four masks and a sampler from `firstBinding` on in group 0. + * @internal + */ +export function waterFootprintWGSL(firstBinding: number): string { + return /* wgsl */` +@group(0) @binding(${firstBinding}) var footprintMask0: texture_2d; +@group(0) @binding(${firstBinding + 1}) var footprintMask1: texture_2d; +@group(0) @binding(${firstBinding + 2}) var footprintMask2: texture_2d; +@group(0) @binding(${firstBinding + 3}) var footprintMask3: texture_2d; +@group(0) @binding(${firstBinding + 4}) var footprintSampler: sampler; + +fn footprintMask(i: u32, uv: vec2f) -> f32 { + switch (i) { + case 0u: { return textureSampleLevel(footprintMask0, footprintSampler, uv, 0.0).r; } + case 1u: { return textureSampleLevel(footprintMask1, footprintSampler, uv, 0.0).r; } + case 2u: { return textureSampleLevel(footprintMask2, footprintSampler, uv, 0.0).r; } + default: { return textureSampleLevel(footprintMask3, footprintSampler, uv, 0.0).r; } + } +} + +// True when the world point is above or below water i's footprint. +fn insideFootprint(i: u32, world: vec3f) -> bool { + let local = (p.waters[i].invWorld * vec4f(world, 1.0)).xz; + let b = p.waters[i].bounds; + if (any(local < b.xy) || any(local > b.zw)) { + return false; + } + if (p.waters[i].mask.x < 0.5) { + return true; + } + return footprintMask(i, (local - b.xy) / max(b.zw - b.xy, vec2f(1e-6))) > 0.5; +} +`; +} + +/** + * Bind group entries for {@link waterFootprintWGSL}: each water's mask, or + * a 1x1 placeholder for waters without one. + * @internal + */ +export class WaterFootprintBindings { + private _placeholder: GPUTexture | null = null; + private _placeholderView: GPUTextureView | null = null; + private _sampler: GPUSampler | null = null; + + /** Layout entries, for the fragment stage, from `firstBinding` on. */ + public static layoutEntries(firstBinding: number): GPUBindGroupLayoutEntry[] { + const entries: GPUBindGroupLayoutEntry[] = []; + for (let i = 0; i < 4; i++) { + entries.push({ binding: firstBinding + i, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } }); + } + entries.push({ binding: firstBinding + 4, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } }); + return entries; + } + + /** Entries for up to four footprints, in the order the waters were written to the uniforms. */ + public entries(device: GPUDevice, footprints: (WaterFootprint | null)[], firstBinding: number): GPUBindGroupEntry[] { + if (!this._placeholder) { + this._placeholder = device.createTexture({ + label: 'WaterFootprint:Placeholder', + size: [1, 1, 1], + format: 'r8unorm', + usage: GPUTextureUsage.TEXTURE_BINDING, + }); + this._placeholderView = this._placeholder.createView(); + this._sampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear' }); + } + const entries: GPUBindGroupEntry[] = []; + for (let i = 0; i < 4; i++) { + const view = footprints[i]?.getMaskView(device) ?? this._placeholderView!; + entries.push({ binding: firstBinding + i, resource: view }); + } + entries.push({ binding: firstBinding + 4, resource: this._sampler! }); + return entries; + } + + public destroy(): void { + this._placeholder?.destroy(); + this._placeholder = null; + this._placeholderView = null; + this._sampler = null; + } +} diff --git a/src/components/renderer/WaterRenderer.ts b/src/components/renderer/WaterRenderer.ts new file mode 100644 index 000000000..8fc9d145a --- /dev/null +++ b/src/components/renderer/WaterRenderer.ts @@ -0,0 +1,525 @@ +import { GeometryBase } from '../../core/geometry/GeometryBase'; +import { View3D } from '../../core/View3D'; +import { Context3D } from '../../gfx/graphics/webGpu/Context3D'; +import { Texture } from '../../gfx/graphics/webGpu/core/texture/Texture'; +import { RTResourceMap } from '../../gfx/renderJob/frame/RTResourceMap'; +import { SCENE_LINEAR_DEPTH } from '../../gfx/renderJob/graph/passes/SceneLinearDepthPass'; +import { RendererMask } from '../../gfx/renderJob/passRenderer/state/RendererMask'; +import { WATER_MAX_WAVES, WaterMaterial } from '../../materials/WaterMaterial'; +import { Matrix4 } from '../../math/Matrix4'; +import { Vector2 } from '../../math/Vector2'; +import { Vector3 } from '../../math/Vector3'; +import { PlaneGeometry } from '../../shape/PlaneGeometry'; +import { Time } from '../../util/Time'; +import { MeshRenderer } from './MeshRenderer'; +import { WaterFootprint } from './WaterFootprint'; +import { WATER_FFT_MAX_QUERIES, WaterFFT } from './WaterFFT'; +import { waterFoamTexture } from './WaterFoamTexture'; +import { WATER_MAX_RIPPLES_PER_FRAME, WaterRipples } from './WaterRipples'; +import { WaterSpectrum } from './WaterSpectrum'; + +/** + * One Gerstner wave of a {@link WaterRenderer}. + * @group Components + */ +export type GerstnerWave = { + /** Direction of travel in the xz plane. */ + direction: Vector2; + /** Crest-to-crest distance in world units. */ + wavelength: number; + /** 0 to 1; the sum over all waves should stay below 1 to avoid looping crests. */ + steepness: number; +}; + +const GRAVITY = 9.81; + +/** + * Water surface: a grid on the owner's xz plane displaced by Gerstner + * waves and shaded by {@link WaterMaterial} (refraction, absorption, + * reflection, sun highlight). + * + * Waves are up to eight Gerstner waves ({@link waves}) plus, for open + * water, a wind-driven sea simulated with FFTs ({@link spectrum}). + * + * The surface is a rectangle ({@link width} by {@link length}) or any flat + * mesh in the owner's xz plane ({@link surfaceGeometry}), e.g. a round + * pond. The waves are evaluated in world space, so several water objects + * line up; {@link getHeight} returns the same surface on the CPU. The owner + * may be scaled and rotated about y; the surface stays horizontal and the + * waves keep their world directions. + * + * @group Components + */ +export class WaterRenderer extends MeshRenderer { + /** Up to {@link WATER_MAX_WAVES} waves; edit in place or reassign. */ + public waves: GerstnerWave[] = [ + { direction: new Vector2(1, 0.3), wavelength: 8, steepness: 0.18 }, + { direction: new Vector2(0.4, 1), wavelength: 5, steepness: 0.14 }, + { direction: new Vector2(-0.7, 0.6), wavelength: 3, steepness: 0.1 }, + { direction: new Vector2(0.2, -1), wavelength: 1.7, steepness: 0.06 }, + ]; + /** Wave animation speed; 0 freezes the surface. */ + public timeScale: number = 1; + /** Sunlight caustics on everything under the surface (CausticsPass, `setting.render.water`). */ + public caustics: boolean = true; + /** Strength of the caustics. */ + public causticsIntensity: number = 0.6; + /** + * Base wavelength in world units of the fine ripples on top of the waves. + * Too small to displace the mesh, they bend the surface normal per pixel + * and focus the sunlight into the caustics. + */ + public detailScale: number = 1.8; + /** + * How much the fine ripples bend the surface normal (0 to 1): 1 is the + * slope that focuses the caustics, which always use all of it; lower keeps + * the view through calm water clearer. + */ + public detailStrength: number = 0.35; + /** Speed of the interactive ripples ({@link addRipple}) in world units per second. */ + public rippleSpeed: number = 1.2; + /** Fraction of the ripples' motion lost per second. */ + public rippleDamping: number = 0.3; + + private _width: number = 10; + private _length: number = 10; + private _resolution: number = 128; + private _time: number = 0; + private _waterMaterial!: WaterMaterial; + private _pyramid: Texture | null = null; + private _sceneDepth: Texture | null | undefined = undefined; + /** Last wave values sent to the material, to skip unchanged uploads. */ + private _sentWaves: number[] = []; + private _invWorld!: Matrix4; + private _surface: GeometryBase | null = null; + private _footprint: WaterFootprint | null = null; + private _rippleResolution: number = 256; + private _rippleArea: number | null = null; + private _waveFadeDistance: number = 80; + private _ripples: WaterRipples | null = null; + /** Ripples waiting for the simulation: local x, local z, strength, radius. */ + private _rippleQueue: number[] = []; + private _simulationFrame: number = -1; + private _spectrum: WaterSpectrum | null = null; + private _foamTextureSet = false; + /** World x, z pairs whose FFT height was asked for this frame. */ + private _heightQueries: number[] = []; + private _fft: WaterFFT | null = null; + private _ctx: Context3D | null = null; + + public init(param?: any): void { + super.init(param); + this._invWorld = new Matrix4(); + this._waterMaterial = new WaterMaterial(); + this._waterMaterial.waveFadeDistance = this._waveFadeDistance; + this.material = this._waterMaterial; + this._rebuildGeometry(); + // The default depth, shadow and reflection passes would draw the undisplaced grid: + // a flat depth prepass would hide everything below the waves. + this.addMask(RendererMask.IgnoreDepthPass); + this.castShadow = false; + this.castReflection = false; + this._pushWaves(); + } + + /** Surface material, for shading parameters. */ + public get waterMaterial(): WaterMaterial { + return this._waterMaterial; + } + + /** Size of the default rectangle along local x; the owner's scale applies. */ + public get width(): number { + return this._width; + } + public set width(value: number) { + this._width = value; + this._rebuildGeometry(); + if (!this._surface) this._resetRipples(); + } + + /** Size of the default rectangle along local z; the owner's scale applies. */ + public get length(): number { + return this._length; + } + public set length(value: number) { + this._length = value; + this._rebuildGeometry(); + if (!this._surface) this._resetRipples(); + } + + /** Grid segments of the default rectangle along its longer side; the waves need a few vertices per shortest wavelength. */ + public get resolution(): number { + return this._resolution; + } + public set resolution(value: number) { + this._resolution = Math.max(1, Math.floor(value)); + this._rebuildGeometry(); + } + + /** + * Custom surface mesh: flat, in the owner's local xz plane (its y is + * ignored), indexed, and fine enough for the waves. The water, + * underwater view and caustics all follow its outline. Null restores + * the rectangle. + */ + public get surfaceGeometry(): GeometryBase | null { + return this._surface; + } + public set surfaceGeometry(value: GeometryBase | null) { + this._footprint?.destroy(); + this._surface = value; + this._footprint = value ? new WaterFootprint(value) : null; + if (value) { + this.geometry = value; + } else { + this._rebuildGeometry(); + } + this._resetRipples(); + } + + /** + * Distance from the camera, in wavelengths, at which each wave has faded + * out of the surface (from half of it on), so waves too short for the mesh + * or the screen there do not alias. The default suits an even mesh; lower + * it for a mesh that coarsens with distance. 0 keeps every wave at any + * distance. Visual only: {@link getHeight} keeps every wave. + */ + public get waveFadeDistance(): number { + return this._waveFadeDistance; + } + public set waveFadeDistance(value: number) { + this._waveFadeDistance = Math.max(0, value); + if (this._waterMaterial) this._waterMaterial.waveFadeDistance = this._waveFadeDistance; + } + + /** Ripple grid cells along the longer side of the water; changing it clears the ripples. */ + public get rippleResolution(): number { + return this._rippleResolution; + } + public set rippleResolution(value: number) { + this._rippleResolution = Math.max(8, Math.floor(value)); + this._resetRipples(); + } + + /** + * Side, in local units, of the square around the water's origin where + * ripples are simulated, all of it taken as water; null covers the whole + * surface. For water too large for one grid to resolve ripples, such as + * an ocean. Changing it clears the ripples. + */ + public get rippleArea(): number | null { + return this._rippleArea; + } + public set rippleArea(value: number | null) { + this._rippleArea = value && value > 0 ? value : null; + this._resetRipples(); + } + + /** @internal Local xz bounds of the ripple grid: min x, min z, max x, max z. */ + public get rippleBounds(): [number, number, number, number] { + const a = this._rippleArea; + return a ? [-a / 2, -a / 2, a / 2, a / 2] : this.footprintBounds; + } + + /** + * Starts a ripple at world (x, z): the surface there is pushed down, as by + * something striking it, and a ring spreads out, reflecting off the edge + * of the water. Pointer + * input and objects entering or moving through the water all start + * ripples this way. Points off the water are ignored; at most + * {@link WATER_MAX_RIPPLES_PER_FRAME} start per frame. Needs + * `setting.render.water`. + * @param strength depth of the crater at its center, in world units + * @param radius radius of the pushed area, in world units + */ + public addRipple(x: number, z: number, strength: number = 0.05, radius: number = 0.2): void { + if (!this.containsXZ(x, z) || this._rippleQueue.length >= WATER_MAX_RIPPLES_PER_FRAME * 4) return; + const m = this.invWorldMatrix.rawData; + const y = this.baseHeight; + const lx = m[0] * x + m[4] * y + m[8] * z + m[12]; + const lz = m[2] * x + m[6] * y + m[10] * z + m[14]; + const [minX, minZ, maxX, maxZ] = this.rippleBounds; + if (lx < minX || lx > maxX || lz < minZ || lz > maxZ) return; + this._rippleQueue.push(lx, lz, strength, radius); + } + + /** + * FFT ocean waves added to the Gerstner waves, from wind over open water; + * null for none. Needs `setting.render.water`. + */ + public get spectrum(): WaterSpectrum | null { + return this._spectrum; + } + public set spectrum(value: WaterSpectrum | null) { + this._spectrum = value; + if (!value) this._resetFFT(); + } + + /** @internal The FFT simulation of {@link spectrum}, once started. */ + public get fft(): WaterFFT | null { + return this._fft; + } + + /** @internal Starts reading back what the simulation computed for the CPU, once submitted. */ + public afterSimulationSubmit(): void { + this._fft?.readBack(); + } + + /** @internal True when there are FFT waves or ripples to advance. */ + public get hasSimulation(): boolean { + return !!this._fft || !!this._ripples; + } + + /** @internal Advances the FFT waves and the ripples by dt seconds (once per frame however many views draw). */ + public stepSimulation(command: GPUCommandEncoder, dt: number): void { + if (Time.frame === this._simulationFrame) return; + this._simulationFrame = Time.frame; + if (this._fft && this._spectrum) { + this._fft.step(command, this._spectrum, this._time, dt * this.timeScale); + this._fft.queryHeights(command, this._heightQueries); + this._heightQueries.length = 0; + } + const ripples = this._ripples; + if (!ripples) return; + const w = this.transform.worldMatrix.rawData; + const [minX, minZ, maxX, maxZ] = ripples.bounds; + const cell: [number, number] = [ + (maxX - minX) / ripples.gridWidth * Math.hypot(w[0], w[1], w[2]), + (maxZ - minZ) / ripples.gridHeight * Math.hypot(w[8], w[9], w[10]), + ]; + // The mask covers the footprint's bounds; a ripple area is all water. + const mask = this._footprint && this._ctx && !this._rippleArea ? this._footprint.getMaskView(this._ctx.device as GPUDevice) : null; + ripples.step(command, dt * this.timeScale, cell, this.rippleSpeed, this.rippleDamping, mask); + } + + /** @internal Current ripple heights (r, over {@link footprintBounds}), or null before the first ripple. */ + public get rippleView(): GPUTextureView | null { + return this._ripples ? this._ripples.heightTexture.getGPUView() as GPUTextureView : null; + } + + /** @internal True once a ripple has started the simulation. */ + public get hasRipples(): boolean { + return !!this._ripples; + } + + /** @internal Outline of a custom surface mesh; null for the rectangle. */ + public get footprint(): WaterFootprint | null { + return this._footprint; + } + + /** @internal Local xz bounds of the surface: min x, min z, max x, max z. */ + public get footprintBounds(): [number, number, number, number] { + if (this._footprint) return this._footprint.bounds; + return [-this._width / 2, -this._length / 2, this._width / 2, this._length / 2]; + } + + /** Wave phase time in seconds. */ + public get time(): number { + return this._time; + } + public set time(value: number) { + this._time = value; + } + + public onUpdate(view?: View3D): void { + this._time += Time.delta * 0.001 * this.timeScale; + this._waterMaterial.waveTime = this._time; + this._waterMaterial.baseHeight = this.baseHeight; + this._waterMaterial.detailScale = Math.max(this.detailScale, 1e-3); + this._waterMaterial.detailStrength = this.detailStrength; + this._waterMaterial.fftCrest = this._spectrum ? this._significantHeight(this._spectrum) : 0; + this._pushWaves(); + this._bindPyramid(view); + this._updateRipples(view); + } + + /** True when the point is inside the water's xz footprint and below the surface. */ + public isUnderwater(point: Vector3): boolean { + if (!this.containsXZ(point.x, point.z)) return false; + return point.y < this.getHeight(point.x, point.z); + } + + /** + * True when world (x, z) lies inside the water's footprint. + * @param margin grows the footprint by this many world units on each side + */ + public containsXZ(x: number, z: number, margin: number = 0): boolean { + if (!this.transform || !this._invWorld) return false; + const m = this.invWorldMatrix.rawData; + const y = this.baseHeight; + const lx = m[0] * x + m[4] * y + m[8] * z + m[12]; + const lz = m[2] * x + m[6] * y + m[10] * z + m[14]; + // Margin in local units along x and z. + const mx = margin * Math.hypot(m[0], m[4], m[8]); + const mz = margin * Math.hypot(m[2], m[6], m[10]); + const [minX, minZ, maxX, maxZ] = this.footprintBounds; + if (lx < minX - mx || lx > maxX + mx || lz < minZ - mz || lz > maxZ + mz) return false; + const f = this._footprint; + if (!f) return true; + return f.contains(lx, lz) || f.contains(lx - mx, lz) || f.contains(lx + mx, lz) + || f.contains(lx, lz - mz) || f.contains(lx, lz + mz); + } + + /** @internal World to local space, where the footprint is |x| <= width / 2, |z| <= length / 2. */ + public get invWorldMatrix(): Matrix4 { + this._invWorld.rawData.set(this.transform.worldMatrix.rawData); + return this._invWorld.invert(); + } + + /** @internal How high above {@link baseHeight} the waves can lift the surface. */ + public get waveReach(): number { + let reach = 0; + for (let i = 0; i < Math.min(this.waves.length, WATER_MAX_WAVES); i++) { + const w = this.waves[i]; + if (w && w.wavelength > 0) reach += w.steepness * w.wavelength / (2 * Math.PI); + } + // The highest FFT crests rise about the significant wave height. + return reach + (this._spectrum ? this._significantHeight(this._spectrum) : 0); + } + + /** @internal World y of the undisplaced surface. */ + public get baseHeight(): number { + return this.transform?.worldPosition.y ?? 0; + } + + /** @internal Wave i as (direction.x, direction.z, steepness, wavelength), zeros when unused. */ + public waveVector(i: number): [number, number, number, number] { + const w = i < WATER_MAX_WAVES ? this.waves[i] : undefined; + return w ? [w.direction.x, w.direction.y, w.steepness, w.wavelength] : [0, 0, 0, 0]; + } + + /** + * World-space height of the surface above (x, z) at the current time. + * Gerstner waves also move points sideways, so the undisplaced position + * whose displaced xz lands on (x, z) is found by fixed-point iteration. + * The FFT waves ({@link spectrum}) are computed on the GPU: asking for a + * point queues it, and their part of the height comes from the nearest + * point asked for in an earlier frame, a frame or two old (none until + * then). Ask every frame for points that move. + */ + public getHeight(x: number, z: number): number { + const baseY = this.baseHeight; + let px = x; + let pz = z; + for (let i = 0; i < 4; i++) { + const d = this._displacement(px, pz); + px = x - d[0]; + pz = z - d[2]; + } + let height = baseY + this._displacement(px, pz)[1]; + if (this._fft) { + if (this._heightQueries.length < WATER_FFT_MAX_QUERIES * 2) this._heightQueries.push(x, z); + height += this._fft.heightAt(x, z) ?? 0; + } + return height; + } + + private _displacement(x: number, z: number): [number, number, number] { + let dx = 0, dy = 0, dz = 0; + for (let i = 0; i < Math.min(this.waves.length, WATER_MAX_WAVES); i++) { + const w = this.waves[i]; + if (!w || w.wavelength <= 0) continue; + const len = Math.hypot(w.direction.x, w.direction.y) || 1; + const ux = w.direction.x / len, uz = w.direction.y / len; + const k = (2 * Math.PI) / w.wavelength; + const c = Math.sqrt(GRAVITY / k); + const f = k * (ux * x + uz * z - c * this._time); + const a = w.steepness / k; + dx += ux * a * Math.cos(f); + dy += a * Math.sin(f); + dz += uz * a * Math.cos(f); + } + return [dx, dy, dz]; + } + + private _pushWaves(): void { + for (let i = 0; i < WATER_MAX_WAVES; i++) { + const v = this.waveVector(i); + const o = i * 4; + if (this._sentWaves[o] === v[0] && this._sentWaves[o + 1] === v[1] + && this._sentWaves[o + 2] === v[2] && this._sentWaves[o + 3] === v[3]) continue; + this._waterMaterial.setWave(i, v[0], v[1], v[2], v[3]); + this._sentWaves.splice(o, 4, ...v); + } + } + + // The pyramid and the scene depth are created with the render graph and can be replaced (e.g. on resize). + private _bindPyramid(view?: View3D): void { + const ctx = view?.engine3D?.context3D; + if (!ctx) return; + const pyramid = RTResourceMap.getTexture(ctx, '_SceneColorPyramid') as Texture; + if (pyramid && pyramid !== this._pyramid) { + this._pyramid = pyramid; + this._waterMaterial.sceneColorPyramid = pyramid; + } + // Present only with setting.render.water (SceneLinearDepthPass). + const depth = (RTResourceMap.getTexture(ctx, SCENE_LINEAR_DEPTH) as Texture) ?? null; + if (depth !== this._sceneDepth) { + this._sceneDepth = depth; + this._waterMaterial.sceneLinearDepth = depth; + } + } + + public destroy(force?: boolean): void { + this._resetRipples(); + this._resetFFT(); + this._footprint?.destroy(); + this._footprint = null; + super.destroy(force); + } + + // The simulation starts with the first ripple and covers the current footprint bounds. + private _updateRipples(view?: View3D): void { + this._ctx = view?.engine3D?.context3D ?? this._ctx; + // The built-in foam texture once the context is known, unless one was set. + if (this._ctx && !this._foamTextureSet) { + this._foamTextureSet = true; + if (!this._waterMaterial.foamTexture) this._waterMaterial.foamTexture = waterFoamTexture(this._ctx); + } + if (this._spectrum && !this._fft && this._ctx) { + this._fft = new WaterFFT(this._ctx); + this._waterMaterial.fft = this._fft; + } + if (!this._ripples && this._rippleQueue.length > 0 && this._ctx) { + this._ripples = new WaterRipples(this._ctx, [...this.rippleBounds], this._rippleResolution); + this._waterMaterial.rippleMap = this._ripples.heightTexture; + } + if (!this._ripples) return; + const q = this._rippleQueue; + for (let i = 0; i < q.length; i += 4) this._ripples.add(q[i], q[i + 1], q[i + 2], q[i + 3]); + q.length = 0; + const m = this.invWorldMatrix.rawData; + const y = this.baseHeight; + this._waterMaterial.setRippleTransform( + [m[0], m[8], m[4] * y + m[12]], + [m[2], m[10], m[6] * y + m[14]], + this._ripples.bounds); + } + + // Significant wave height of a fetch-limited JONSWAP sea, 0.0016 U sqrt(F / g). + private _significantHeight(spectrum: WaterSpectrum): number { + return 0.0016 * spectrum.windSpeed * Math.sqrt(spectrum.fetch / GRAVITY) * spectrum.amplitude; + } + + private _resetFFT(): void { + if (!this._fft) return; + this._fft.destroy(); + this._fft = null; + this._waterMaterial.fft = null; + } + + private _resetRipples(): void { + if (!this._ripples) return; + this._ripples.destroy(); + this._ripples = null; + this._waterMaterial.rippleMap = null; + } + + private _rebuildGeometry(): void { + if (!this._waterMaterial || this._surface) return; + const longer = Math.max(this._width, this._length); + const segW = Math.max(1, Math.round(this._resolution * this._width / longer)); + const segL = Math.max(1, Math.round(this._resolution * this._length / longer)); + this.geometry = new PlaneGeometry(this._width, this._length, segW, segL); + } +} diff --git a/src/components/renderer/WaterRipples.ts b/src/components/renderer/WaterRipples.ts new file mode 100644 index 000000000..9cdaa20d5 --- /dev/null +++ b/src/components/renderer/WaterRipples.ts @@ -0,0 +1,274 @@ +import { Context3D } from '../../gfx/graphics/webGpu/Context3D'; +import { GPUTextureFormat } from '../../gfx/graphics/webGpu/WebGPUConst'; +import { VirtualTexture } from '../../textures/VirtualTexture'; + +/** Ripples started per frame; more are dropped until the next frame. */ +export const WATER_MAX_RIPPLES_PER_FRAME = 32; +/** See RIPPLE_WGSL for the layout. */ +const UNIFORM_FLOATS = 12 + WATER_MAX_RIPPLES_PER_FRAME * 4; +/** Upper bound of simulation steps per frame. */ +const MAX_STEPS = 12; +/** + * Dispersion length in world units: waves shorter than about 2 pi times it + * travel faster, so a ripple trails a few rings rather than a single pulse. + * Longer spreads the energy so fast that the rings fade within a second. + */ +const DISPERSION_LENGTH = 0.05; + +/** + * Interactive ripples of a {@link WaterRenderer}: a height field over the + * water's local xz bounds, advanced on the GPU with the wave equation plus + * a fourth-order term, d2h/dt2 = c^2 lap(h) - c^2 l^2 lap(lap(h)), so that + * shorter waves run ahead (dispersion length l). + * A ripple starts as a push, like something striking the water: down at + * the center and up around it, adding no volume. A crater opens and a ring + * travels out, leaving the center level; a net push would leave a slowly + * filling hollow instead, and a pressed-in dip springs up into a peak. + * Ripples interfere, reflect off the edge of the water and die out. + * + * The state is two rgba32float textures used in turn (r = height, + * g = vertical velocity); an even number of steps per frame leaves the + * current state in {@link heightTexture}. + * @internal + */ +export class WaterRipples { + /** Grid cells along local x and z. */ + public readonly gridWidth: number; + public readonly gridHeight: number; + + private _ctx: Context3D; + private _textures: VirtualTexture[]; + private _pipeline: GPUComputePipeline | null = null; + private _layout: GPUBindGroupLayout | null = null; + private _uniform: GPUBuffer | null = null; + private _sampler: GPUSampler | null = null; + private _placeholder: GPUTexture | null = null; + private _uniformData = new Float32Array(UNIFORM_FLOATS); + private _pending: number[] = []; + + /** + * @param bounds local xz bounds the grid covers: min x, min z, max x, max z + * @param resolution cells along the longer side + */ + constructor(ctx: Context3D, public readonly bounds: [number, number, number, number], resolution: number) { + this._ctx = ctx; + const w = Math.max(bounds[2] - bounds[0], 1e-6); + const h = Math.max(bounds[3] - bounds[1], 1e-6); + this.gridWidth = Math.max(8, Math.round(resolution * Math.min(1, w / h))); + this.gridHeight = Math.max(8, Math.round(resolution * Math.min(1, h / w))); + const usage = GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC; + this._textures = [0, 1].map(() => { + const t = new VirtualTexture(this.gridWidth, this.gridHeight, GPUTextureFormat.rgba32float, false, usage, 1, 0, 1, ctx); + // rgba32float is not filterable; read with textureLoad. + t.textureBindingLayout.sampleType = 'unfilterable-float'; + return t; + }); + } + + /** Current state (r = height above the surface in world units), for sampling. */ + public get heightTexture(): VirtualTexture { + return this._textures[0]; + } + + /** + * Queues a ripple for the next step. + * @param x local x + * @param z local z + * @param strength depth of the crater at the center, in world units + * @param radius radius of the pushed area, in world units + */ + public add(x: number, z: number, strength: number, radius: number): void { + if (this._pending.length >= WATER_MAX_RIPPLES_PER_FRAME * 4) return; + const [minX, minZ, maxX, maxZ] = this.bounds; + this._pending.push( + (x - minX) / (maxX - minX) * this.gridWidth, + (z - minZ) / (maxZ - minZ) * this.gridHeight, + strength, radius); + } + + /** + * Advances the simulation by dt seconds. + * @param cellSize world size of a cell along local x and z + * @param speed wave speed in world units per second + * @param damping fraction of the motion lost per second + * @param mask footprint mask over the bounds, or null when the whole grid is water + */ + public step(command: GPUCommandEncoder, dt: number, cellSize: [number, number], speed: number, damping: number, mask: GPUTextureView | null): void { + const device = this._ctx.device as GPUDevice; + if (!this._pipeline) this._createPipeline(device); + dt = Math.min(Math.max(dt, 0), 1 / 30); + // Stable while step * highest frequency < 2; keep to half of that. The highest + // frequency is sqrt(c^2 * L + beta * L^2), L the largest eigenvalue of the grid Laplacian. + const beta = speed * speed * DISPERSION_LENGTH * DISPERSION_LENGTH; + const L = 4 / (cellSize[0] * cellSize[0]) + 4 / (cellSize[1] * cellSize[1]); + const maxStep = 1 / Math.sqrt(speed * speed * L + beta * L * L); + // An even count ends in texture 0. + let steps = Math.ceil(dt / maxStep); + steps = Math.min(MAX_STEPS, Math.max(2, steps + (steps & 1))); + const h = dt / steps; + + const f = this._uniformData; + f[0] = this.gridWidth; f[1] = this.gridHeight; f[2] = cellSize[0]; f[3] = cellSize[1]; + f[4] = speed; f[5] = h; f[6] = Math.exp(-damping * h); f[7] = mask ? 1 : 0; + const count = this._pending.length / 4; + f[8] = count; + f[9] = beta; + f.set(this._pending, 12); + this._pending.length = 0; + + const maskView = mask ?? this._placeholder!.createView(); + const groupsX = Math.ceil(this.gridWidth / 8), groupsY = Math.ceil(this.gridHeight / 8); + for (let s = 0; s < steps; s++) { + // Ripples are pushed in on the first step only. + if (s === 1) f[8] = 0; + if (s <= 1) { + // A buffer per step: writeBuffer lands before the whole command buffer runs. + device.queue.writeBuffer(this._uniform!, s * 256 * 4, f.buffer, f.byteOffset, UNIFORM_FLOATS * 4); + } + const src = this._textures[s & 1].getGPUTexture() as GPUTexture; + const dst = this._textures[(s + 1) & 1].getGPUTexture() as GPUTexture; + const bg = device.createBindGroup({ + layout: this._layout!, + entries: [ + { binding: 0, resource: { buffer: this._uniform!, offset: Math.min(s, 1) * 256 * 4, size: UNIFORM_FLOATS * 4 } }, + { binding: 1, resource: src.createView() }, + { binding: 2, resource: dst.createView() }, + { binding: 3, resource: maskView }, + { binding: 4, resource: this._sampler! }, + ], + }); + const pass = command.beginComputePass({ label: 'WaterRipples' }); + pass.setPipeline(this._pipeline!); + pass.setBindGroup(0, bg); + pass.dispatchWorkgroups(groupsX, groupsY); + pass.end(); + } + } + + public destroy(): void { + this._textures.forEach((t) => t.destroy()); + this._uniform?.destroy(); + this._placeholder?.destroy(); + this._uniform = null; + this._placeholder = null; + this._pipeline = null; + } + + private _createPipeline(device: GPUDevice): void { + // Two uniform slots, 256-float aligned: with ripples (first step) and without. + this._uniform = device.createBuffer({ + label: 'WaterRipples:Uniforms', + size: 2 * 256 * 4, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + this._sampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear' }); + this._placeholder = device.createTexture({ + label: 'WaterRipples:NoMask', + size: [1, 1, 1], + format: 'r8unorm', + usage: GPUTextureUsage.TEXTURE_BINDING, + }); + this._layout = device.createBindGroupLayout({ + label: 'WaterRipples:BGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.COMPUTE, texture: { sampleType: 'unfilterable-float' } }, + { binding: 2, visibility: GPUShaderStage.COMPUTE, storageTexture: { access: 'write-only', format: 'rgba32float' } }, + { binding: 3, visibility: GPUShaderStage.COMPUTE, texture: { sampleType: 'float' } }, + { binding: 4, visibility: GPUShaderStage.COMPUTE, sampler: { type: 'filtering' } }, + ], + }); + this._pipeline = device.createComputePipeline({ + label: 'WaterRipples', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._layout] }), + compute: { module: device.createShaderModule({ label: 'WaterRipples', code: RIPPLE_WGSL }), entryPoint: 'main' }, + }); + } +} + +const RIPPLE_WGSL = /* wgsl */` +struct Params { + // x, y = grid size; z, w = world size of a cell along local x and z + grid: vec4f, + // x = wave speed, y = step seconds, z = damping factor per step, w = 1 when masked + sim: vec4f, + // x = ripples to push in this step, y = dispersion coefficient (c^2 l^2) + info: vec4f, + // cell x, cell z, strength, world radius + ripples: array, +}; + +@group(0) @binding(0) var p: Params; +@group(0) @binding(1) var src: texture_2d; +@group(0) @binding(2) var dst: texture_storage_2d; +@group(0) @binding(3) var mask: texture_2d; +@group(0) @binding(4) var maskSampler: sampler; + +fn isWater(c: vec2i) -> bool { + let size = vec2i(p.grid.xy); + if (any(c < vec2i(0)) || any(c >= size)) { + return false; + } + if (p.sim.w < 0.5) { + return true; + } + return textureSampleLevel(mask, maskSampler, (vec2f(c) + 0.5) / p.grid.xy, 0.0).r > 0.5; +} + +// Height of a neighbour; the edge of the water reflects waves like a wall. +fn neighbour(c: vec2i, center: f32) -> f32 { + if (isWater(c)) { + return textureLoad(src, c, 0).r; + } + return center; +} + +fn laplacian(c: vec2i, h: f32) -> f32 { + let lx = neighbour(c - vec2i(1, 0), h) + neighbour(c + vec2i(1, 0), h) - 2.0 * h; + let lz = neighbour(c - vec2i(0, 1), h) + neighbour(c + vec2i(0, 1), h) - 2.0 * h; + return lx / (p.grid.z * p.grid.z) + lz / (p.grid.w * p.grid.w); +} + +// Laplacian at a neighbour, mirrored from the center across the edge of the water. +fn neighbourLaplacian(c: vec2i, center: f32) -> f32 { + if (isWater(c)) { + return laplacian(c, textureLoad(src, c, 0).r); + } + return center; +} + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3u) { + let c = vec2i(id.xy); + if (any(c >= vec2i(p.grid.xy))) { + return; + } + if (!isWater(c)) { + textureStore(dst, c, vec4f(0.0)); + return; + } + let state = textureLoad(src, c, 0); + var h = state.r; + var v = state.g; + + // Push the queued ripples in: a velocity kick shaped (1 - u^2) exp(-u^2), down at the center + // and up around it with no net volume, reaching about the radius; scaled so the crater it + // opens is about strength deep. + for (var i = 0; i < i32(p.info.x); i++) { + let r = p.ripples[i]; + let u = 2.0 * length((vec2f(c) + 0.5 - r.xy) * p.grid.zw) / r.w; + if (u < 3.5) { + v -= 6.7 * r.z * p.sim.x / r.w * (1.0 - u * u) * exp(-u * u); + } + } + + let lap = laplacian(c, h); + let lap2x = neighbourLaplacian(c - vec2i(1, 0), lap) + neighbourLaplacian(c + vec2i(1, 0), lap) - 2.0 * lap; + let lap2z = neighbourLaplacian(c - vec2i(0, 1), lap) + neighbourLaplacian(c + vec2i(0, 1), lap) - 2.0 * lap; + let lap2 = lap2x / (p.grid.z * p.grid.z) + lap2z / (p.grid.w * p.grid.w); + let dt = p.sim.y; + v = (v + (p.sim.x * p.sim.x * lap - p.info.y * lap2) * dt) * p.sim.z; + h = (h + v * dt) * p.sim.z; + textureStore(dst, c, vec4f(h, v, 0.0, 0.0)); +} +`; diff --git a/src/components/renderer/WaterSpectrum.ts b/src/components/renderer/WaterSpectrum.ts new file mode 100644 index 000000000..34ab3874f --- /dev/null +++ b/src/components/renderer/WaterSpectrum.ts @@ -0,0 +1,35 @@ +import { Vector2 } from '../../math/Vector2'; + +/** + * Wind-driven ocean waves for {@link WaterRenderer.spectrum}: a JONSWAP + * spectrum, spread around the wind direction, simulated with FFTs in + * three cascades from swells hundreds of metres long down to centimetre + * ripples. Adds to the Gerstner waves. + * @group Components + */ +export class WaterSpectrum { + /** Wind speed 10 m above the water, in metres per second. */ + public windSpeed: number = 10; + /** Direction the wind blows toward, in the xz plane. */ + public windDirection: Vector2 = new Vector2(1, 0.3); + /** + * Distance in metres the wind has blown over open water. A short fetch + * gives young, short waves; a long one, a fully developed sea. + */ + public fetch: number = 100000; + /** Wave height scale. */ + public amplitude: number = 1; + /** + * How far the water moves sideways toward the crests: 0 gives rounded + * waves, 1 sharp crests and troughs that whitecaps break from. + */ + public choppiness: number = 1; + /** Random seed of the wave phases. */ + public seed: number = 1; + + /** @internal Key of everything that changes the initial spectrum. */ + public get shapeKey(): string { + const d = this.windDirection; + return `${this.windSpeed}|${d.x}|${d.y}|${this.fetch}|${this.amplitude}|${this.seed}`; + } +} diff --git a/src/components/shape/BoxColliderShape.ts b/src/components/shape/BoxColliderShape.ts index 8b79ce5f6..e624abff8 100644 --- a/src/components/shape/BoxColliderShape.ts +++ b/src/components/shape/BoxColliderShape.ts @@ -11,7 +11,6 @@ import { ColliderShape, ColliderShapeType, HitInfo } from "./ColliderShape"; * @group Collider */ export class BoxColliderShape extends ColliderShape { - private _pickRet: HitInfo; private readonly box: BoundingBox; /** @@ -25,9 +24,11 @@ export class BoxColliderShape extends ColliderShape { /** * @internal - * @param ray - * @param fromMatrix - * @returns + * Entry point of `ray` on the box (exit point when the ray starts + * inside). Point, normal and distance are world space; the local hit + * point is in `localPoint`. + * @param ray world-space ray + * @param fromMatrix local → world matrix */ public rayPick(ray: Ray, fromMatrix: Matrix4): HitInfo { let box = this.box; @@ -39,15 +40,27 @@ export class BoxColliderShape extends ColliderShape { let helpRay = ColliderShape.helpRay.copy(ray); helpRay.applyMatrix(helpMatrix); - let pick = helpRay.intersectBox(this.box, ColliderShape.v3_help_0); - if (pick) { - if (!this._pickRet) { - this._pickRet = { intersectPoint: new Vector3(), distance: 0 }; - } - this._pickRet.intersectPoint = pick; - this._pickRet.distance = Vector3.distance(helpRay.origin, ColliderShape.v3_help_0); - return this._pickRet; + let local = helpRay.intersectBox(box, ColliderShape.v3_help_0); + if (!local) return null; + + // Normal of the face the hit point lies on (the nearest face plane). + const n = BoxColliderShape._normal; + let best = Infinity; + const faces = [ + local.x - box.min.x, box.max.x - local.x, + local.y - box.min.y, box.max.y - local.y, + local.z - box.min.z, box.max.z - local.z, + ]; + let face = 0; + for (let i = 0; i < 6; i++) { + const d = Math.abs(faces[i]); + if (d < best) { best = d; face = i; } } - return null; + const sign = face % 2 === 0 ? -1 : 1; + const axis = face >> 1; + n.set(axis === 0 ? sign : 0, axis === 1 ? sign : 0, axis === 2 ? sign : 0); + return ColliderShape.toWorldHit(ray, fromMatrix, helpMatrix, local, n); } + + private static _normal: Vector3 = new Vector3(); } diff --git a/src/components/shape/ColliderShape.ts b/src/components/shape/ColliderShape.ts index b280e8f82..54736eab1 100644 --- a/src/components/shape/ColliderShape.ts +++ b/src/components/shape/ColliderShape.ts @@ -1,9 +1,41 @@ import { Matrix4 } from "../../math/Matrix4"; import { Ray } from "../../math/Ray"; +import { Vector2 } from "../../math/Vector2"; import { Vector3 } from "../../math/Vector3"; import { ColliderComponent } from "../ColliderComponent"; +import { MeshRaycast } from "../../io/raycast/MeshRaycast"; -export type HitInfo = { intersectPoint?: Vector3; normal?: Vector3; distance: number; collider?: ColliderComponent }; +/** + * Result of `ColliderShape.rayPick`. `intersectPoint`, `normal` and + * `distance` are in world space (distance is measured from the world ray + * origin), so hits from different shapes and transforms can be compared. + */ +export type HitInfo = { + /** Hit point in world space. */ + intersectPoint?: Vector3; + /** Surface normal in world space (unit length). */ + normal?: Vector3; + /** World-space distance from the ray origin to `intersectPoint`. */ + distance: number; + /** Collider that produced the hit (filled in by the caller). */ + collider?: ColliderComponent; + /** Hit point in the collider's local space. */ + localPoint?: Vector3; + /** Mesh colliders: geometric normal of the hit triangle (world space). */ + faceNormal?: Vector3; + /** Mesh colliders: triangle index into the index buffer. */ + faceIndex?: number; + /** Mesh colliders: barycentric weights (w0, w1, w2) of the hit triangle. */ + barycentric?: Vector3; + /** Mesh colliders: interpolated `uv` (TEXCOORD_0), if the geometry has one. */ + uv?: Vector2; + /** Mesh colliders: interpolated `TEXCOORD_1`, if the geometry has one. */ + uv1?: Vector2; + /** Mesh colliders: sub-geometry (material slot) of the hit triangle. */ + subGeometryIndex?: number; + /** Mesh colliders: whether the front (counter-clockwise) side was hit. */ + frontFace?: boolean; +}; export enum ColliderShapeType { None, @@ -98,4 +130,33 @@ export class ColliderShape { return null; } + /** + * Build a world-space `HitInfo` from a local-space hit. + * @param ray the world-space ray that was cast + * @param fromMatrix local → world matrix + * @param invMatrix inverse of `fromMatrix` + * @param localPoint hit point in local space + * @param localNormal surface normal in local space, if known + */ + protected static toWorldHit(ray: Ray, fromMatrix: Matrix4, invMatrix: Matrix4, localPoint: Vector3, localNormal?: Vector3): HitInfo { + const point = Matrix4.transformPoint(fromMatrix, localPoint, new Vector3()); + const hit: HitInfo = { + intersectPoint: point, + localPoint: new Vector3(localPoint.x, localPoint.y, localPoint.z), + distance: Vector3.distance(ray.origin, point), + }; + if (localNormal) { + hit.normal = ColliderShape.transformNormal(invMatrix, localNormal, new Vector3()); + } + return hit; + } + + /** + * Transform a local-space normal to world space with the inverse + * transpose of the local → world matrix. See `MeshRaycast.transformNormal`. + */ + public static transformNormal(invMatrix: Matrix4, n: Vector3, out: Vector3): Vector3 { + return MeshRaycast.transformNormal(invMatrix, n, out); + } + } diff --git a/src/components/shape/MeshColliderShape.ts b/src/components/shape/MeshColliderShape.ts index 80cfcdd5a..2fd290dfe 100644 --- a/src/components/shape/MeshColliderShape.ts +++ b/src/components/shape/MeshColliderShape.ts @@ -1,10 +1,11 @@ import { GeometryBase } from "../../core/geometry/GeometryBase"; -import { VertexAttributeName } from "../../core/geometry/VertexAttributeName"; import { Matrix4 } from "../../math/Matrix4"; import { Ray } from "../../math/Ray"; -import { Triangle } from "../../math/Triangle"; -import { Vector3 } from "../../math/Vector3"; import { ColliderShape, ColliderShapeType, HitInfo } from "./ColliderShape"; +import { MeshRaycast, MeshRaycastOptions, RaycastBVHMode } from "../../io/raycast/MeshRaycast"; +import { RaycastHit } from "../../io/raycast/RaycastHit"; +import { RaycastDeformation } from "../../io/raycast/MeshDeformer"; +import type { MeshRenderer } from "../renderer/MeshRenderer"; /** @@ -13,78 +14,80 @@ import { ColliderShape, ColliderShapeType, HitInfo } from "./ColliderShape"; */ export class MeshColliderShape extends ColliderShape { /** - * meshComponent + * Geometry to pick against. When left unset, `ColliderComponent` uses the + * geometry of the `MeshRenderer` on the same object. */ public mesh: GeometryBase; - private static triangle: Triangle; - private _pickRet: HitInfo; + /** Skip triangles whose front face points away from the ray. */ + public backfaceCulling: boolean = false; - constructor() { - super(); - this._shapeType = ColliderShapeType.Mesh; - } - - public rayPick(ray: Ray, fromMatrix: Matrix4): HitInfo { - if (this.mesh) { - MeshColliderShape.triangle ||= new Triangle(new Vector3(), new Vector3(), new Vector3()); - - let positionAttribute = this.mesh.getAttribute(VertexAttributeName.position); - let indexAttribute = this.mesh.getAttribute(VertexAttributeName.indices); - - let helpMatrix = ColliderShape.helpMatrix; - helpMatrix.copy(fromMatrix).invert(); - - let helpRay = ColliderShape.helpRay.copy(ray); - helpRay.applyMatrix(helpMatrix); - - helpRay.intersectBox(this.mesh.bounds); - let pick = helpRay.intersectBox(this.mesh.bounds, ColliderShape.v3_help_0); - if (!pick) { - return null; - } - - if (indexAttribute && positionAttribute && indexAttribute.data.length > 0) { - - let vertexData = positionAttribute.data; - for (let i = 0, c = indexAttribute.data.length / 3; i < c; i++) { - - let offsetIndex = i * 3; - const i1 = indexAttribute.data[offsetIndex + 0] * 3; - const i2 = indexAttribute.data[offsetIndex + 1] * 3; - const i3 = indexAttribute.data[offsetIndex + 2] * 3; - - let triangle = MeshColliderShape.triangle; - - let p1 = triangle.v1.set(vertexData[i1 + 0], vertexData[i1 + 1], vertexData[i1 + 2]); - let p2 = triangle.v2.set(vertexData[i2 + 0], vertexData[i2 + 1], vertexData[i2 + 2]); - let p3 = triangle.v3.set(vertexData[i3 + 0], vertexData[i3 + 1], vertexData[i3 + 2]); - - triangle.set(p1, p2, p3); + /** + * When to use the geometry's `MeshBVH`. Default `'always'`: the tree is + * built on the first pick and cached per geometry. Use `'auto'` to only + * use a tree built elsewhere (`MeshBVH.build`), `'never'` to always test + * every triangle. + */ + public useBVH: RaycastBVHMode = 'always'; - let pick = helpRay.intersectTriangle(helpRay.origin, helpRay.direction, triangle); + /** Ignore hits farther than this (world units). */ + public maxDistance: number = Infinity; - if (pick) { - this._pickRet ||= { intersectPoint: new Vector3(), distance: 0 }; - this._pickRet.intersectPoint = pick; - this._pickRet.distance = Vector3.distance(helpRay.origin, pick); + /** + * Renderer drawing `mesh`, set automatically by `ColliderComponent` from + * the same object. When it skins or morphs the mesh, picks follow the + * deformed surface (see `deformation`). + */ + public renderer: MeshRenderer = null; - let normalAttribute = this.mesh.getAttribute(VertexAttributeName.normal); - if(normalAttribute){ - let normalData = normalAttribute.data; - let normal = new Vector3(normalData[i1], normalData[i1 + 1], normalData[i1 + 2]); - Matrix4.transformVector(fromMatrix, normal, normal); - normal.normalize(); - this._pickRet.normal = normal - } - return this._pickRet; - } + /** How a skinned / morphed `renderer` is picked. Default `'cpu'`: as drawn. */ + public deformation: RaycastDeformation = 'cpu'; - } - } - } + private _opts: MeshRaycastOptions = {}; + private _hits: RaycastHit[] = []; - return null; + constructor() { + super(); + this._shapeType = ColliderShapeType.Mesh; } + /** + * Closest triangle hit along `ray` (world space), or null. With the + * default `useBVH` the cost is O(log n) triangles. `distance`, + * `intersectPoint`, `normal` (interpolated vertex normal, face normal + * when the geometry has none) and `faceNormal` are world space; the + * result also carries `localPoint`, `faceIndex`, `barycentric`, `uv`, + * `uv1`, `subGeometryIndex` and `frontFace`. + */ + public rayPick(ray: Ray, fromMatrix: Matrix4): HitInfo { + if (!this.mesh) return null; + const opts = this._opts; + opts.cull = this.backfaceCulling ? 'back' : 'none'; + opts.far = this.maxDistance; + opts.useBVH = this.useBVH; + const hits = this._hits; + hits.length = 0; + opts.deformation = this.deformation; + const r = this.renderer; + const count = r && r.geometry === this.mesh + ? MeshRaycast.intersectRenderer(r, ray, opts, hits) + : MeshRaycast.intersect(this.mesh, fromMatrix, ray, opts, hits); + if (count === 0) return null; + const h = hits[0]; + hits.length = 0; + const ret: HitInfo = { + intersectPoint: h.point, + normal: h.normal, + distance: h.distance, + localPoint: h.localPoint, + faceNormal: h.faceNormal, + faceIndex: h.faceIndex, + barycentric: h.barycentric, + subGeometryIndex: h.subGeometryIndex, + frontFace: h.frontFace, + }; + if (h.uv) ret.uv = h.uv; + if (h.uv1) ret.uv1 = h.uv1; + return ret; + } } diff --git a/src/components/shape/SphereColliderShape.ts b/src/components/shape/SphereColliderShape.ts index 2f0646df9..b3023f62e 100644 --- a/src/components/shape/SphereColliderShape.ts +++ b/src/components/shape/SphereColliderShape.ts @@ -2,7 +2,7 @@ import { BoundingSphere } from "../../core/bound/BoundingSphere"; import { Matrix4 } from "../../math/Matrix4"; import { Ray } from "../../math/Ray"; import { Vector3 } from "../../math/Vector3"; -import { ColliderShape, ColliderShapeType } from "./ColliderShape"; +import { ColliderShape, ColliderShapeType, HitInfo } from "./ColliderShape"; /** @@ -11,7 +11,6 @@ import { ColliderShape, ColliderShapeType } from "./ColliderShape"; */ export class SphereColliderShape extends ColliderShape { - private _pickRet: { intersect: boolean; intersectPoint?: Vector3; distance: number }; private readonly box: BoundingSphere; /** @@ -30,7 +29,14 @@ export class SphereColliderShape extends ColliderShape { this.box = new BoundingSphere(new Vector3(), 1); } - public rayPick(ray: Ray, fromMatrix: Matrix4): { intersect: boolean; intersectPoint?: Vector3; distance: number } { + /** + * Entry point of `ray` on the sphere (exit point when the ray starts + * inside). Point, normal and distance are world space; the local hit + * point is in `localPoint`. + * @param ray world-space ray + * @param fromMatrix local → world matrix + */ + public rayPick(ray: Ray, fromMatrix: Matrix4): HitInfo { let box = this.box; box.setFromCenterAndSize(this.center, this.radius); @@ -40,16 +46,22 @@ export class SphereColliderShape extends ColliderShape { let helpRay = ColliderShape.helpRay.copy(ray); helpRay.applyMatrix(helpMatrix); - let pick = helpRay.intersectSphere(helpRay.origin, helpRay.direction, this.box.center, this.box.radius); - if (pick) { - if (!this._pickRet) { - this._pickRet = { intersect: false, intersectPoint: new Vector3(), distance: 0 }; - } - this._pickRet.intersect = true; - this._pickRet.intersectPoint = pick; - this._pickRet.distance = Vector3.distance(helpRay.origin, ColliderShape.v3_help_0); - return this._pickRet; - } - return null; + const o = helpRay.origin, d = helpRay.direction, c = box.center, r = box.radius; + const ox = o.x - c.x, oy = o.y - c.y, oz = o.z - c.z; + const a = d.x * d.x + d.y * d.y + d.z * d.z; + const b = 2 * (ox * d.x + oy * d.y + oz * d.z); + const cc = ox * ox + oy * oy + oz * oz - r * r; + const disc = b * b - 4 * a * cc; + if (disc < 0 || a === 0) return null; + const sq = Math.sqrt(disc); + let t = (-b - sq) / (2 * a); + if (t < 0) t = (-b + sq) / (2 * a); + if (t < 0) return null; + + const local = ColliderShape.v3_help_0.set(o.x + d.x * t, o.y + d.y * t, o.z + d.z * t); + const n = SphereColliderShape._normal.set(local.x - c.x, local.y - c.y, local.z - c.z); + return ColliderShape.toWorldHit(ray, fromMatrix, helpMatrix, local, n); } + + private static _normal: Vector3 = new Vector3(); } diff --git a/src/core/bound/BoundingBox.ts b/src/core/bound/BoundingBox.ts index 490b204b8..aa2b75570 100644 --- a/src/core/bound/BoundingBox.ts +++ b/src/core/bound/BoundingBox.ts @@ -230,7 +230,7 @@ export class BoundingBox implements IBound { * @param point output hit point */ public intersectsRay(ray: Ray, point: Vector3): boolean { - throw new Error('Method not implemented.'); + return ray.intersectBox(this, point) != null; } /** diff --git a/src/core/bound/BoundingSphere.ts b/src/core/bound/BoundingSphere.ts index bff36b15f..6ccaaf253 100644 --- a/src/core/bound/BoundingSphere.ts +++ b/src/core/bound/BoundingSphere.ts @@ -55,10 +55,20 @@ export class BoundingSphere implements IBound { } /** - * Recompute the bound from the source data. Not implemented for spheres. + * Recompute the derived AABB fields (`extents`, `size`, `min`, `max`) + * from `center` and `radius`, so a sphere can stand in wherever an + * `IBound` is expected (frustum tests, `Ray.intersectBox`, octrees). */ updateBound() { - throw new Error('Method not implemented.'); + const r = this.radius; + this.extents ||= new Vector3(); + this.size ||= new Vector3(); + this.min ||= new Vector3(); + this.max ||= new Vector3(); + this.extents.set(r, r, r); + this.size.set(r * 2, r * 2, r * 2); + this.min.set(this.center.x - r, this.center.y - r, this.center.z - r); + this.max.set(this.center.x + r, this.center.y + r, this.center.z + r); } /** @@ -167,5 +177,6 @@ export class BoundingSphere implements IBound { public setFromCenterAndSize(center: Vector3, size: number) { this.center.copy(center); this.radius = size; + this.updateBound(); } } diff --git a/src/core/geometry/GeometryBase.ts b/src/core/geometry/GeometryBase.ts index 763da82e0..e8aba3f97 100644 --- a/src/core/geometry/GeometryBase.ts +++ b/src/core/geometry/GeometryBase.ts @@ -66,6 +66,7 @@ export class GeometryBase { private _indicesBuffer: GeometryIndicesBuffer; private _vertexBuffer: GeometryVertexBuffer; private _onChange: boolean = true; + private _version: number = 0; private _wireframeLines: Vector3[]; constructor() { @@ -75,6 +76,17 @@ export class GeometryBase { this._vertexBuffer = new GeometryVertexBuffer(); } + /** + * Change counter for the CPU-side triangle data: bumped by + * `setIndices` / `setVertexs` / `setAttribute` and whenever positions are + * re-uploaded through `vertexBuffer.upload`. Code that caches derived + * data (e.g. `MeshBVH`) compares it to detect stale caches. Editing the + * position array in place without uploading is not detected. + */ + public get version(): number { + return this._version + this._vertexBuffer.positionVersion; + } + /** Get the GPU index buffer of this geometry. */ public get indicesBuffer(): GeometryIndicesBuffer { return this._indicesBuffer; @@ -212,6 +224,7 @@ export class GeometryBase { * @param data the index buffer data */ public setIndices(data: ArrayBufferData) { + this._version++; if (!this._attributeMap.has(VertexAttributeName.indices)) { let vertexInfo: VertexAttributeData = { attribute: VertexAttributeName.indices, @@ -228,6 +241,7 @@ export class GeometryBase { * @param data the position buffer data */ public setVertexs(data: ArrayBufferData) { + this._version++; let vertexInfo: VertexAttributeData = { attribute: VertexAttributeName.position, data: data, @@ -247,6 +261,7 @@ export class GeometryBase { } else if (attribute == VertexAttributeName.position) { this.setVertexs(data); } else { + this._version++; let vertexInfo: VertexAttributeData = { attribute: attribute, data: data, diff --git a/src/core/geometry/GeometryVertexBuffer.ts b/src/core/geometry/GeometryVertexBuffer.ts index 709f7b10f..1a1acda12 100644 --- a/src/core/geometry/GeometryVertexBuffer.ts +++ b/src/core/geometry/GeometryVertexBuffer.ts @@ -73,6 +73,11 @@ export class GeometryVertexBuffer { this._composeBinStride = stride; } + /** The interleave layout recorded by {@link setComposeBinLayout}, or null. */ + public get composeBinLayout(): VertexAttribute[] { + return this._composeBinLayout; + } + constructor() { this._vertexBufferLayouts = []; this._attributeLocation = {}; @@ -388,7 +393,15 @@ export class GeometryVertexBuffer { this.allocVertexBuffer(this.vertexCount * attributeOffset); } + /** + * Bumped whenever position data is re-uploaded (`position`, or the packed + * `all` buffer), so CPU-side consumers such as `MeshBVH` can tell that + * the vertices moved. See `GeometryBase.version`. + */ + public positionVersion: number = 0; + public upload(attribute: string, vertexDataInfo: VertexAttributeData) { + if (attribute === VertexAttributeName.position || attribute === VertexAttributeName.all) this.positionVersion++; if (!this.vertexGPUBuffer) return; switch (this.geometryType) { case GeometryVertexType.split: diff --git a/src/core/tree/bvh/MeshBVH.ts b/src/core/tree/bvh/MeshBVH.ts new file mode 100644 index 000000000..160973097 --- /dev/null +++ b/src/core/tree/bvh/MeshBVH.ts @@ -0,0 +1,755 @@ +import { GeometryBase } from '../../geometry/GeometryBase'; +import { VertexAttributeName } from '../../geometry/VertexAttributeName'; +import { Vector3 } from '../../../math/Vector3'; + +/** + * Which triangle faces a ray query ignores. Front faces are counter-clockwise + * as seen from the ray origin (the engine's default `frontFace: 'ccw'`). + * - `none`: hit both sides + * - `back`: skip back faces (what a `cullMode: 'back'` material shows) + * - `front`: skip front faces (what a `cullMode: 'front'` material shows) + * @group Core + */ +export type MeshBVHCull = 'none' | 'back' | 'front'; + +/** + * Options for `MeshBVH` ray queries. Distances are along the normalized ray + * direction in the geometry's local space. + * @group Core + */ +export interface MeshBVHRayOptions { + /** Faces to ignore; `true` means `'back'`. Default `'none'`. */ + cull?: MeshBVHCull | boolean; + /** Ignore hits closer than this. Default 0. */ + near?: number; + /** Ignore hits farther than this. Default Infinity. */ + far?: number; +} + +/** + * Result of a `MeshBVH` ray query. All values are in the geometry's local + * space; `t` is the distance along the (normalized) ray direction. + * @group Core + */ +export interface MeshBVHHit { + /** Distance along the ray. */ + t: number; + /** Triangle index into the index buffer (`indices[triIndex*3 .. +2]`). */ + triIndex: number; + /** Barycentric weight of vertex 1 (v0 gets `1-u-v`). */ + u: number; + /** Barycentric weight of vertex 2. */ + v: number; + /** Hit point in local space. */ + point: Vector3; + /** Geometric (face) normal in local space, unit length, from the triangle winding. */ + faceNormal: Vector3; + /** Whether the ray hit the front (counter-clockwise) side of the triangle. */ + frontFace: boolean; + /** Index of the `SubGeometry` (and so the renderer material) the triangle belongs to. */ + subGeometryIndex: number; +} + +/** + * Strided view of one vertex attribute: component `k` of vertex `i` is + * `data[i * stride + offset + k]`. Covers both split attributes and the + * interleaved `all` buffer of `compose_bin` (prefab) geometry. + * @group Core + */ +export interface MeshAttributeView { + data: ArrayLike; + stride: number; + offset: number; +} + +/** A run of triangles `[start, start + count)` belonging to one sub-geometry. */ +interface TriRange { + start: number; + count: number; + sub: number; +} + +/** Triangle data shared by the tree and the tree-less queries. */ +interface TriSource { + pos: MeshAttributeView; + /** null → non-indexed: triangle t uses vertices 3t, 3t+1, 3t+2. */ + indices: ArrayLike | null; + ranges: TriRange[]; + triCount: number; +} + +const EPS_DET = 1e-12; +const EPS_T = 1e-7; +// Scratch written by rayTri: u, v, det. +let _u = 0, _v = 0, _det = 0; + +/** + * Möller–Trumbore. Returns t, or -1 on a miss; leaves u/v/det in the module + * scratch. `cull`: 0 none, 1 skip back faces, 2 skip front faces. + */ +function rayTri(P: ArrayLike, ia: number, ib: number, ic: number, + ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, cull: number): number { + const ax = P[ia], ay = P[ia + 1], az = P[ia + 2]; + const e1x = P[ib] - ax, e1y = P[ib + 1] - ay, e1z = P[ib + 2] - az; + const e2x = P[ic] - ax, e2y = P[ic + 1] - ay, e2z = P[ic + 2] - az; + // p = d × e2 + const px = dy * e2z - dz * e2y, py = dz * e2x - dx * e2z, pz = dx * e2y - dy * e2x; + const det = e1x * px + e1y * py + e1z * pz; + // det > 0 ⇔ the ray sees the counter-clockwise (front) side. + if (cull === 1) { if (det < EPS_DET) return -1; } + else if (cull === 2) { if (det > -EPS_DET) return -1; } + else if (det > -EPS_DET && det < EPS_DET) return -1; + const inv = 1 / det; + const tx = ox - ax, ty = oy - ay, tz = oz - az; + const u = (tx * px + ty * py + tz * pz) * inv; + if (u < 0 || u > 1) return -1; + // q = t × e1 + const qx = ty * e1z - tz * e1y, qy = tz * e1x - tx * e1z, qz = tx * e1y - ty * e1x; + const v = (dx * qx + dy * qy + dz * qz) * inv; + if (v < 0 || u + v > 1) return -1; + _u = u; _v = v; _det = det; + return (e2x * qx + e2y * qy + e2z * qz) * inv; +} + +function cullCode(cull: MeshBVHCull | boolean | undefined): number { + if (cull === true || cull === 'back') return 1; + if (cull === 'front') return 2; + return 0; +} + +function newHit(): MeshBVHHit { + return { t: 0, triIndex: -1, u: 0, v: 0, point: new Vector3(), faceNormal: new Vector3(), frontFace: true, subGeometryIndex: 0 }; +} + +/** + * Bounding-volume hierarchy over the triangles of a `GeometryBase`, for fast + * CPU ray queries (picking, placement, line-of-sight). Built once per + * geometry and cached in a `WeakMap`; brute-force scanning every triangle + * is O(n) per ray, the BVH is O(log n). + * + * Nodes are stored flat in typed arrays (6 floats of bounds + 2 uints per + * node) so traversal allocates nothing until a hit is reported. Leaves hold + * up to `maxLeafTris` triangles; interior nodes split on the longest + * centroid axis at the midpoint of the centroid bounds, falling back to a + * median split when one side would be empty. + * + * Only triangles drawn at LOD 0 of each `SubGeometry` are indexed (the + * whole index buffer when the geometry has no sub-geometries). Positions + * are read from the `position` attribute, or from the interleaved `all` + * buffer of `compose_bin` (prefab) geometry. Skinning and morph targets are + * not applied: the tree describes the bind pose. + * + * The cache follows `GeometryBase.version`: when positions are re-uploaded + * in place the tree is refit, when the vertex/index arrays are replaced it + * is rebuilt. After editing positions in place without an upload, call + * `refit()` (or `MeshBVH.invalidate`). + * + * ```ts + * const bvh = MeshBVH.get(meshRenderer.geometry); + * const hit = bvh.raycast(localOrigin, localDirection, { cull: 'back', far: 100 }); + * ``` + * + * The static `raycastGeometry` / `raycastGeometryAll` run the same queries + * without building a tree, for one-off rays or tiny meshes. + * @group Core + */ +export class MeshBVH { + private static _cache: WeakMap = new WeakMap(); + + /** + * Fetch the cached BVH for a geometry, building it on first use. A cached + * tree whose geometry changed since (see `GeometryBase.version`) is + * refit or rebuilt first. + * @param maxLeafTris only used when a tree has to be built; use + * `build` to force a different leaf size. + */ + public static get(geometry: GeometryBase, maxLeafTris: number = 8): MeshBVH { + let bvh = MeshBVH._cache.get(geometry); + if (bvh) { + if (bvh._version !== geometry.version) { + const src = MeshBVH._source(geometry); + if (src.pos.data === bvh._pos.data && src.indices === bvh._srcIndices && src.triCount === bvh._srcTriCount) { + bvh.refit(); + } else { + bvh = MeshBVH.build(geometry, maxLeafTris); + } + } + return bvh; + } + return MeshBVH.build(geometry, maxLeafTris); + } + + /** Build (or rebuild) the BVH for a geometry and cache it, replacing any cached tree. */ + public static build(geometry: GeometryBase, maxLeafTris: number = 8): MeshBVH { + const bvh = new MeshBVH(geometry, maxLeafTris); + MeshBVH._cache.set(geometry, bvh); + return bvh; + } + + /** Drop the cached BVH (the next `get` rebuilds it). */ + public static invalidate(geometry: GeometryBase): void { + MeshBVH._cache.delete(geometry); + } + + /** Whether a BVH has been built (and not invalidated) for this geometry. */ + public static has(geometry: GeometryBase): boolean { + return MeshBVH._cache.has(geometry); + } + + /** + * Strided view of a vertex attribute (`position`, `normal`, `uv`, + * `TEXCOORD_1`, …), whether the geometry stores it as its own array or + * interleaved in a `compose_bin` buffer. null when absent. + */ + public static getAttributeView(geometry: GeometryBase, name: string): MeshAttributeView | null { + const attr = geometry.getAttribute(name); + if (attr && attr.data && attr.data.length > 0) { + const dim = MeshBVH._attributeDim(name); + return { data: attr.data as ArrayLike, stride: dim, offset: 0 }; + } + const all = geometry.getAttribute(VertexAttributeName.all); + if (all && all.data && all.data.length > 0 && geometry.vertexDim > 0) { + const layout = geometry.vertexBuffer?.composeBinLayout; + if (layout) { + for (let i = 0; i < layout.length; i++) { + if (layout[i].name === name) return { data: all.data as ArrayLike, stride: geometry.vertexDim, offset: layout[i].offset / 4 }; + } + return null; + } + // Legacy packed buffers without a recorded layout start with position. + if (name === VertexAttributeName.position) return { data: all.data as ArrayLike, stride: geometry.vertexDim, offset: 0 }; + } + return null; + } + + private static _attributeDim(name: string): number { + switch (name) { + case VertexAttributeName.position: + case VertexAttributeName.normal: + return 3; + case VertexAttributeName.TANGENT: + case VertexAttributeName.color: + case VertexAttributeName.joints0: + case VertexAttributeName.joints1: + case VertexAttributeName.weights0: + case VertexAttributeName.weights1: + return 4; + case VertexAttributeName.vIndex: + return 1; + } + return name.startsWith('a_morph') ? 3 : 2; + } + + /** + * Closest hit without a tree: tests every triangle (O(n)). Same options + * and result as `raycast`. + */ + public static raycastGeometry(geometry: GeometryBase, origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions, target?: MeshBVHHit): MeshBVHHit | null { + const src = MeshBVH._source(geometry); + const cull = cullCode(options?.cull); + const near = options?.near ?? 0; + let best = options?.far ?? Infinity, bestTri = -1, bu = 0, bv = 0, bdet = 0; + const P = src.pos.data, ps = src.pos.stride, po = src.pos.offset, I = src.indices; + const ox = origin.x, oy = origin.y, oz = origin.z, dx = direction.x, dy = direction.y, dz = direction.z; + for (const r of src.ranges) { + for (let tri = r.start, e = r.start + r.count; tri < e; tri++) { + const k = tri * 3; + const a = I ? I[k] : k, b = I ? I[k + 1] : k + 1, c = I ? I[k + 2] : k + 2; + const t = rayTri(P, a * ps + po, b * ps + po, c * ps + po, ox, oy, oz, dx, dy, dz, cull); + if (t > EPS_T && t >= near && t < best) { best = t; bestTri = tri; bu = _u; bv = _v; bdet = _det; } + } + } + if (bestTri < 0) return null; + return MeshBVH._fill(target || newHit(), src, bestTri, best, bu, bv, bdet, ox, oy, oz, dx, dy, dz); + } + + /** Every hit without a tree, sorted by distance. Same options as `raycastAll`. */ + public static raycastGeometryAll(geometry: GeometryBase, origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions, out: MeshBVHHit[] = []): MeshBVHHit[] { + const src = MeshBVH._source(geometry); + const cull = cullCode(options?.cull); + const near = options?.near ?? 0, far = options?.far ?? Infinity; + const P = src.pos.data, ps = src.pos.stride, po = src.pos.offset, I = src.indices; + const ox = origin.x, oy = origin.y, oz = origin.z, dx = direction.x, dy = direction.y, dz = direction.z; + const first = out.length; + for (const r of src.ranges) { + for (let tri = r.start, e = r.start + r.count; tri < e; tri++) { + const k = tri * 3; + const a = I ? I[k] : k, b = I ? I[k + 1] : k + 1, c = I ? I[k + 2] : k + 2; + const t = rayTri(P, a * ps + po, b * ps + po, c * ps + po, ox, oy, oz, dx, dy, dz, cull); + if (t > EPS_T && t >= near && t <= far) out.push(MeshBVH._fill(newHit(), src, tri, t, _u, _v, _det, ox, oy, oz, dx, dy, dz)); + } + } + MeshBVH._sortFrom(out, first, src); + return out; + } + + /** Number of triangles indexed. */ + public readonly triCount: number; + /** Number of BVH nodes (interior + leaf). */ + public nodeCount: number = 0; + /** Deepest leaf level (root = 0). */ + public depth: number = 0; + /** The geometry this tree was built for. */ + public readonly geometry: GeometryBase; + + private readonly _src: TriSource; + private readonly _pos: MeshAttributeView; + /** Index array the tree reads (a generated sequence for non-indexed geometry). */ + private readonly _indices: ArrayLike; + /** The geometry's own index array (null when non-indexed), for change detection. */ + private readonly _srcIndices: ArrayLike | null; + private readonly _srcTriCount: number; + private _version: number; + /** Per-node [minX, minY, minZ, maxX, maxY, maxZ]. */ + private _bounds: Float32Array; + /** + * Per-node [a, b]: leaf → a = first slot in `_triOrder`, b = triangle + * count (≥1); interior → a = left child index, b = 0 (right = a + 1). + * Children always have larger indices than their parent. + */ + private _info: Uint32Array; + /** Triangle indices (into the index buffer) grouped per leaf. */ + private _triOrder: Uint32Array; + private readonly _maxLeafTris: number; + private _stack: Int32Array; + + private constructor(geometry: GeometryBase, maxLeafTris: number) { + this.geometry = geometry; + const src = MeshBVH._source(geometry); + this._src = src; + this._pos = src.pos; + this._srcIndices = src.indices; + this._srcTriCount = src.triCount; + if (src.indices) { + this._indices = src.indices; + } else { + const n = src.triCount * 3; + const seq = new Uint32Array(n); + for (let i = 0; i < n; i++) seq[i] = i; + this._indices = seq; + } + let count = 0; + for (const r of src.ranges) count += r.count; + this.triCount = count; + this._maxLeafTris = Math.max(1, maxLeafTris | 0); + this._version = geometry.version; + this._build(); + } + + /** Triangle source of a geometry: positions, indices and LOD-0 sub-geometry ranges. */ + private static _source(geometry: GeometryBase): TriSource { + const pos = MeshBVH.getAttributeView(geometry, VertexAttributeName.position); + if (!pos) throw new Error('MeshBVH: geometry has no position attribute'); + const idx = geometry.getAttribute(VertexAttributeName.indices); + const indices = idx && idx.data && idx.data.length > 0 ? idx.data as ArrayLike : null; + const triCount = indices ? (indices.length / 3) | 0 : (((pos.data.length - pos.offset) / pos.stride) / 3) | 0; + const ranges: TriRange[] = []; + const subs = geometry.subGeometries; + if (indices && subs && subs.length > 0) { + for (let i = 0; i < subs.length; i++) { + const lod = subs[i].lodLevels && subs[i].lodLevels[0]; + if (!lod) continue; + const start = Math.min(triCount, Math.floor(lod.indexStart / 3)); + const count = Math.min(triCount - start, Math.floor(lod.indexCount / 3)); + if (count > 0) ranges.push({ start, count, sub: i }); + } + } + if (ranges.length === 0 && triCount > 0) ranges.push({ start: 0, count: triCount, sub: 0 }); + return { pos, indices, ranges, triCount }; + } + + // ------------------------------------------------------------------ build + + private _build(): void { + const n = this.triCount; + const P = this._pos.data, ps = this._pos.stride, po = this._pos.offset, I = this._indices; + + // Local slot → triangle index. + const tris = new Uint32Array(n); + let k = 0; + for (const r of this._src.ranges) for (let t = r.start, e = r.start + r.count; t < e; t++) tris[k++] = t; + + // Per-triangle AABB + centroid, computed once. + const triMin = new Float32Array(n * 3), triMax = new Float32Array(n * 3), cen = new Float32Array(n * 3); + for (let s = 0; s < n; s++) { + const t = tris[s]; + const a = I[t * 3] * ps + po, b = I[t * 3 + 1] * ps + po, c = I[t * 3 + 2] * ps + po; + for (let j = 0; j < 3; j++) { + const pa = P[a + j], pb = P[b + j], pc = P[c + j]; + const mn = pa < pb ? (pa < pc ? pa : pc) : (pb < pc ? pb : pc); + const mx = pa > pb ? (pa > pc ? pa : pc) : (pb > pc ? pb : pc); + triMin[s * 3 + j] = mn; + triMax[s * 3 + j] = mx; + cen[s * 3 + j] = (mn + mx) * 0.5; + } + } + + const order = new Uint32Array(n); + for (let i = 0; i < n; i++) order[i] = i; + + // Upper bound on node count for a binary tree with ≥1 tri per leaf. + const maxNodes = Math.max(1, 2 * n - 1); + const bounds = new Float32Array(maxNodes * 6); + const info = new Uint32Array(maxNodes * 2); + let nodeCount = 0; + let depth = 0; + + if (n > 0) { + // Iterative build with an explicit work stack: [nodeIndex, start, end, level]. + const work: number[] = []; + const root = nodeCount++; + work.push(root, 0, n, 0); + + while (work.length) { + const level = work.pop()!, end = work.pop()!, start = work.pop()!, node = work.pop()!; + if (level > depth) depth = level; + + // Node bounds + centroid bounds over [start, end). + let mnx = Infinity, mny = Infinity, mnz = Infinity, mxx = -Infinity, mxy = -Infinity, mxz = -Infinity; + let cmnx = Infinity, cmny = Infinity, cmnz = Infinity, cmxx = -Infinity, cmxy = -Infinity, cmxz = -Infinity; + for (let i = start; i < end; i++) { + const t = order[i] * 3; + if (triMin[t] < mnx) mnx = triMin[t]; if (triMax[t] > mxx) mxx = triMax[t]; + if (triMin[t + 1] < mny) mny = triMin[t + 1]; if (triMax[t + 1] > mxy) mxy = triMax[t + 1]; + if (triMin[t + 2] < mnz) mnz = triMin[t + 2]; if (triMax[t + 2] > mxz) mxz = triMax[t + 2]; + const cx = cen[t], cy = cen[t + 1], cz = cen[t + 2]; + if (cx < cmnx) cmnx = cx; if (cx > cmxx) cmxx = cx; + if (cy < cmny) cmny = cy; if (cy > cmxy) cmxy = cy; + if (cz < cmnz) cmnz = cz; if (cz > cmxz) cmxz = cz; + } + const b = node * 6; + bounds[b] = mnx; bounds[b + 1] = mny; bounds[b + 2] = mnz; + bounds[b + 3] = mxx; bounds[b + 4] = mxy; bounds[b + 5] = mxz; + + const count = end - start; + const ex = cmxx - cmnx, ey = cmxy - cmny, ez = cmxz - cmnz; + if (count <= this._maxLeafTris || (ex === 0 && ey === 0 && ez === 0)) { + info[node * 2] = start; + info[node * 2 + 1] = count; + continue; + } + + // Split on the longest centroid axis at the centroid-bounds midpoint. + const axis = ex >= ey && ex >= ez ? 0 : (ey >= ez ? 1 : 2); + const split = axis === 0 ? (cmnx + cmxx) * 0.5 : axis === 1 ? (cmny + cmxy) * 0.5 : (cmnz + cmxz) * 0.5; + let mid = MeshBVH._partition(order, cen, start, end, axis, split); + if (mid === start || mid === end) { + // Degenerate (all centroids on one side): median split by count. + mid = (start + end) >>> 1; + MeshBVH._nthElement(order, cen, start, end, mid, axis); + } + + const left = nodeCount, right = nodeCount + 1; + nodeCount += 2; + info[node * 2] = left; + info[node * 2 + 1] = 0; + work.push(right, mid, end, level + 1); + work.push(left, start, mid, level + 1); + } + } + + this.nodeCount = nodeCount; + this.depth = depth; + this._bounds = bounds.subarray(0, nodeCount * 6); + this._info = info.subarray(0, nodeCount * 2); + // Leaves reference triangle indices directly from here on. + for (let i = 0; i < n; i++) order[i] = tris[order[i]]; + this._triOrder = order; + // DFS keeps at most one pending sibling per level, plus the node in hand. + this._stack = new Int32Array(depth + 2); + } + + /** Hoare-style partition of `order[start,end)` by centroid[axis] < split. Returns first index of the right side. */ + private static _partition(order: Uint32Array, cen: Float32Array, start: number, end: number, axis: number, split: number): number { + let i = start, j = end - 1; + while (i <= j) { + if (cen[order[i] * 3 + axis] < split) { i++; continue; } + const tmp = order[i]; order[i] = order[j]; order[j] = tmp; + j--; + } + return i; + } + + /** Quickselect so that order[k] is the k-th smallest by centroid[axis] and sides are partitioned around it. */ + private static _nthElement(order: Uint32Array, cen: Float32Array, start: number, end: number, k: number, axis: number): void { + let lo = start, hi = end - 1; + while (lo < hi) { + const pivot = cen[order[(lo + hi) >>> 1] * 3 + axis]; + let i = lo, j = hi; + while (i <= j) { + while (cen[order[i] * 3 + axis] < pivot) i++; + while (cen[order[j] * 3 + axis] > pivot) j--; + if (i <= j) { const t = order[i]; order[i] = order[j]; order[j] = t; i++; j--; } + } + if (k <= j) hi = j; else if (k >= i) lo = i; else break; + } + } + + /** + * Recompute node bounds from the current vertex positions, keeping the + * tree topology. Cheap (O(n)); use after moving vertices in place. Large + * deformations make the tree slower but never wrong; rebuild with + * `MeshBVH.build` if queries degrade. + */ + public refit(): void { + const B = this._bounds, N = this._info, order = this._triOrder; + const P = this._pos.data, ps = this._pos.stride, po = this._pos.offset, I = this._indices; + // Children have larger indices than their parent: walk backwards. + for (let node = this.nodeCount - 1; node >= 0; node--) { + const b = node * 6, a = N[node * 2], cnt = N[node * 2 + 1]; + let mnx = Infinity, mny = Infinity, mnz = Infinity, mxx = -Infinity, mxy = -Infinity, mxz = -Infinity; + if (cnt > 0) { + for (let i = a, e = a + cnt; i < e; i++) { + const t = order[i] * 3; + for (let j = 0; j < 3; j++) { + const p = I[t + j] * ps + po; + const x = P[p], y = P[p + 1], z = P[p + 2]; + if (x < mnx) mnx = x; if (x > mxx) mxx = x; + if (y < mny) mny = y; if (y > mxy) mxy = y; + if (z < mnz) mnz = z; if (z > mxz) mxz = z; + } + } + } else { + const l = a * 6, r = (a + 1) * 6; + mnx = Math.min(B[l], B[r]); mny = Math.min(B[l + 1], B[r + 1]); mnz = Math.min(B[l + 2], B[r + 2]); + mxx = Math.max(B[l + 3], B[r + 3]); mxy = Math.max(B[l + 4], B[r + 4]); mxz = Math.max(B[l + 5], B[r + 5]); + } + B[b] = mnx; B[b + 1] = mny; B[b + 2] = mnz; + B[b + 3] = mxx; B[b + 4] = mxy; B[b + 5] = mxz; + } + this._version = this.geometry.version; + } + + // ---------------------------------------------------------------- queries + + /** + * Closest hit along a ray (local space). `null` on miss. + * @param origin ray origin + * @param direction ray direction (normalized for `t` to be a distance) + * @param options culling and near/far limits + * @param target object to write the result into (a new one by default) + */ + public raycast(origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions, target?: MeshBVHHit): MeshBVHHit | null { + if (this.nodeCount === 0) return null; + const cull = cullCode(options?.cull); + const near = options?.near ?? 0; + let best = options?.far ?? Infinity, bestTri = -1, bu = 0, bv = 0, bdet = 0; + const ox = origin.x, oy = origin.y, oz = origin.z; + const dx = direction.x, dy = direction.y, dz = direction.z; + const ix = 1 / dx, iy = 1 / dy, iz = 1 / dz; + const B = this._bounds, N = this._info, order = this._triOrder; + const P = this._pos.data, ps = this._pos.stride, po = this._pos.offset, I = this._indices; + const stack = this._stack; + let sp = 0; + stack[sp++] = 0; + while (sp > 0) { + const node = stack[--sp]; + const b = node * 6; + // Slab test against [near, current best]. + let t0 = ((ix >= 0 ? B[b] : B[b + 3]) - ox) * ix; + let t1 = ((ix >= 0 ? B[b + 3] : B[b]) - ox) * ix; + const ty0 = ((iy >= 0 ? B[b + 1] : B[b + 4]) - oy) * iy; + const ty1 = ((iy >= 0 ? B[b + 4] : B[b + 1]) - oy) * iy; + if (t0 > ty1 || ty0 > t1) continue; + if (ty0 > t0) t0 = ty0; + if (ty1 < t1) t1 = ty1; + const tz0 = ((iz >= 0 ? B[b + 2] : B[b + 5]) - oz) * iz; + const tz1 = ((iz >= 0 ? B[b + 5] : B[b + 2]) - oz) * iz; + if (t0 > tz1 || tz0 > t1) continue; + if (tz0 > t0) t0 = tz0; + if (tz1 < t1) t1 = tz1; + if (t1 < near || t0 > best) continue; + + const a = N[node * 2], cnt = N[node * 2 + 1]; + if (cnt > 0) { + for (let i = a, e = a + cnt; i < e; i++) { + const tri = order[i], k = tri * 3; + const t = rayTri(P, I[k] * ps + po, I[k + 1] * ps + po, I[k + 2] * ps + po, ox, oy, oz, dx, dy, dz, cull); + if (t > EPS_T && t >= near && t < best) { best = t; bestTri = tri; bu = _u; bv = _v; bdet = _det; } + } + } else { + // Visit the child nearer along the dominant axis first so the + // best-t pruning kicks in early. + const axis = MeshBVH._longestAxis(B, a * 6, (a + 1) * 6); + const dirNeg = axis === 0 ? dx < 0 : axis === 1 ? dy < 0 : dz < 0; + if (dirNeg) { stack[sp++] = a; stack[sp++] = a + 1; } + else { stack[sp++] = a + 1; stack[sp++] = a; } + } + } + if (bestTri < 0) return null; + return MeshBVH._fill(target || newHit(), this._src, bestTri, best, bu, bv, bdet, ox, oy, oz, dx, dy, dz); + } + + /** + * Every hit along a ray (local space), sorted by distance. Each result is + * a new object appended to `out`. A crossing through an edge or vertex + * shared by several triangles is reported once. + */ + public raycastAll(origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions, out: MeshBVHHit[] = []): MeshBVHHit[] { + if (this.nodeCount === 0) return out; + const cull = cullCode(options?.cull); + const near = options?.near ?? 0, far = options?.far ?? Infinity; + const ox = origin.x, oy = origin.y, oz = origin.z; + const dx = direction.x, dy = direction.y, dz = direction.z; + const first = out.length; + this._traverse(ox, oy, oz, dx, dy, dz, near, far, (tri, k) => { + const P = this._pos.data, ps = this._pos.stride, po = this._pos.offset, I = this._indices; + const t = rayTri(P, I[k] * ps + po, I[k + 1] * ps + po, I[k + 2] * ps + po, ox, oy, oz, dx, dy, dz, cull); + if (t > EPS_T && t >= near && t <= far) out.push(MeshBVH._fill(newHit(), this._src, tri, t, _u, _v, _det, ox, oy, oz, dx, dy, dz)); + return false; + }); + MeshBVH._sortFrom(out, first, this._src); + return out; + } + + /** Whether the ray hits any triangle; stops at the first one found. */ + public intersectsRay(origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions): boolean { + if (this.nodeCount === 0) return false; + const cull = cullCode(options?.cull); + const near = options?.near ?? 0, far = options?.far ?? Infinity; + const ox = origin.x, oy = origin.y, oz = origin.z; + const dx = direction.x, dy = direction.y, dz = direction.z; + const P = this._pos.data, ps = this._pos.stride, po = this._pos.offset, I = this._indices; + return this._traverse(ox, oy, oz, dx, dy, dz, near, far, (_tri, k) => { + const t = rayTri(P, I[k] * ps + po, I[k + 1] * ps + po, I[k + 2] * ps + po, ox, oy, oz, dx, dy, dz, cull); + return t > EPS_T && t >= near && t <= far; + }); + } + + /** + * Brute-force closest hit over this tree's triangles. O(n); exists to + * validate the tree in tests and benchmarks. + */ + public raycastBruteForce(origin: Vector3, direction: Vector3, options?: MeshBVHRayOptions, target?: MeshBVHHit): MeshBVHHit | null { + return MeshBVH.raycastGeometry(this.geometry, origin, direction, options, target); + } + + /** Local-space AABB of the whole mesh (root node bounds). */ + public getRootBounds(outMin: Vector3, outMax: Vector3): void { + const B = this._bounds; + if (this.nodeCount === 0) { outMin.set(0, 0, 0); outMax.set(0, 0, 0); return; } + outMin.set(B[0], B[1], B[2]); + outMax.set(B[3], B[4], B[5]); + } + + /** Vertex indices of a triangle. */ + public getTriangle(triIndex: number, out: [number, number, number] = [0, 0, 0]): [number, number, number] { + out[0] = this._indices[triIndex * 3]; + out[1] = this._indices[triIndex * 3 + 1]; + out[2] = this._indices[triIndex * 3 + 2]; + return out; + } + + /** Sub-geometry index of a triangle (0 when the geometry has a single range). */ + public getSubGeometryIndex(triIndex: number): number { + return MeshBVH._subOf(this._src.ranges, triIndex); + } + + /** + * Visit candidate triangles whose node boxes overlap [near, far] along + * the ray; `visit` returning true stops the walk (and makes this return true). + */ + private _traverse(ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, near: number, far: number, + visit: (tri: number, k: number) => boolean): boolean { + const ix = 1 / dx, iy = 1 / dy, iz = 1 / dz; + const B = this._bounds, N = this._info, order = this._triOrder; + const stack = this._stack; + let sp = 0; + stack[sp++] = 0; + while (sp > 0) { + const node = stack[--sp]; + const b = node * 6; + let t0 = ((ix >= 0 ? B[b] : B[b + 3]) - ox) * ix; + let t1 = ((ix >= 0 ? B[b + 3] : B[b]) - ox) * ix; + const ty0 = ((iy >= 0 ? B[b + 1] : B[b + 4]) - oy) * iy; + const ty1 = ((iy >= 0 ? B[b + 4] : B[b + 1]) - oy) * iy; + if (t0 > ty1 || ty0 > t1) continue; + if (ty0 > t0) t0 = ty0; + if (ty1 < t1) t1 = ty1; + const tz0 = ((iz >= 0 ? B[b + 2] : B[b + 5]) - oz) * iz; + const tz1 = ((iz >= 0 ? B[b + 5] : B[b + 2]) - oz) * iz; + if (t0 > tz1 || tz0 > t1) continue; + if (tz0 > t0) t0 = tz0; + if (tz1 < t1) t1 = tz1; + if (t1 < near || t0 > far) continue; + + const a = N[node * 2], cnt = N[node * 2 + 1]; + if (cnt > 0) { + for (let i = a, e = a + cnt; i < e; i++) { + const tri = order[i]; + if (visit(tri, tri * 3)) return true; + } + } else { + stack[sp++] = a + 1; + stack[sp++] = a; + } + } + return false; + } + + private static _subOf(ranges: TriRange[], tri: number): number { + for (let i = 0; i < ranges.length; i++) { + const r = ranges[i]; + if (tri >= r.start && tri < r.start + r.count) return r.sub; + } + return 0; + } + + private static _fill(hit: MeshBVHHit, src: TriSource, tri: number, t: number, u: number, v: number, det: number, + ox: number, oy: number, oz: number, dx: number, dy: number, dz: number): MeshBVHHit { + hit.t = t; hit.triIndex = tri; hit.u = u; hit.v = v; + hit.frontFace = det > 0; + hit.subGeometryIndex = MeshBVH._subOf(src.ranges, tri); + hit.point.set(ox + dx * t, oy + dy * t, oz + dz * t); + const P = src.pos.data, ps = src.pos.stride, po = src.pos.offset, I = src.indices; + const k = tri * 3; + const a = (I ? I[k] : k) * ps + po, b = (I ? I[k + 1] : k + 1) * ps + po, c = (I ? I[k + 2] : k + 2) * ps + po; + const e1x = P[b] - P[a], e1y = P[b + 1] - P[a + 1], e1z = P[b + 2] - P[a + 2]; + const e2x = P[c] - P[a], e2y = P[c + 1] - P[a + 1], e2z = P[c + 2] - P[a + 2]; + const n = hit.faceNormal; + n.set(e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x); + const l = n.length; + if (l > 0) n.multiplyScalar(1 / l); + return hit; + } + + /** + * Sort `out[first..]` by distance and drop repeats of the same crossing: + * a ray through an edge or vertex shared by several triangles hits each + * of them at the same t (on the same side). + */ + private static _sortFrom(out: MeshBVHHit[], first: number, src: TriSource): void { + if (out.length - first < 2) return; + const tail = out.splice(first).sort((x, y) => x.t - y.t); + let prev: MeshBVHHit = null; + for (const h of tail) { + if (prev && h.frontFace === prev.frontFace && h.t - prev.t <= 1e-7 * Math.max(1, prev.t) + && MeshBVH._shareVertex(src, h.triIndex, prev.triIndex)) continue; + out.push(h); + prev = h; + } + } + + /** Whether two triangles share a vertex (by index, or by position for unwelded meshes). */ + private static _shareVertex(src: TriSource, ta: number, tb: number): boolean { + const I = src.indices, P = src.pos.data, ps = src.pos.stride, po = src.pos.offset; + for (let i = 0; i < 3; i++) { + const a = I ? I[ta * 3 + i] : ta * 3 + i; + for (let j = 0; j < 3; j++) { + const b = I ? I[tb * 3 + j] : tb * 3 + j; + if (a === b) return true; + const pa = a * ps + po, pb = b * ps + po; + if (P[pa] === P[pb] && P[pa + 1] === P[pb + 1] && P[pa + 2] === P[pb + 2]) return true; + } + } + return false; + } + + private static _longestAxis(B: Float32Array, l: number, r: number): number { + // Extent of the union of both children along each axis. + const ex = Math.max(B[l + 3], B[r + 3]) - Math.min(B[l], B[r]); + const ey = Math.max(B[l + 4], B[r + 4]) - Math.min(B[l + 1], B[r + 1]); + const ez = Math.max(B[l + 5], B[r + 5]) - Math.min(B[l + 2], B[r + 2]); + return ex >= ey && ex >= ez ? 0 : (ey >= ez ? 1 : 2); + } +} diff --git a/src/event/eventConst/PointerEvent3D.ts b/src/event/eventConst/PointerEvent3D.ts index ee1579110..1a8589bd0 100644 --- a/src/event/eventConst/PointerEvent3D.ts +++ b/src/event/eventConst/PointerEvent3D.ts @@ -1,13 +1,32 @@ import { Vector2 } from '../../math/Vector2'; import { Vector3 } from '../../math/Vector3'; import { CEvent } from '../CEvent'; +import type { HitInfo } from '../../components/shape/ColliderShape'; type pickResult = { - meshID: number, - worldPos: Vector3, - worldNormal: Vector3, - screenUv?: Vector2, - distance?: number + meshID: number, + worldPos: Vector3, + worldNormal: Vector3, + screenUv?: Vector2, + distance?: number, + /** `bound` mode: hit point in the collider's local space. */ + localPos?: Vector3, + /** `bound` mode, mesh colliders: geometric normal of the hit triangle (world space). */ + faceNormal?: Vector3, + /** `bound` mode, mesh colliders: triangle index into the index buffer. */ + faceIndex?: number, + /** `bound` mode, mesh colliders: barycentric weights of the hit triangle. */ + barycentric?: Vector3, + /** `bound` mode, mesh colliders: interpolated `uv`, if the geometry has one. */ + uv?: Vector2, + /** `bound` mode, mesh colliders: interpolated `TEXCOORD_1`, if the geometry has one. */ + uv1?: Vector2, + /** `bound` mode, mesh colliders: sub-geometry (material slot) of the hit triangle. */ + subGeometryIndex?: number, + /** `bound` mode, mesh colliders: whether the front side was hit. */ + frontFace?: boolean, + /** `bound` mode: every collider hit by the ray, nearest first (`hits[0]` is the target). */ + hits?: HitInfo[], } /** diff --git a/src/gfx/graphics/webGpu/core/buffer/GPUBufferBase.ts b/src/gfx/graphics/webGpu/core/buffer/GPUBufferBase.ts index 83ec1e320..38676464f 100644 --- a/src/gfx/graphics/webGpu/core/buffer/GPUBufferBase.ts +++ b/src/gfx/graphics/webGpu/core/buffer/GPUBufferBase.ts @@ -38,6 +38,7 @@ export class GPUBufferBase { public visibility: number = GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE; protected mapAsyncBuffersOutstanding = 0; protected mapAsyncReady: GPUBuffer[]; + private _warnedPendingStaging = false; private _dataView: Float32Array; /** The Context3D this buffer is bound to. Set on first GPU use via `bindCtx`. */ @@ -499,6 +500,14 @@ export class GPUBufferBase { } } + /** Max idle staging buffers kept in `mapAsyncReady`; extras are destroyed + * when their mapAsync resolves so a burst of slow frames (asset parsing, + * hidden tab, GPU stall) cannot pin dozens of full-size copies forever. */ + protected static readonly MAX_IDLE_STAGING = 3; + /** In-flight `mapAsync` count above which we warn — a real "GPU has not + * handed the staging buffer back" signal, not the total pool size. */ + protected static readonly WARN_PENDING_STAGING = 60; + public mapAsyncWrite(floatArray: FloatArray, len: number) { let mapAsyncArray: Float32Array; if (floatArray instanceof Float64Array) { @@ -518,7 +527,6 @@ export class GPUBufferBase { if (tBuffer['usedSize'] == mapAsyncArray.byteLength) break; tBuffer.destroy(); - this.mapAsyncBuffersOutstanding--; tBuffer = null; } if (!tBuffer) { @@ -528,10 +536,19 @@ export class GPUBufferBase { mappedAtCreation: true, }); tBuffer['usedSize'] = mapAsyncArray.byteLength; - this.mapAsyncBuffersOutstanding++; - if (this.mapAsyncBuffersOutstanding > 20) { - console.warn(` Warning: mapAsync requests from ${this.mapAsyncBuffersOutstanding} frames ago have not resolved yet. MB of staging buffers allocated.`); + // `mapAsyncBuffersOutstanding` counts staging buffers whose + // mapAsync has not resolved yet. It used to count every buffer + // ever created (never decremented on reuse), so after one slow + // startup burst it stayed above the threshold and this warning + // fired on every frame for the rest of the session. + // Warn once per backlog episode (pipeline compilation on the + // first frames routinely stalls map callbacks for 20+ frames), + // then stay quiet until the backlog has drained. + if (this.mapAsyncBuffersOutstanding > GPUBufferBase.WARN_PENDING_STAGING && !this._warnedPendingStaging) { + this._warnedPendingStaging = true; + const mb = (this.mapAsyncBuffersOutstanding * mapAsyncArray.byteLength / (1024 * 1024)).toFixed(2); + console.warn(`[GPUBufferBase] ${this.mapAsyncBuffersOutstanding} mapAsync staging uploads still pending (${mb} MB); the GPU is falling behind CPU-side matrix uploads.`); } } let a = new Float32Array(mapAsyncArray.buffer, mapAsyncArray.byteOffset, len); @@ -541,9 +558,22 @@ export class GPUBufferBase { const commandEncoder = device.createCommandEncoder(); commandEncoder.copyBufferToBuffer(tBuffer, 0, destBuffer, 0, len * 4); device.queue.submit([commandEncoder.finish()]); + this.mapAsyncBuffersOutstanding++; tBuffer.mapAsync(GPUMapMode.WRITE).then( - () => this.mapAsyncReady.push(tBuffer), + () => { + this.mapAsyncBuffersOutstanding--; + if (this.mapAsyncBuffersOutstanding === 0) this._warnedPendingStaging = false; + // Buffer was destroyed (or pool is already full) → release + // instead of hoarding a full-size copy. + if (!this.mapAsyncReady || this.mapAsyncReady.length >= GPUBufferBase.MAX_IDLE_STAGING) { + tBuffer.unmap(); + tBuffer.destroy(); + } else { + this.mapAsyncReady.push(tBuffer); + } + }, (err) => { + this.mapAsyncBuffersOutstanding--; // device.destroy() during dispose rejects pending mapAsync with AbortError. if (err?.name !== 'AbortError') throw err; }, @@ -576,6 +606,14 @@ export class GPUBufferBase { try { this._readBuffer.destroy(); } catch { /* ignore */ } this._readBuffer = null; } + if (this.mapAsyncReady) { + for (const b of this.mapAsyncReady) { + try { b.unmap(); b.destroy(); } catch { /* ignore */ } + } + // Null (not []) so in-flight mapAsync resolutions release their + // buffer instead of re-populating a pool nobody will drain. + this.mapAsyncReady = null; + } this._boundCtx = null; } diff --git a/src/gfx/graphics/webGpu/core/buffer/MatrixGPUBuffer.ts b/src/gfx/graphics/webGpu/core/buffer/MatrixGPUBuffer.ts index 41dd8ee86..351727afa 100644 --- a/src/gfx/graphics/webGpu/core/buffer/MatrixGPUBuffer.ts +++ b/src/gfx/graphics/webGpu/core/buffer/MatrixGPUBuffer.ts @@ -20,58 +20,9 @@ export class MatrixGPUBuffer extends GPUBufferBase { this.createBuffer(GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | usage, size, data, "MatrixGPUBuffer"); } + /** Legacy name — same staging-buffer upload as `mapAsyncWrite`. */ public writeBufferByHeap(floatArray: FloatArray, len: number) { - let mapAsyncArray: Float32Array; - if (floatArray instanceof Float64Array) { - mapAsyncArray = new Float32Array(floatArray); - } else { - mapAsyncArray = floatArray as Float32Array; - } - // Upload data using mapAsync and a queue of staging buffers. - let bytesLen = len; - // Touch .buffer to trigger lazy bind on first call - void this.buffer; - let device = this._boundCtx!.device; - if (mapAsyncArray.length > 0) { - let tBuffer: GPUBuffer = null; - while (this.mapAsyncReady.length) { - tBuffer = this.mapAsyncReady.shift(); - if (tBuffer['usedSize'] == mapAsyncArray.byteLength) - break; - tBuffer.destroy(); - this.mapAsyncBuffersOutstanding--; - tBuffer = null; - } - if (!tBuffer) { - tBuffer = device.createBuffer({ - size: mapAsyncArray.byteLength, - usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE, - mappedAtCreation: true, - }); - tBuffer['usedSize'] = mapAsyncArray.byteLength; - this.mapAsyncBuffersOutstanding++; - if (this.mapAsyncBuffersOutstanding > 10) { - // ${(this.mapAsync.value * this.mapAsyncBuffersOutstanding).toFixed(2)} - console.warn(` Warning: mapAsync requests from ${this.mapAsyncBuffersOutstanding} frames ago have not resolved yet. MB of staging buffers allocated.`); - } - } - let a = new Float32Array(mapAsyncArray.buffer, mapAsyncArray.byteOffset, len); - let b = new Float32Array(tBuffer.getMappedRange(0, len * 4)) - b.set(a); - tBuffer.unmap(); - const commandEncoder = device.createCommandEncoder(); - commandEncoder.copyBufferToBuffer(tBuffer, 0, this.buffer, 0, len * 4); - // TODO: combine this submit with the main one, but we'll have to delay calling mapAsync until after the submit. - device.queue.submit([commandEncoder.finish()]); - // TODO: use this data during rendering. - tBuffer.mapAsync(GPUMapMode.WRITE).then( - () => this.mapAsyncReady.push(tBuffer), - (err) => { - // device.destroy() during dispose rejects pending mapAsync with AbortError. - if (err?.name !== 'AbortError') throw err; - }, - ); - } + this.mapAsyncWrite(floatArray, len); } } diff --git a/src/gfx/graphics/webGpu/shader/RenderShaderPass.ts b/src/gfx/graphics/webGpu/shader/RenderShaderPass.ts index 75900d6af..2925b763f 100644 --- a/src/gfx/graphics/webGpu/shader/RenderShaderPass.ts +++ b/src/gfx/graphics/webGpu/shader/RenderShaderPass.ts @@ -1313,20 +1313,15 @@ export class RenderShaderPass extends ShaderPassBase { this.shaderVariant = ShaderReflection.genRenderShaderVariant(this); let reflection = ShaderReflection.poolGetReflection(this.shaderVariant); if (!reflection) { - // The shaderReflection instance is shared across re-runs on the - // same ShaderPassBase. Re-parsing with a changed define (e.g. - // USE_VIDEO_TEXTURE flipping from false → true after the video - // texture loads) produces a new variable type at the same - // binding slot. Without clearing the previous groups[]/variables{} - // entries, `combineShaderReflectionVarInfo` sees aInfo (stale) - // vs bInfo (new) and emits `dataType not match` even though the - // pipeline actually builds correctly from the fresh parse. - if (this.shaderReflection) { - this.shaderReflection.groups = []; - this.shaderReflection.variables = {}; - this.shaderReflection.vs_variables = []; - this.shaderReflection.fs_variables = []; - } + // Start from a fresh reflection. The current one may be the + // pooled reflection of the previous variant (taken from the pool + // below), so it must not be cleared or refilled in place: other + // passes of that variant would then build their bind group + // layouts from this variant's bindings. Re-parsing into the old + // groups[]/variables{} would also mix stale entries with the + // new ones (e.g. USE_VIDEO_TEXTURE flipping after the video + // texture loads changes the type at a binding slot). + this.shaderReflection = new ShaderReflection(); let vsPreShader = Preprocessor.parse(this._destVS, this.defineValue); vsPreShader = Preprocessor.parse(vsPreShader, this.defineValue); diff --git a/src/gfx/renderJob/graph/passes/CausticsPass.ts b/src/gfx/renderJob/graph/passes/CausticsPass.ts new file mode 100644 index 000000000..03fda070a --- /dev/null +++ b/src/gfx/renderJob/graph/passes/CausticsPass.ts @@ -0,0 +1,455 @@ +import { WaterWaves_wgsl } from '../../../../assets/shader/materials/WaterShader'; +import { ILight } from '../../../../components/lights/ILight'; +import { LightType } from '../../../../components/lights/LightData'; +import { WaterFootprintBindings, waterFootprintWGSL } from '../../../../components/renderer/WaterFootprint'; +import { WaterRenderer } from '../../../../components/renderer/WaterRenderer'; +import { WATER_MAX_WAVES } from '../../../../materials/WaterMaterial'; +import { Camera3D } from '../../../../core/Camera3D'; +import { Vector3 } from '../../../../math/Vector3'; +import { RenderTexture } from '../../../../textures/RenderTexture'; +import { Context3D } from '../../../graphics/webGpu/Context3D'; +import { Preprocessor } from '../../../graphics/webGpu/shader/util/Preprocessor'; +import { ComponentCollect } from '../../collect/ComponentCollect'; +import { EntityCollect } from '../../collect/EntityCollect'; +import { GBufferFrame } from '../../frame/GBufferFrame'; +import { RenderGraphBuilder, RenderGraphPass, RenderGraphPassContext } from '../RenderGraphPass'; +import { COLOR_BUFFER } from './ColorPass'; +import { MAIN_COLOR_RT } from './GBufferResourcePass'; +import { MAIN_DEPTH_TEXTURE } from './PreDepthPass'; + +/** Must match COLOR_BUFFER's format. */ +const COLOR_FORMAT: GPUTextureFormat = 'rgba16float'; +/** Water surfaces handled per frame. */ +const MAX_WATERS = 4; +/** See CAUSTICS_WGSL for the layout. */ +const HEADER_FLOATS = 40; +const WAVE_FLOATS = WATER_MAX_WAVES * 4; +const WATER_FLOATS = 16 + WAVE_FLOATS + 16; +/** First binding of the footprint masks. */ +const FOOTPRINT_BINDING = 2; +/** First binding of the interactive ripple heights, after the masks and their sampler. */ +const RIPPLE_BINDING = FOOTPRINT_BINDING + 5; +const UNIFORM_BYTES = (HEADER_FLOATS + MAX_WATERS * WATER_FLOATS) * 4; + +/** + * Sunlight caustics under {@link WaterRenderer} surfaces. For every opaque + * pixel below a surface, the light refracted through the surface is + * focused or spread by its curvature: a ray entering where the height + * field is h reaches depth d displaced by d * k * grad(h), so the light + * there is scaled by 1 / |det(I + d * k * hessian(h))|. The curvature + * comes from the waves plus the fine ripples ({@link WaterRenderer.detailScale}) + * that the waves are too long to provide; the same ripples bend the surface + * normal, so what is seen on the surface and below it matches. The scene color is multiplied + * by the result, weighted by how much the receiving surface faces the + * refracted sunlight. + * + * {@link ForwardRendererJob} adds it after the opaque scene and the sky, + * before the scene color pyramid, when `setting.render.water` is true, so + * the caustics are seen both through the surface and underwater. It does + * nothing without a directional light. + * + * @group Graph + */ +export class CausticsPass extends RenderGraphPass { + public readonly name: string = 'CausticsPass'; + + private _device!: GPUDevice; + private _pipeline!: GPURenderPipeline; + private _layout!: GPUBindGroupLayout; + private _uniform!: GPUBuffer; + private _uniformData = new Float32Array(UNIFORM_BYTES / 4); + private _waters: WaterRenderer[] = []; + private _active: WaterRenderer[] = []; + private _footprints = new WaterFootprintBindings(); + private _noRipples: GPUTexture | null = null; + private _depthSrc: GPUTexture | null = null; + private _depthView: GPUTextureView | null = null; + + public setup(b: RenderGraphBuilder): void { + this._device = b.context3D.device as GPUDevice; + const setting = b.context3D.engine?.setting?.render; + if (setting?.zPrePass) b.read(MAIN_DEPTH_TEXTURE); + b.write(COLOR_BUFFER); + b.useRenderTarget(MAIN_COLOR_RT); + this._createPipeline(!!setting?.useLogDepth); + } + + public destroy(): void { + this._uniform?.destroy(); + this._footprints.destroy(); + this._noRipples?.destroy(); + this._noRipples = null; + this._waters.length = 0; + this._active.length = 0; + this._depthSrc = null; + this._depthView = null; + } + + public execute(ctx: RenderGraphPassContext): void { + const view = ctx.view; + const camera = view.camera; + const sun = this._findSun(EntityCollect.instance.getLights(view.scene)); + if (!sun) return; + const mask = (this.layerMask & (camera?.cullingMask ?? 0xFFFFFFFF)) >>> 0; + ComponentCollect.collectByTypeLayered(view, WaterRenderer, mask, this._waters); + const waters = this._active; + waters.length = 0; + for (const w of this._waters) { + if (waters.length < MAX_WATERS && w.transform?.enable && w.caustics && w.causticsIntensity > 0) waters.push(w); + } + if (waters.length === 0) return; + + const engine = view.engine3D; + const colorTex = ctx.get(COLOR_BUFFER); + const depthView = this._getSceneDepthView(engine.context3D); + if (!colorTex || !depthView) return; + this._writeUniforms(waters, camera, sun); + + const bg = this._device.createBindGroup({ + layout: this._layout, + entries: [ + { binding: 0, resource: { buffer: this._uniform } }, + { binding: 1, resource: depthView }, + ...this._footprints.entries(this._device, waters.map((w) => w.footprint), FOOTPRINT_BINDING), + ...this._rippleEntries(waters), + ], + }); + const gpu = engine.context3D.gpuContext; + const command = gpu.beginCommandEncoder(); + const enc = command.beginRenderPass({ + label: 'Caustics', + colorAttachments: [{ view: (colorTex.getGPUTexture() as GPUTexture).createView(), loadOp: 'load', storeOp: 'store' }], + }); + enc.setPipeline(this._pipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + gpu.endCommandEncoder(command); + } + + /** Each water's ripple heights, or a 1x1 placeholder. */ + private _rippleEntries(waters: WaterRenderer[]): GPUBindGroupEntry[] { + if (!this._noRipples) { + this._noRipples = this._device.createTexture({ + label: 'Caustics:NoRipples', + size: [1, 1, 1], + format: 'rgba32float', + usage: GPUTextureUsage.TEXTURE_BINDING, + }); + } + const entries: GPUBindGroupEntry[] = []; + for (let i = 0; i < MAX_WATERS; i++) { + const view = waters[i]?.rippleView ?? this._noRipples.createView(); + entries.push({ binding: RIPPLE_BINDING + i, resource: view }); + } + return entries; + } + + /** Travel direction of the first enabled directional light's rays. */ + private _findSun(lights: ILight[]): Vector3 | null { + for (const light of lights) { + const enabled = (light as any).enable ?? true; + if (enabled && light.lightData.lightType === LightType.DirectionLight) return light.lightData.direction; + } + return null; + } + + /** Opaque depth: the water surface skips the depth prepass and is drawn after this pass. */ + private _getSceneDepthView(context3D: Context3D): GPUTextureView | null { + const frame = GBufferFrame.getGBufferFrame(GBufferFrame.colorPass_GBuffer, context3D); + const tex = (frame.zPreTexture ?? frame.depthTexture) as RenderTexture; + const gpuTex = tex?.getGPUTexture() as GPUTexture; + if (!gpuTex) return null; + if (gpuTex !== this._depthSrc) { + this._depthSrc = gpuTex; + this._depthView = gpuTex.createView({ aspect: 'depth-only' }); + } + return this._depthView; + } + + private _writeUniforms(waters: WaterRenderer[], camera: Camera3D, sun: Vector3): void { + const f = this._uniformData; + f.set(camera.projectionMatrixInv.rawData, 0); + f.set(camera.transform.worldMatrix.rawData, 16); + // Light data holds the direction the rays travel; the shader wants the way to the sun. + const len = Math.hypot(sun.x, sun.y, sun.z) || 1; + f[32] = -sun.x / len; f[33] = -sun.y / len; f[34] = -sun.z / len; f[35] = 0; + f[36] = waters.length; + f[37] = camera.far; + for (let w = 0; w < waters.length; w++) { + const water = waters[w]; + const o = HEADER_FLOATS + w * WATER_FLOATS; + f.set(water.invWorldMatrix.rawData, o); + for (let i = 0; i < WATER_MAX_WAVES; i++) f.set(water.waveVector(i), o + 16 + i * 4); + // Fields after the waves, in Water struct order. + const q = o + 16 + WAVE_FLOATS; + f[q] = water.baseHeight; + f[q + 1] = water.time; + f[q + 2] = water.causticsIntensity; + f[q + 3] = Math.max(water.detailScale, 1e-3); + f.set(water.footprintBounds, q + 4); + f[q + 8] = water.footprint ? 1 : 0; + f[q + 9] = water.hasRipples ? 1 : 0; + f.set(water.rippleBounds, q + 12); + } + this._device.queue.writeBuffer(this._uniform, 0, f.buffer, f.byteOffset, UNIFORM_BYTES); + } + + private _createPipeline(useLogDepth: boolean): void { + const device = this._device; + this._uniform = device.createBuffer({ + label: 'Caustics:Uniforms', + size: UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + this._layout = device.createBindGroupLayout({ + label: 'Caustics:BGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ...WaterFootprintBindings.layoutEntries(FOOTPRINT_BINDING), + ...[0, 1, 2, 3].map((i): GPUBindGroupLayoutEntry => ({ + binding: RIPPLE_BINDING + i, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' }, + })), + ], + }); + const module = device.createShaderModule({ + label: 'Caustics', + code: Preprocessor.parse(CAUSTICS_WGSL, { USE_LOGDEPTH: useLogDepth }), + }); + this._pipeline = device.createRenderPipeline({ + label: 'Caustics', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._layout] }), + vertex: { module, entryPoint: 'vs' }, + fragment: { + module, entryPoint: 'fs', + // Multiplies the scene color. + targets: [{ + format: COLOR_FORMAT, + blend: { + color: { srcFactor: 'dst', dstFactor: 'zero', operation: 'add' }, + alpha: { srcFactor: 'zero', dstFactor: 'one', operation: 'add' }, + }, + }], + }, + primitive: { topology: 'triangle-list', cullMode: 'none' }, + }); + } +} + +const CAUSTICS_WGSL = /* wgsl */` +${WaterWaves_wgsl} + +struct Water { + // world to local + invWorld: mat4x4f, + waves: array, + // x = undisplaced surface height, y = wave time, z = caustics intensity, w = detail scale + params: vec4f, + // local xz bounds: min x, min z, max x, max z + bounds: vec4f, + // x = 1 when the footprint has a mask (custom surface mesh), y = 1 with interactive ripples + mask: vec4f, + // local xz bounds of the ripple grid + rippleBounds: vec4f, +}; + +struct Params { + projInv: mat4x4f, + cameraWorld: mat4x4f, + // toward the sun + sun: vec4f, + // x = water count, y = camera far + info: vec4f, + waters: array, +}; + +@group(0) @binding(0) var p: Params; +@group(0) @binding(1) var sceneDepth: texture_depth_2d; +${waterFootprintWGSL(FOOTPRINT_BINDING)} + +// Interactive ripple heights (WaterRipples) over each water's local bounds. +@group(0) @binding(${RIPPLE_BINDING}) var rippleMap0: texture_2d; +@group(0) @binding(${RIPPLE_BINDING + 1}) var rippleMap1: texture_2d; +@group(0) @binding(${RIPPLE_BINDING + 2}) var rippleMap2: texture_2d; +@group(0) @binding(${RIPPLE_BINDING + 3}) var rippleMap3: texture_2d; + +fn rippleSize(i: u32) -> vec2i { + switch (i) { + case 0u: { return vec2i(textureDimensions(rippleMap0)); } + case 1u: { return vec2i(textureDimensions(rippleMap1)); } + case 2u: { return vec2i(textureDimensions(rippleMap2)); } + default: { return vec2i(textureDimensions(rippleMap3)); } + } +} + +fn rippleTexel(i: u32, c: vec2i, size: vec2i) -> f32 { + let t = clamp(c, vec2i(0), size - 1); + switch (i) { + case 0u: { return textureLoad(rippleMap0, t, 0).r; } + case 1u: { return textureLoad(rippleMap1, t, 0).r; } + case 2u: { return textureLoad(rippleMap2, t, 0).r; } + default: { return textureLoad(rippleMap3, t, 0).r; } + } +} + +// Bilinear ripple height at grid coordinates c + o (o in -1..1), from the 4x4 texels +// around c (texels, row-major from floor(c) - 1); none off the grid. +fn rippleAt(texels: ptr>, c: vec2f, o: vec2i, size: vec2f) -> f32 { + let coord = c + vec2f(o); + if (any(coord < vec2f(-0.5)) || any(coord > size - 0.5)) { + return 0.0; + } + let f = c - floor(c); + let k = (o.y + 1) * 4 + o.x + 1; + let top = mix((*texels)[k], (*texels)[k + 1], f.x); + let bottom = mix((*texels)[k + 4], (*texels)[k + 5], f.x); + return mix(top, bottom, f.y); +} + +// Adds water i's interactive ripples at world xz: finite differences on the grid, carried +// from local to world axes (local xz = A world xz, A from the inverse world matrix). +fn addRipples(i: u32, slope: ptr, xz: vec2f) { + let w = p.waters[i]; + if (w.mask.y < 0.5) { + return; + } + let local = (w.invWorld * vec4f(xz.x, w.params.x, xz.y, 1.0)).xz; + let isize = rippleSize(i); + let size = vec2f(isize); + let cell = (w.rippleBounds.zw - w.rippleBounds.xy) / size; + let c = (local - w.rippleBounds.xy) / cell - 0.5; + // One texture read site for all nine samples: unrolled per sample, the switch over the + // four maps makes the shader too large for software rasterizers to compile. + var texels: array; + let base = vec2i(floor(c)) - 1; + for (var k = 0; k < 16; k++) { + texels[k] = rippleTexel(i, base + vec2i(k % 4, k / 4), isize); + } + let h = rippleAt(&texels, c, vec2i(0, 0), size); + let hx0 = rippleAt(&texels, c, vec2i(-1, 0), size); + let hx1 = rippleAt(&texels, c, vec2i(1, 0), size); + let hz0 = rippleAt(&texels, c, vec2i(0, -1), size); + let hz1 = rippleAt(&texels, c, vec2i(0, 1), size); + let hxz = rippleAt(&texels, c, vec2i(1, 1), size) - rippleAt(&texels, c, vec2i(1, -1), size) + - rippleAt(&texels, c, vec2i(-1, 1), size) + rippleAt(&texels, c, vec2i(-1, -1), size); + let g = vec2f(hx1 - hx0, hz1 - hz0) / (2.0 * cell); + let lxx = (hx1 - 2.0 * h + hx0) / (cell.x * cell.x); + let lzz = (hz1 - 2.0 * h + hz0) / (cell.y * cell.y); + let lxz = hxz / (4.0 * cell.x * cell.y); + // A = [[a, b], [c, d]]: world gradient = A^T g, world Hessian = A^T H A. + let a = w.invWorld[0].x; + let b = w.invWorld[2].x; + let cc = w.invWorld[0].z; + let d = w.invWorld[2].z; + (*slope).grad += vec2f(a * g.x + cc * g.y, b * g.x + d * g.y); + let hxx = a * (a * lxx + cc * lxz) + cc * (a * lxz + cc * lzz); + let hzz = b * (b * lxx + d * lxz) + d * (b * lxz + d * lzz); + let hxzw = a * (b * lxx + d * lxz) + cc * (b * lxz + d * lzz); + (*slope).hess += vec3f(hxx, hxzw, hzz); +} + +const IOR: f32 = 1.333; +// Lower bound of |det|: the sun's size and the ripples' spread keep the focus finite. +const MIN_DET: f32 = 0.25; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var v = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(v[vi], 0.0, 1.0); +} + +// Slope and curvature of water i's surface at xz: its waves plus the fine ripples. +fn surfaceSlope(i: u32, xz: vec2f) -> WaterSlope { + let w = p.waters[i]; + let t = w.params.y; + var slope = WaterSlope(vec2f(0.0), vec3f(0.0)); + for (var j = 0; j < ${WATER_MAX_WAVES}; j++) { + let wave = w.waves[j]; + if (wave.w > 0.0) { + let k = 2.0 * WATER_PI / wave.w; + let d = normalize(wave.xy); + waterSlopeTerm(&slope, d, k, wave.z, k * (dot(d, xz) - sqrt(WATER_GRAVITY / k) * t)); + } + } + waterDetail(&slope, xz, t, w.params.w, 0.0); + addRipples(i, &slope, xz); + return slope; +} + +fn worldPosition(pos: vec2f, dim: vec2f) -> vec3f { + let uv = pos / dim; + let ndc = vec2f(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0); + let d = textureLoad(sceneDepth, vec2i(pos), 0); + let farH = p.projInv * vec4f(ndc, 1.0, 1.0); + let ray = farH.xyz / farH.w; + #if USE_LOGDEPTH + let viewZ = pow(p.info.y + 1.0, d) - 1.0; + #else + let v = p.projInv * vec4f(0.0, 0.0, d, 1.0); + let viewZ = v.z / v.w; + #endif + return (p.cameraWorld * vec4f(ray * (viewZ / ray.z), 1.0)).xyz; +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let dim = vec2f(textureDimensions(sceneDepth)); + let world = worldPosition(pos.xy, dim); + // Receiving surface normal and pixel footprint from the reconstructed positions (before any discard). + let dx = dpdx(world); + let dy = dpdy(world); + var n = normalize(cross(dy, dx)); + // Geometric mean: at grazing views the pixel stretches along one axis only. + let footprint = sqrt(length(dx) * length(dy)); + let toCamera = p.cameraWorld[3].xyz - world; + if (dot(n, toCamera) < 0.0) { + n = -n; + } + + // Sunlight inside the water, travelling down. + let L = normalize(p.sun.xyz); + let down = refract(-L, vec3f(0.0, 1.0, 0.0), 1.0 / IOR); + if (L.y <= 0.0) { + discard; + } + + var light = 1.0; + var covered = false; + for (var i = 0u; i < u32(p.info.x); i++) { + if (!insideFootprint(i, world)) { + continue; + } + let w = p.waters[i]; + let surface = w.params.x + waterHeight(w.waves, world.xz, w.params.y); + let depth = surface - world.y; + if (depth <= 0.0) { + continue; + } + // Follow the sunlight back up to where it entered: light entering at q lands at + // q + s * grad(h(q)), with s the path times the fraction of a surface tilt the + // refraction turns it by. Solve for the q that lands here by fixed-point iteration. + let path = depth / max(-down.y, 0.1); + let flat = world.xz - down.xz * path; + let s = path * (1.0 - 1.0 / IOR); + var q = flat; + for (var it = 0; it < 3; it++) { + q = flat - s * surfaceSlope(i, q).grad; + } + // Light density there: the area ratio 1 / |det(I + s * H)|. + let hess = surfaceSlope(i, q).hess; + let det = (1.0 + s * hess.x) * (1.0 + s * hess.z) - s * s * hess.y * hess.y; + let focus = 1.0 / max(abs(det), MIN_DET); + let facing = clamp(dot(n, -down), 0.0, 1.0); + // Fade out where the lines get thinner than a pixel and would only flicker. + let resolved = 1.0 - smoothstep(0.05, 0.2, footprint / w.params.w); + light = 1.0 + w.params.z * (focus - 1.0) * facing * resolved; + covered = true; + break; + } + if (!covered) { + discard; + } + return vec4f(vec3f(max(light, 0.0)), 1.0); +} +`; diff --git a/src/gfx/renderJob/graph/passes/FluidPass.ts b/src/gfx/renderJob/graph/passes/FluidPass.ts new file mode 100644 index 000000000..46e60ef4c --- /dev/null +++ b/src/gfx/renderJob/graph/passes/FluidPass.ts @@ -0,0 +1,1009 @@ +import { FluidAnisotropy_wgsl, FluidEllipsoid_wgsl } from '../../../../assets/shader/fluid/FluidAnisotropy_shader'; +import { + FluidBilateralBlur_wgsl, FluidComposite_wgsl, FluidDebugView_wgsl, FluidGaussianBlur_wgsl, FluidGeometricThickness_wgsl, + FluidNarrowRangeFilter_wgsl, FluidParticle_wgsl, FluidSceneLinearDepth_wgsl, +} from '../../../../assets/shader/fluid/FluidParticle_shader'; +import { DirectLight } from '../../../../components/lights/DirectLight'; +import { FluidDebug, FluidDepthFilter, FluidRenderer, FluidThicknessMode } from '../../../../components/renderer/FluidRenderer'; +import { Camera3D } from '../../../../core/Camera3D'; +import { View3D } from '../../../../core/View3D'; +import { Matrix4 } from '../../../../math/Matrix4'; +import { Vector3 } from '../../../../math/Vector3'; +import { RenderTexture } from '../../../../textures/RenderTexture'; +import { Context3D } from '../../../graphics/webGpu/Context3D'; +import { Preprocessor } from '../../../graphics/webGpu/shader/util/Preprocessor'; +import { ComponentCollect } from '../../collect/ComponentCollect'; +import { VisibleLayer } from '../../config/VisibleLayer'; +import { GBufferFrame } from '../../frame/GBufferFrame'; +import { RenderGraphBuilder, RenderGraphPass, RenderGraphPassContext } from '../RenderGraphPass'; +import { COLOR_BUFFER } from './ColorPass'; +import { MAIN_COLOR_RT } from './GBufferResourcePass'; +import { MAIN_DEPTH_TEXTURE } from './PreDepthPass'; + +/** Must match COLOR_BUFFER's format. */ +const COLOR_FORMAT: GPUTextureFormat = 'rgba16float'; +/** Linear view-space depth of the fluid surface; 0 = no fluid, negative = fluid hidden by the scene. */ +const DEPTH_FORMAT: GPUTextureFormat = 'r32float'; +/** Accumulated thickness; additive blending needs a blendable format. */ +const THICKNESS_FORMAT: GPUTextureFormat = 'r16float'; + +/** See FluidUniforms_wgsl for the layout. */ +const UNIFORM_BYTES = 256; +const TMP_UNIFORM_F32 = new Float32Array(UNIFORM_BYTES / 4); +/** See FluidBlurParams_wgsl for the layout. */ +const BLUR_UNIFORM_BYTES = 48; +/** Cap of the depth threshold scale at grazing angles. */ +const MAX_GRAZING_SCALE = 8; +const TMP_BLUR_F32 = new Float32Array(BLUR_UNIFORM_BYTES / 4); +/** See FluidShadeUniforms_wgsl for the layout. */ +const SHADE_UNIFORM_BYTES = 128; +const TMP_SHADE_F32 = new Float32Array(SHADE_UNIFORM_BYTES / 4); + +/** Light direction used when the fluid has no dirLight and the scene has no DirectLight. */ +const DEFAULT_LIGHT_DIR = new Vector3(-2, -1, 1).normalize(); +const TMP_LIGHT_DIR = new Vector3(); + +const RT_USAGE = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING; + +/** See FluidAnisotropy_wgsl for the layout. */ +const ANISO_UNIFORM_BYTES = 48; +const TMP_ANISO = new ArrayBuffer(ANISO_UNIFORM_BYTES); +const TMP_ANISO_U32 = new Uint32Array(TMP_ANISO); +const TMP_ANISO_F32 = new Float32Array(TMP_ANISO); +/** Hash buckets per scan block; must match SCAN_BLOCK in FluidAnisotropy_wgsl. */ +const SCAN_BLOCK = 1024; +/** The block totals are scanned by one workgroup of 256 × 4. */ +const MAX_HASH_TABLE = SCAN_BLOCK * SCAN_BLOCK; +/** Background clamp offset of the narrow-range filter, in particle radii. */ +const NARROW_RANGE_MU = 3; + +type Target = { texture: GPUTexture; view: GPUTextureView; width: number; height: number }; + +type SceneDepth = { + texture: GPUTexture; + /** Depth aspect only, so depth24plus-stencil8 also binds as texture_depth_2d. */ + sampleView: GPUTextureView; + attachView: GPUTextureView; +}; + +/** GPU state owned per {@link FluidRenderer}. */ +type FluidGpu = { + uniform: GPUBuffer; + shade: GPUBuffer; + /** Upload target for CPU particle data. */ + particleBuffer: GPUBuffer | null; + particleVersion: number; + targets: Map; + blurUniforms: Map; + aniso: AnisoGpu | null; +}; + +/** Neighbor-search and ellipsoid buffers of one {@link FluidRenderer}. */ +type AnisoGpu = { + params: GPUBuffer; + capacity: number; + tableSize: number; + cellCount: GPUBuffer; + cellStart: GPUBuffer; + blockSums: GPUBuffer; + particleCell: GPUBuffer; + sortedPos: GPUBuffer; + ellipsoids: GPUBuffer; +}; + +/** + * Screen-space fluid pass. For every enabled {@link FluidRenderer} in + * the view it: + * 1. renders the particles as sphere impostors into a linear depth + * map and, with additive blending, into a thickness map; + * 2. smooths depth with a separable bilateral blur and thickness with + * a separable gaussian blur; + * 3. shades the surface (refraction of the scene behind, absorption, + * environment reflection, specular) into `_ColorBuffer`, writing + * its depth into the scene depth so transparents sort against it. + * + * {@link ForwardRendererJob} inserts it between the opaque/transmission + * passes and the transparent passes when `setting.render.fluid` is true, + * so the fluid is clipped by opaque geometry and transparent objects + * draw over it. + * + * @group Graph + */ +export class FluidPass extends RenderGraphPass { + public readonly name: string = 'FluidPass'; + + private _device!: GPUDevice; + private _useLogDepth: boolean = false; + + private _particleBGLayout!: GPUBindGroupLayout; + private _depthPipeline!: GPURenderPipeline; + private _thicknessPipeline!: GPURenderPipeline; + private _blurBGLayout!: GPUBindGroupLayout; + private _bilateralPipeline!: GPURenderPipeline; + private _narrowRangePipeline!: GPURenderPipeline; + /** Blur layout plus the scene's linear depth (binding 2). */ + private _narrowRangeBGLayout!: GPUBindGroupLayout; + private _sceneLinearBGLayout!: GPUBindGroupLayout; + private _sceneLinearPipeline!: GPURenderPipeline; + private _narrowRange2DPipeline!: GPURenderPipeline; + private _gaussianPipeline!: GPURenderPipeline; + private _ellipsoidDepthPipeline!: GPURenderPipeline; + private _ellipsoidThicknessPipeline!: GPURenderPipeline; + private _backDepthPipeline!: GPURenderPipeline; + private _ellipsoidBackDepthPipeline!: GPURenderPipeline; + private _geometricBGLayout!: GPUBindGroupLayout; + private _geometricPipeline!: GPURenderPipeline; + private _anisoBGLayout!: GPUBindGroupLayout; + private _anisoPipelines!: Record<'clearCells' | 'countCells' | 'scanBlocks' | 'scanBlockSums' | 'addBlockOffsets' | 'scatter' | 'computeEllipsoids', GPUComputePipeline>; + private _debugBGLayout!: GPUBindGroupLayout; + private _debugPipeline!: GPURenderPipeline; + /** Fluid maps and shading parameters, shared by the color and depth-write stages. */ + private _surfaceBGLayout!: GPUBindGroupLayout; + /** Scene inputs of the color stage: color copy, sampler, environment, depth. */ + private _sceneBGLayout!: GPUBindGroupLayout; + private _compositeModule!: GPUShaderModule; + private _colorPipeline!: GPURenderPipeline; + /** Keyed by scene depth format (depth32float, or depth24plus-stencil8 with useStencil). */ + private _depthWritePipelines: Map = new Map(); + private _linearSampler!: GPUSampler; + private _emptyCubeView!: GPUTextureView; + private _lights: DirectLight[] = []; + + private _gpu: WeakMap = new WeakMap(); + private _fluids: FluidRenderer[] = []; + private _warned: WeakSet = new WeakSet(); + + private _sceneDepth: SceneDepth | null = null; + /** 2 / proj[1][1] of the current camera: world size of the view height per unit of depth. */ + private _pixelWorldPerDepth: number = 1; + /** Allocated in setup: matrices come from a pool created at engine init. */ + private _modelView!: Matrix4; + + public setup(b: RenderGraphBuilder): void { + this._device = b.context3D.device as GPUDevice; + const setting = b.context3D.engine?.setting?.render; + this._useLogDepth = !!setting?.useLogDepth; + this._modelView = new Matrix4(); + + if (setting?.zPrePass) b.read(MAIN_DEPTH_TEXTURE); + b.write(COLOR_BUFFER); + b.useRenderTarget(MAIN_COLOR_RT); + + this._createPipelines(); + } + + public destroy(): void { + this._fluids.length = 0; + this._lights.length = 0; + this._sceneDepth = null; + } + + public execute(ctx: RenderGraphPassContext): void { + const view = ctx.view; + const camera = view.camera; + const mask = (this.layerMask & (camera?.cullingMask ?? 0xFFFFFFFF)) >>> 0; + ComponentCollect.collectByTypeLayered(view, FluidRenderer, mask, this._fluids); + if (this._fluids.length === 0) return; + + const engine = view.engine3D; + const colorTex = ctx.get(COLOR_BUFFER); + const sceneDepth = this._getSceneDepth(engine.context3D); + if (!colorTex || !sceneDepth) return; + const color = colorTex.getGPUTexture() as GPUTexture; + const [screenW, screenH] = engine.context3D.presentationSize as [number, number]; + + const gpu = engine.context3D.gpuContext; + const command = gpu.beginCommandEncoder(); + for (const fluid of this._fluids) { + if (!fluid.transform || !fluid.transform.enable) continue; + const particles = this._getParticleBuffer(fluid); + if (!particles || fluid.particleCount === 0) continue; + this._renderFluid(command, view, fluid, camera, particles, sceneDepth, color, screenW, screenH); + } + gpu.endCommandEncoder(command); + } + + private _renderFluid( + command: GPUCommandEncoder, view: View3D, fluid: FluidRenderer, camera: Camera3D, particles: GPUBuffer, + sceneDepth: SceneDepth, color: GPUTexture, screenW: number, screenH: number, + ): void { + const res = this._ensureGpu(fluid); + const [dw, dh] = mapSize(fluid.depthMapSize, screenW, screenH); + const [tw, th] = mapSize(fluid.thicknessMapSize, screenW, screenH); + const depth = this._target(res, 'depth', dw, dh, DEPTH_FORMAT); + const zBuffer = this._target(res, 'zBuffer', dw, dh, 'depth32float', GPUTextureUsage.RENDER_ATTACHMENT); + const thickness = this._target(res, 'thickness', tw, th, THICKNESS_FORMAT); + this._writeUniforms(res, fluid, camera, depth, thickness, screenW, screenH); + + const count = fluid.particleCount; + // With anisotropy the particle stages draw ellipsoids from a per-frame neighbor search. + const ellipsoids = fluid.useAnisotropy ? this._computeEllipsoids(command, res, fluid, particles) : null; + const depthPipeline = ellipsoids ? this._ellipsoidDepthPipeline : this._depthPipeline; + const thicknessPipeline = ellipsoids ? this._ellipsoidThicknessPipeline : this._thicknessPipeline; + const backDepthPipeline = ellipsoids ? this._ellipsoidBackDepthPipeline : this._backDepthPipeline; + const particleBG = this._device.createBindGroup({ + layout: this._particleBGLayout, + entries: [ + { binding: 0, resource: { buffer: res.uniform } }, + { binding: 1, resource: { buffer: ellipsoids ?? particles } }, + { binding: 2, resource: sceneDepth.sampleView }, + ], + }); + const useThickness = !fluid.useFixedThickness; + { + const enc = command.beginRenderPass({ + label: 'FluidPass:Depth', + colorAttachments: [{ view: depth.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + depthStencilAttachment: { view: zBuffer.view, depthLoadOp: 'clear', depthClearValue: 1, depthStoreOp: 'discard' }, + }); + enc.setPipeline(depthPipeline); + enc.setBindGroup(0, particleBG); + enc.draw(6, count); + enc.end(); + } + if (useThickness && fluid.thicknessMode === FluidThicknessMode.Geometric) { + // Far side of the volume, then thickness = far - near per pixel. + const backDepth = this._target(res, 'backDepth', dw, dh, DEPTH_FORMAT); + const backZ = this._target(res, 'backZBuffer', dw, dh, 'depth32float', GPUTextureUsage.RENDER_ATTACHMENT); + { + const enc = command.beginRenderPass({ + label: 'FluidPass:BackDepth', + colorAttachments: [{ view: backDepth.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + depthStencilAttachment: { view: backZ.view, depthLoadOp: 'clear', depthClearValue: 0, depthStoreOp: 'discard' }, + }); + enc.setPipeline(backDepthPipeline); + enc.setBindGroup(0, particleBG); + enc.draw(6, count); + enc.end(); + } + { + const bg = this._device.createBindGroup({ + layout: this._geometricBGLayout, + entries: [ + { binding: 0, resource: { buffer: res.uniform } }, + { binding: 1, resource: depth.view }, + { binding: 2, resource: backDepth.view }, + ], + }); + const enc = command.beginRenderPass({ + label: 'FluidPass:GeometricThickness', + colorAttachments: [{ view: thickness.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + }); + enc.setPipeline(this._geometricPipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + } + } else if (useThickness) { + const enc = command.beginRenderPass({ + label: 'FluidPass:Thickness', + colorAttachments: [{ view: thickness.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + }); + enc.setPipeline(thicknessPipeline); + enc.setBindGroup(0, particleBG); + enc.draw(6, count); + enc.end(); + } + + let depthBlurred = depth; + if (fluid.enableBlurDepth) { + const div = Math.max(1, fluid.blurDepthSizeDivisor); + const bw = Math.max(1, Math.floor(dw / div)); + const bh = Math.max(1, Math.floor(dh / div)); + // Blur radius in pixels = projectedConstant / viewZ, proportional to the projected particle size. + const proj11 = camera.projectionMatrix.rawData[5]; + this._pixelWorldPerDepth = 2 / Math.abs(proj11); + const projected = fluid.blurDepthFilterSize * fluid.particleSize * 0.05 * (bh / 2) * proj11; + const radius = fluid.particleSize * 0.5; + const depthThreshold = radius * fluid.blurDepthDepthScale; + const narrow = fluid.depthFilter === FluidDepthFilter.NarrowRange; + // The narrow-range filter checks the scene behind empty samples to tell walls from free edges. + const sceneLinear = narrow ? this._renderSceneLinear(command, res, sceneDepth, dw, dh) : null; + depthBlurred = this._blur(command, res, 'depthBlur', narrow ? this._narrowRangePipeline : this._bilateralPipeline, + depth, bw, bh, DEPTH_FORMAT, fluid.blurDepthNumIterations, + projected, fluid.blurDepthMaxFilterSize, depthThreshold, radius * NARROW_RANGE_MU, + narrow ? this._narrowRange2DPipeline : null, sceneLinear); + } + let thicknessBlurred = thickness; + if (useThickness && fluid.enableBlurThickness) { + const div = Math.max(1, fluid.blurThicknessSizeDivisor); + const bw = Math.max(1, Math.floor(tw / div)); + const bh = Math.max(1, Math.floor(th / div)); + thicknessBlurred = this._blur(command, res, 'thicknessBlur', this._gaussianPipeline, thickness, bw, bh, THICKNESS_FORMAT, + fluid.blurThicknessNumIterations, Math.max(0, Math.round(fluid.blurThicknessFilterSize)), 0, 0, 0); + } + + const colorView = color.createView(); + if (fluid.debug) { + const mode = fluid.debugFeature; + const debugDepth = mode === FluidDebug.DepthTexture ? depth : depthBlurred; + const debugThickness = mode === FluidDebug.ThicknessTexture ? thickness : thicknessBlurred; + this._renderDebug(command, res, debugDepth, debugThickness, colorView); + return; + } + + // Refraction samples a copy of the scene color, since the pass draws into the original. + const sceneColor = this._target(res, 'sceneColor', color.width, color.height, COLOR_FORMAT, + GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST); + command.copyTextureToTexture({ texture: color }, { texture: sceneColor.texture }, [color.width, color.height, 1]); + const envView = this._writeShadeUniforms(res, view, fluid, camera); + this._renderComposite(command, res, depthBlurred, thicknessBlurred, sceneColor, envView, colorView, sceneDepth); + } + + private _renderComposite( + command: GPUCommandEncoder, res: FluidGpu, depth: Target, thickness: Target, sceneColor: Target, + envView: GPUTextureView, colorView: GPUTextureView, sceneDepth: SceneDepth, + ): void { + const surfaceBG = this._device.createBindGroup({ + layout: this._surfaceBGLayout, + entries: [ + { binding: 0, resource: { buffer: res.uniform } }, + { binding: 1, resource: depth.view }, + { binding: 2, resource: thickness.view }, + { binding: 3, resource: { buffer: res.shade } }, + ], + }); + const sceneBG = this._device.createBindGroup({ + layout: this._sceneBGLayout, + entries: [ + { binding: 0, resource: sceneColor.view }, + { binding: 1, resource: this._linearSampler }, + { binding: 2, resource: envView }, + { binding: 3, resource: sceneDepth.sampleView }, + ], + }); + { + // Samples the scene depth, so it cannot be the depth attachment here. + const enc = command.beginRenderPass({ + label: 'FluidPass:Color', + colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }], + }); + enc.setPipeline(this._colorPipeline); + enc.setBindGroup(0, surfaceBG); + enc.setBindGroup(1, sceneBG); + enc.draw(3); + enc.end(); + } + { + const format = sceneDepth.texture.format; + const depthAttachment: GPURenderPassDepthStencilAttachment = { + view: sceneDepth.attachView, depthLoadOp: 'load', depthStoreOp: 'store', + }; + if (format.includes('stencil')) { + depthAttachment.stencilLoadOp = 'load'; + depthAttachment.stencilStoreOp = 'store'; + } + const enc = command.beginRenderPass({ + label: 'FluidPass:DepthWrite', + colorAttachments: [], + depthStencilAttachment: depthAttachment, + }); + enc.setPipeline(this._getDepthWritePipeline(format)); + enc.setBindGroup(0, surfaceBG); + enc.draw(3); + enc.end(); + } + } + + /** Writes the composite parameters and returns the environment cube view to bind. */ + private _writeShadeUniforms(res: FluidGpu, view: View3D, fluid: FluidRenderer, camera: Camera3D): GPUTextureView { + // Direction toward the light, in view space. + const dir = TMP_LIGHT_DIR.copy(fluid.dirLight ?? this._sceneLightDirection(view) ?? DEFAULT_LIGHT_DIR); + dir.normalize(); + const m = camera.viewMatrix.rawData; + const lx = -(m[0] * dir.x + m[4] * dir.y + m[8] * dir.z); + const ly = -(m[1] * dir.x + m[5] * dir.y + m[9] * dir.z); + const lz = -(m[2] * dir.x + m[6] * dir.y + m[10] * dir.z); + + const env = fluid.environmentMap === undefined ? view.scene?.envMap : fluid.environmentMap; + const envView = env && env.textureBindingLayout?.viewDimension === 'cube' ? env.getGPUView() as GPUTextureView : null; + + const f = TMP_SHADE_F32; + f[0] = fluid.fluidColor.r; f[1] = fluid.fluidColor.g; f[2] = fluid.fluidColor.b; + f[3] = fluid.thicknessMode === FluidThicknessMode.Geometric && !fluid.useFixedThickness ? 1 : 0; + f[4] = lx; f[5] = ly; f[6] = lz; f[7] = fluid.specularPower; + f[8] = fluid.density; f[9] = fluid.refractionStrength; f[10] = fluid.fresnelClamp; f[11] = fluid.minimumThickness; + f[12] = fluid.useFixedThickness ? 1 : 0; + f[13] = envView ? 1 : 0; + f[14] = view.engine3D.setting.sky?.skyExposure ?? 1; + // One particle's worth of thickness: its center contribution, or its diameter when geometric. + const perParticle = fluid.thicknessMode === FluidThicknessMode.Geometric ? fluid.particleSize : fluid.particleThicknessAlpha; + f[15] = fluid.useFixedThickness ? 0 : Math.max(0, fluid.edgeSoftness) * perParticle; + f.set(camera.transform.worldMatrix.rawData, 16); + this._device.queue.writeBuffer(res.shade, 0, f.buffer, f.byteOffset, SHADE_UNIFORM_BYTES); + return envView ?? this._emptyCubeView; + } + + private _sceneLightDirection(view: View3D): Vector3 | null { + ComponentCollect.collectByTypeLayered(view, DirectLight, VisibleLayer.All, this._lights); + return this._lights.length > 0 ? this._lights[0].direction : null; + } + + private _getDepthWritePipeline(depthFormat: GPUTextureFormat): GPURenderPipeline { + let pipeline = this._depthWritePipelines.get(depthFormat); + if (!pipeline) { + pipeline = this._device.createRenderPipeline({ + label: 'FluidPass:DepthWritePipeline', + layout: this._device.createPipelineLayout({ bindGroupLayouts: [this._surfaceBGLayout] }), + vertex: { module: this._compositeModule, entryPoint: 'vs' }, + fragment: { module: this._compositeModule, entryPoint: 'fsDepth', targets: [] }, + primitive: { topology: 'triangle-list', cullMode: 'none' }, + depthStencil: { format: depthFormat, depthCompare: 'less', depthWriteEnabled: true }, + }); + this._depthWritePipelines.set(depthFormat, pipeline); + } + return pipeline; + } + + /** + * Separable blur: `iterations` × (horizontal into A, vertical into B), + * starting from `src`, then `finalPipeline` (if any) from B into A. + * Returns the last target written. + */ + private _blur( + command: GPUCommandEncoder, res: FluidGpu, key: string, pipeline: GPURenderPipeline, src: Target, + width: number, height: number, format: GPUTextureFormat, iterations: number, + p0: number, p1: number, p2: number, p3: number = 0, finalPipeline: GPURenderPipeline | null = null, + extra: Target | null = null, + ): Target { + iterations = Math.max(0, Math.floor(iterations)); + if (iterations === 0) return src; + const a = this._target(res, `${key}A`, width, height, format); + const b = this._target(res, `${key}B`, width, height, format); + const ux = this._blurUniform(res, `${key}X`, 1, 0, width, height, p0, p1, p2, p3); + const uy = this._blurUniform(res, `${key}Y`, 0, 1, width, height, p0, p1, p2, p3); + + let input = src; + for (let i = 0; i < iterations; i++) { + this._blurPass(command, pipeline, ux, input, a, extra); + this._blurPass(command, pipeline, uy, a, b, extra); + input = b; + } + if (!finalPipeline) return b; + this._blurPass(command, finalPipeline, ux, b, a, extra); + return a; + } + + /** Linear view depth of the opaque scene at the depth-map size. */ + private _renderSceneLinear(command: GPUCommandEncoder, res: FluidGpu, sceneDepth: SceneDepth, width: number, height: number): Target { + const target = this._target(res, 'sceneLinear', width, height, DEPTH_FORMAT); + const bg = this._device.createBindGroup({ + layout: this._sceneLinearBGLayout, + entries: [ + { binding: 0, resource: { buffer: res.uniform } }, + { binding: 1, resource: sceneDepth.sampleView }, + ], + }); + const enc = command.beginRenderPass({ + label: 'FluidPass:SceneLinearDepth', + colorAttachments: [{ view: target.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + }); + enc.setPipeline(this._sceneLinearPipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + return target; + } + + /** + * Neighbor search on a hashed grid and per-particle ellipsoids; returns the + * ellipsoid buffer (4 × vec4f per particle, see FluidAnisotropy_wgsl). + */ + private _computeEllipsoids(command: GPUCommandEncoder, res: FluidGpu, fluid: FluidRenderer, particles: GPUBuffer): GPUBuffer { + const count = fluid.particleCount; + const aniso = this._ensureAniso(res, count); + const radius = Math.max(1e-6, fluid.anisotropyRadius ?? fluid.particleSize * 1.5); + + TMP_ANISO_U32[0] = count; + TMP_ANISO_U32[1] = fluid.stride / 4; + TMP_ANISO_U32[2] = fluid.positionOffset / 4; + TMP_ANISO_U32[3] = aniso.tableSize; + TMP_ANISO_F32[4] = radius; + TMP_ANISO_F32[5] = radius; + TMP_ANISO_F32[6] = fluid.particleSize * 0.5; + TMP_ANISO_F32[7] = Math.max(1, fluid.anisotropyMaxRatio); + TMP_ANISO_F32[8] = fluid.anisotropyMinNeighbors; + TMP_ANISO_F32[9] = Math.min(1, Math.max(0, fluid.anisotropySmoothing)); + TMP_ANISO_F32[10] = 0; + TMP_ANISO_F32[11] = 0; + this._device.queue.writeBuffer(aniso.params, 0, TMP_ANISO, 0, ANISO_UNIFORM_BYTES); + + const bg = this._device.createBindGroup({ + layout: this._anisoBGLayout, + entries: [ + { binding: 0, resource: { buffer: aniso.params } }, + { binding: 1, resource: { buffer: particles } }, + { binding: 2, resource: { buffer: aniso.cellCount } }, + { binding: 3, resource: { buffer: aniso.cellStart } }, + { binding: 4, resource: { buffer: aniso.blockSums } }, + { binding: 5, resource: { buffer: aniso.particleCell } }, + { binding: 6, resource: { buffer: aniso.sortedPos } }, + { binding: 7, resource: { buffer: aniso.ellipsoids } }, + ], + }); + const p = this._anisoPipelines; + const groups = (n: number, size: number) => Math.max(1, Math.ceil(n / size)); + const enc = command.beginComputePass({ label: 'FluidPass:Anisotropy' }); + enc.setBindGroup(0, bg); + enc.setPipeline(p.clearCells); + enc.dispatchWorkgroups(groups(aniso.tableSize, 256)); + enc.setPipeline(p.countCells); + enc.dispatchWorkgroups(groups(count, 256)); + enc.setPipeline(p.scanBlocks); + enc.dispatchWorkgroups(groups(aniso.tableSize, SCAN_BLOCK)); + enc.setPipeline(p.scanBlockSums); + enc.dispatchWorkgroups(1); + enc.setPipeline(p.addBlockOffsets); + enc.dispatchWorkgroups(groups(aniso.tableSize, 256)); + enc.setPipeline(p.scatter); + enc.dispatchWorkgroups(groups(count, 256)); + enc.setPipeline(p.computeEllipsoids); + enc.dispatchWorkgroups(groups(count, 128)); + enc.end(); + return aniso.ellipsoids; + } + + /** Neighbor-search buffers sized for `count` particles; regrown when the count exceeds them. */ + private _ensureAniso(res: FluidGpu, count: number): AnisoGpu { + const capacity = Math.max(1, count); + if (res.aniso && res.aniso.capacity >= capacity) return res.aniso; + if (res.aniso) { + const a = res.aniso; + for (const b of [a.params, a.cellCount, a.cellStart, a.blockSums, a.particleCell, a.sortedPos, a.ellipsoids]) b.destroy(); + } + // About two buckets per particle keeps collisions rare; power of two for the hash mask. + const tableSize = Math.min(MAX_HASH_TABLE, Math.max(SCAN_BLOCK, 2 ** Math.ceil(Math.log2(capacity * 2)))); + const storage = GPUBufferUsage.STORAGE; + const buffer = (label: string, size: number, usage: number = storage) => + this._device.createBuffer({ label: `FluidPass:${label}`, size, usage }); + res.aniso = { + params: buffer('AnisoParams', ANISO_UNIFORM_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST), + capacity, + tableSize, + cellCount: buffer('CellCount', tableSize * 4), + cellStart: buffer('CellStart', tableSize * 4), + blockSums: buffer('BlockSums', SCAN_BLOCK * 4), + particleCell: buffer('ParticleCell', capacity * 8), + sortedPos: buffer('SortedPositions', capacity * 16), + ellipsoids: buffer('Ellipsoids', capacity * 64), + }; + return res.aniso; + } + + private _blurPass(command: GPUCommandEncoder, pipeline: GPURenderPipeline, uniform: GPUBuffer, src: Target, dst: Target, extra: Target | null = null): void { + const entries: GPUBindGroupEntry[] = [ + { binding: 0, resource: { buffer: uniform } }, + { binding: 1, resource: src.view }, + ]; + if (extra) entries.push({ binding: 2, resource: extra.view }); + const bg = this._device.createBindGroup({ layout: extra ? this._narrowRangeBGLayout : this._blurBGLayout, entries }); + const enc = command.beginRenderPass({ + label: 'FluidPass:Blur', + colorAttachments: [{ view: dst.view, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + }); + enc.setPipeline(pipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + } + + private _renderDebug(command: GPUCommandEncoder, res: FluidGpu, depth: Target, thickness: Target, colorView: GPUTextureView): void { + const bg = this._device.createBindGroup({ + layout: this._debugBGLayout, + entries: [ + { binding: 0, resource: { buffer: res.uniform } }, + { binding: 1, resource: depth.view }, + { binding: 2, resource: thickness.view }, + ], + }); + const enc = command.beginRenderPass({ + label: 'FluidPass:Debug', + colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }], + }); + enc.setPipeline(this._debugPipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + } + + /** Scene depth the opaque passes wrote: the z-prepass texture when enabled, else the G-buffer depth. */ + private _getSceneDepth(context3D: Context3D): SceneDepth | null { + const frame = GBufferFrame.getGBufferFrame(GBufferFrame.colorPass_GBuffer, context3D); + const tex = (frame.zPreTexture ?? frame.depthTexture) as RenderTexture; + const gpuTex = tex?.getGPUTexture() as GPUTexture; + if (!gpuTex) return null; + if (this._sceneDepth?.texture !== gpuTex) { + this._sceneDepth = { + texture: gpuTex, + sampleView: gpuTex.createView({ aspect: 'depth-only' }), + attachView: gpuTex.createView(), + }; + } + return this._sceneDepth; + } + + private _getParticleBuffer(fluid: FluidRenderer): GPUBuffer | null { + const external = fluid.gpuBuffer; + if (external) { + const buffer = external.buffer; + if (!(buffer.usage & GPUBufferUsage.STORAGE)) { + this._warnOnce(external, 'FluidRenderer: the buffer passed to setDataBufferGPU needs GPUBufferUsage.STORAGE.'); + return null; + } + return buffer; + } + + const data = fluid.cpuData; + if (!data) return null; + const res = this._ensureGpu(fluid); + if (!res.particleBuffer || res.particleBuffer.size < data.byteLength) { + res.particleBuffer?.destroy(); + res.particleBuffer = this._device.createBuffer({ + label: 'FluidPass:Particles', + size: Math.max(16, Math.ceil(data.byteLength / 4) * 4), + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, + }); + res.particleVersion = -1; + } + if (res.particleVersion !== fluid.cpuVersion) { + this._device.queue.writeBuffer(res.particleBuffer, 0, data.buffer, data.byteOffset, data.byteLength); + res.particleVersion = fluid.cpuVersion; + } + return res.particleBuffer; + } + + private _ensureGpu(fluid: FluidRenderer): FluidGpu { + let res = this._gpu.get(fluid); + if (!res) { + res = { + uniform: this._device.createBuffer({ + label: 'FluidPass:Uniforms', + size: UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }), + shade: this._device.createBuffer({ + label: 'FluidPass:Shade', + size: SHADE_UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }), + particleBuffer: null, + particleVersion: -1, + targets: new Map(), + blurUniforms: new Map(), + aniso: null, + }; + this._gpu.set(fluid, res); + } + return res; + } + + /** Named per-fluid render target, recreated when its size changes. */ + private _target(res: FluidGpu, key: string, width: number, height: number, format: GPUTextureFormat, usage: number = RT_USAGE): Target { + let t = res.targets.get(key); + if (t && t.width === width && t.height === height) return t; + t?.texture.destroy(); + const texture = this._device.createTexture({ label: `FluidPass:${key}`, size: [width, height, 1], format, usage }); + t = { texture, view: texture.createView(), width, height }; + res.targets.set(key, t); + return t; + } + + private _blurUniform(res: FluidGpu, key: string, dirX: number, dirY: number, width: number, height: number, p0: number, p1: number, p2: number, p3: number): GPUBuffer { + let buffer = res.blurUniforms.get(key); + if (!buffer) { + buffer = this._device.createBuffer({ + label: `FluidPass:${key}`, + size: BLUR_UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + res.blurUniforms.set(key, buffer); + } + const f = TMP_BLUR_F32; + f[0] = dirX; f[1] = dirY; + f[2] = width; f[3] = height; + f[4] = p0; f[5] = p1; f[6] = p2; f[7] = p3; + f[8] = this._pixelWorldPerDepth / height; f[9] = MAX_GRAZING_SCALE; f[10] = 0; f[11] = 0; + this._device.queue.writeBuffer(buffer, 0, f.buffer, f.byteOffset, BLUR_UNIFORM_BYTES); + return buffer; + } + + private _writeUniforms(res: FluidGpu, fluid: FluidRenderer, camera: Camera3D, depth: Target, thickness: Target, screenW: number, screenH: number): void { + const f = TMP_UNIFORM_F32; + f.set(this._modelView.multiplyMatrices(camera.viewMatrix, fluid.transform.worldMatrix).rawData, 0); + f.set(camera.projectionMatrix.rawData, 16); + f.set(camera.projectionMatrixInv.rawData, 32); + f[48] = fluid.particleSize * 0.5; + f[49] = fluid.stride / 4; + f[50] = fluid.positionOffset / 4; + f[51] = fluid.particleThicknessAlpha; + f[52] = camera.near; + f[53] = camera.far; + f[54] = fluid.debugFeature; + f[55] = 0; + f[56] = depth.width; + f[57] = depth.height; + f[58] = screenW; + f[59] = screenH; + f[60] = thickness.width; + f[61] = thickness.height; + f[62] = 0; + f[63] = 0; + this._device.queue.writeBuffer(res.uniform, 0, f.buffer, f.byteOffset, UNIFORM_BYTES); + } + + private _warnOnce(key: object, message: string): void { + if (this._warned.has(key)) return; + this._warned.add(key); + console.warn(message); + } + + private _createPipelines(): void { + const device = this._device; + const defines = { USE_LOGDEPTH: this._useLogDepth }; + const fullscreen: GPUPrimitiveState = { topology: 'triangle-list', cullMode: 'none' }; + + this._particleBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:ParticleBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ], + }); + const particleLayout = device.createPipelineLayout({ bindGroupLayouts: [this._particleBGLayout] }); + const particleModule = device.createShaderModule({ + label: 'FluidPass:ParticleShader', + code: Preprocessor.parse(FluidParticle_wgsl, defines), + }); + // The projection mirrors x, so quad winding is not stable; draw both faces. + const particlePrimitive: GPUPrimitiveState = { topology: 'triangle-list', cullMode: 'none' }; + this._depthPipeline = device.createRenderPipeline({ + label: 'FluidPass:DepthPipeline', + layout: particleLayout, + vertex: { module: particleModule, entryPoint: 'vs' }, + fragment: { module: particleModule, entryPoint: 'fsDepth', targets: [{ format: DEPTH_FORMAT }] }, + primitive: particlePrimitive, + depthStencil: { format: 'depth32float', depthCompare: 'less', depthWriteEnabled: true }, + }); + this._thicknessPipeline = device.createRenderPipeline({ + label: 'FluidPass:ThicknessPipeline', + layout: particleLayout, + vertex: { module: particleModule, entryPoint: 'vs' }, + fragment: { + module: particleModule, entryPoint: 'fsThickness', + targets: [{ + format: THICKNESS_FORMAT, + blend: { + color: { srcFactor: 'one', dstFactor: 'one', operation: 'add' }, + alpha: { srcFactor: 'one', dstFactor: 'one', operation: 'add' }, + }, + }], + }, + primitive: particlePrimitive, + }); + + const ellipsoidModule = device.createShaderModule({ + label: 'FluidPass:EllipsoidShader', + code: Preprocessor.parse(FluidEllipsoid_wgsl, defines), + }); + this._ellipsoidDepthPipeline = device.createRenderPipeline({ + label: 'FluidPass:EllipsoidDepthPipeline', + layout: particleLayout, + vertex: { module: ellipsoidModule, entryPoint: 'vs' }, + fragment: { module: ellipsoidModule, entryPoint: 'fsDepth', targets: [{ format: DEPTH_FORMAT }] }, + primitive: particlePrimitive, + depthStencil: { format: 'depth32float', depthCompare: 'less', depthWriteEnabled: true }, + }); + this._ellipsoidThicknessPipeline = device.createRenderPipeline({ + label: 'FluidPass:EllipsoidThicknessPipeline', + layout: particleLayout, + vertex: { module: ellipsoidModule, entryPoint: 'vs' }, + fragment: { + module: ellipsoidModule, entryPoint: 'fsThickness', + targets: [{ + format: THICKNESS_FORMAT, + blend: { + color: { srcFactor: 'one', dstFactor: 'one', operation: 'add' }, + alpha: { srcFactor: 'one', dstFactor: 'one', operation: 'add' }, + }, + }], + }, + primitive: particlePrimitive, + }); + + // Far side of the fluid: keep the farthest fragment. + const backDepthState: GPUDepthStencilState = { format: 'depth32float', depthCompare: 'greater', depthWriteEnabled: true }; + this._backDepthPipeline = device.createRenderPipeline({ + label: 'FluidPass:BackDepthPipeline', + layout: particleLayout, + vertex: { module: particleModule, entryPoint: 'vs' }, + fragment: { module: particleModule, entryPoint: 'fsBackDepth', targets: [{ format: DEPTH_FORMAT }] }, + primitive: particlePrimitive, + depthStencil: backDepthState, + }); + this._ellipsoidBackDepthPipeline = device.createRenderPipeline({ + label: 'FluidPass:EllipsoidBackDepthPipeline', + layout: particleLayout, + vertex: { module: ellipsoidModule, entryPoint: 'vs' }, + fragment: { module: ellipsoidModule, entryPoint: 'fsBackDepth', targets: [{ format: DEPTH_FORMAT }] }, + primitive: particlePrimitive, + depthStencil: backDepthState, + }); + this._geometricBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:GeometricBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + ], + }); + const geometricModule = device.createShaderModule({ label: 'FluidPass:GeometricThickness', code: FluidGeometricThickness_wgsl }); + this._geometricPipeline = device.createRenderPipeline({ + label: 'FluidPass:GeometricThicknessPipeline', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._geometricBGLayout] }), + vertex: { module: geometricModule, entryPoint: 'vs' }, + fragment: { module: geometricModule, entryPoint: 'fs', targets: [{ format: THICKNESS_FORMAT }] }, + primitive: { topology: 'triangle-list', cullMode: 'none' }, + }); + + this._anisoBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:AnisoBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } }, + ...[1, 2, 3, 4, 5, 6, 7].map((binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' as GPUBufferBindingType } })), + ], + }); + const anisoModule = device.createShaderModule({ label: 'FluidPass:Anisotropy', code: FluidAnisotropy_wgsl }); + const anisoLayout = device.createPipelineLayout({ bindGroupLayouts: [this._anisoBGLayout] }); + const compute = (entryPoint: string) => device.createComputePipeline({ + label: `FluidPass:${entryPoint}`, + layout: anisoLayout, + compute: { module: anisoModule, entryPoint }, + }); + this._anisoPipelines = { + clearCells: compute('clearCells'), + countCells: compute('countCells'), + scanBlocks: compute('scanBlocks'), + scanBlockSums: compute('scanBlockSums'), + addBlockOffsets: compute('addBlockOffsets'), + scatter: compute('scatter'), + computeEllipsoids: compute('computeEllipsoids'), + }; + + this._blurBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:BlurBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + ], + }); + const blurLayout = device.createPipelineLayout({ bindGroupLayouts: [this._blurBGLayout] }); + const bilateralModule = device.createShaderModule({ label: 'FluidPass:BilateralBlur', code: FluidBilateralBlur_wgsl }); + this._bilateralPipeline = device.createRenderPipeline({ + label: 'FluidPass:BilateralBlurPipeline', + layout: blurLayout, + vertex: { module: bilateralModule, entryPoint: 'vs' }, + fragment: { module: bilateralModule, entryPoint: 'fs', targets: [{ format: DEPTH_FORMAT }] }, + primitive: fullscreen, + }); + this._narrowRangeBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:NarrowRangeBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + ], + }); + const narrowRangeLayout = device.createPipelineLayout({ bindGroupLayouts: [this._narrowRangeBGLayout] }); + this._sceneLinearBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:SceneLinearBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ], + }); + const sceneLinearModule = device.createShaderModule({ + label: 'FluidPass:SceneLinearDepth', + code: Preprocessor.parse(FluidSceneLinearDepth_wgsl, defines), + }); + this._sceneLinearPipeline = device.createRenderPipeline({ + label: 'FluidPass:SceneLinearDepthPipeline', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._sceneLinearBGLayout] }), + vertex: { module: sceneLinearModule, entryPoint: 'vs' }, + fragment: { module: sceneLinearModule, entryPoint: 'fs', targets: [{ format: DEPTH_FORMAT }] }, + primitive: fullscreen, + }); + const narrowRangeModule = device.createShaderModule({ label: 'FluidPass:NarrowRangeFilter', code: FluidNarrowRangeFilter_wgsl }); + this._narrowRangePipeline = device.createRenderPipeline({ + label: 'FluidPass:NarrowRangePipeline', + layout: narrowRangeLayout, + vertex: { module: narrowRangeModule, entryPoint: 'vs' }, + fragment: { module: narrowRangeModule, entryPoint: 'fs', targets: [{ format: DEPTH_FORMAT }] }, + primitive: fullscreen, + }); + this._narrowRange2DPipeline = device.createRenderPipeline({ + label: 'FluidPass:NarrowRange2DPipeline', + layout: narrowRangeLayout, + vertex: { module: narrowRangeModule, entryPoint: 'vs' }, + fragment: { module: narrowRangeModule, entryPoint: 'fs2D', targets: [{ format: DEPTH_FORMAT }] }, + primitive: fullscreen, + }); + const gaussianModule = device.createShaderModule({ label: 'FluidPass:GaussianBlur', code: FluidGaussianBlur_wgsl }); + this._gaussianPipeline = device.createRenderPipeline({ + label: 'FluidPass:GaussianBlurPipeline', + layout: blurLayout, + vertex: { module: gaussianModule, entryPoint: 'vs' }, + fragment: { module: gaussianModule, entryPoint: 'fs', targets: [{ format: THICKNESS_FORMAT }] }, + primitive: fullscreen, + }); + + this._debugBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:DebugBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + ], + }); + const debugModule = device.createShaderModule({ + label: 'FluidPass:DebugShader', + code: Preprocessor.parse(FluidDebugView_wgsl, defines), + }); + this._debugPipeline = device.createRenderPipeline({ + label: 'FluidPass:DebugPipeline', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._debugBGLayout] }), + vertex: { module: debugModule, entryPoint: 'vs' }, + fragment: { module: debugModule, entryPoint: 'fs', targets: [{ format: COLOR_FORMAT }] }, + primitive: fullscreen, + }); + + this._surfaceBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:SurfaceBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, + { binding: 3, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + ], + }); + this._sceneBGLayout = device.createBindGroupLayout({ + label: 'FluidPass:SceneBGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float', viewDimension: 'cube' } }, + { binding: 3, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ], + }); + this._compositeModule = device.createShaderModule({ + label: 'FluidPass:CompositeShader', + code: Preprocessor.parse(FluidComposite_wgsl, defines), + }); + this._colorPipeline = device.createRenderPipeline({ + label: 'FluidPass:ColorPipeline', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._surfaceBGLayout, this._sceneBGLayout] }), + vertex: { module: this._compositeModule, entryPoint: 'vs' }, + fragment: { module: this._compositeModule, entryPoint: 'fsColor', targets: [{ format: COLOR_FORMAT }] }, + primitive: fullscreen, + }); + this._linearSampler = device.createSampler({ + label: 'FluidPass:LinearSampler', + magFilter: 'linear', minFilter: 'linear', + addressModeU: 'clamp-to-edge', addressModeV: 'clamp-to-edge', addressModeW: 'clamp-to-edge', + }); + // Bound when the fluid has no environment map; the shader skips reflection then. + this._emptyCubeView = device.createTexture({ + label: 'FluidPass:EmptyCube', + size: [1, 1, 6], + format: 'rgba8unorm', + usage: GPUTextureUsage.TEXTURE_BINDING, + }).createView({ dimension: 'cube' }); + } +} + +/** Map size for an optional fixed width; height keeps the screen aspect. */ +function mapSize(width: number | null, screenW: number, screenH: number): [number, number] { + if (!width || width <= 0) return [Math.max(1, Math.floor(screenW)), Math.max(1, Math.floor(screenH))]; + const w = Math.max(1, Math.floor(width)); + return [w, Math.max(1, Math.floor(w * screenH / screenW))]; +} diff --git a/src/gfx/renderJob/graph/passes/SceneLinearDepthPass.ts b/src/gfx/renderJob/graph/passes/SceneLinearDepthPass.ts new file mode 100644 index 000000000..9e36e6e9b --- /dev/null +++ b/src/gfx/renderJob/graph/passes/SceneLinearDepthPass.ts @@ -0,0 +1,177 @@ +import { Camera3D } from '../../../../core/Camera3D'; +import { RenderTexture } from '../../../../textures/RenderTexture'; +import { Context3D } from '../../../graphics/webGpu/Context3D'; +import { Preprocessor } from '../../../graphics/webGpu/shader/util/Preprocessor'; +import { GPUTextureFormat } from '../../../graphics/webGpu/WebGPUConst'; +import { GBufferFrame } from '../../frame/GBufferFrame'; +import { RenderGraphBuilder, RenderGraphPass, RenderGraphPassContext } from '../RenderGraphPass'; +import { TextureHandle } from '../transient/ResourceHandle'; +import { MAIN_DEPTH_TEXTURE } from './PreDepthPass'; + +/** + * Handle of the opaque scene's linear view depth (r32float, view-space z; + * the far plane where nothing was drawn). Also published by name for + * materials, like the scene color pyramid. + * @group Graph + */ +export const SCENE_LINEAR_DEPTH = '_SceneLinearDepth'; + +const UNIFORM_BYTES = 80; + +/** + * Converts the opaque scene depth into linear view depth that materials + * drawn afterwards (water, by the transmission pass) can sample: the depth + * texture itself is still the depth attachment while they draw. + * + * {@link ForwardRendererJob} adds it right after the scene color pyramid + * when `setting.render.water` is true. + * + * @group Graph + */ +export class SceneLinearDepthPass extends RenderGraphPass { + public readonly name: string = 'SceneLinearDepthPass'; + + private _device!: GPUDevice; + private _handle!: TextureHandle; + private _pipeline!: GPURenderPipeline; + private _layout!: GPUBindGroupLayout; + private _uniform!: GPUBuffer; + private _uniformData = new Float32Array(UNIFORM_BYTES / 4); + private _depthSrc: GPUTexture | null = null; + private _depthView: GPUTextureView | null = null; + + public setup(b: RenderGraphBuilder): void { + this._device = b.context3D.device as GPUDevice; + const setting = b.context3D.engine?.setting?.render; + if (setting?.zPrePass) b.read(MAIN_DEPTH_TEXTURE); + // Opaque depth is final once the pyramid has captured the opaque scene. + b.dependsOn('SceneColorPyramidPass'); + this._handle = b.declareTexture(SCENE_LINEAR_DEPTH, { + format: GPUTextureFormat.r32float, + width: 'screen', height: 'screen', + aliasable: false, + publishToLegacyMap: true, + // COPY bits: the graph's 'attachment' access hint requires them. + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING + | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, + label: SCENE_LINEAR_DEPTH, + }); + b.write(this._handle, 'attachment'); + this._createPipeline(!!setting?.useLogDepth); + } + + public destroy(): void { + this._uniform?.destroy(); + this._depthSrc = null; + this._depthView = null; + } + + public execute(ctx: RenderGraphPassContext): void { + const view = ctx.view; + const engine = view.engine3D; + const target = ctx.getTexture(this._handle) as RenderTexture; + const depthView = this._getSceneDepthView(engine.context3D); + if (!target || !depthView) return; + // r32float is not filterable; materials read it with textureLoad. + target.textureBindingLayout.sampleType = 'unfilterable-float'; + this._writeUniforms(view.camera); + + const bg = this._device.createBindGroup({ + layout: this._layout, + entries: [ + { binding: 0, resource: { buffer: this._uniform } }, + { binding: 1, resource: depthView }, + ], + }); + const gpu = engine.context3D.gpuContext; + const command = gpu.beginCommandEncoder(); + const enc = command.beginRenderPass({ + label: 'SceneLinearDepth', + colorAttachments: [{ view: target.getGPUView() as GPUTextureView, loadOp: 'clear', clearValue: [0, 0, 0, 0], storeOp: 'store' }], + }); + enc.setPipeline(this._pipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + gpu.endCommandEncoder(command); + } + + /** Depth the opaque passes wrote: the z-prepass texture when enabled, else the G-buffer depth. */ + private _getSceneDepthView(context3D: Context3D): GPUTextureView | null { + const frame = GBufferFrame.getGBufferFrame(GBufferFrame.colorPass_GBuffer, context3D); + const tex = (frame.zPreTexture ?? frame.depthTexture) as RenderTexture; + const gpuTex = tex?.getGPUTexture() as GPUTexture; + if (!gpuTex) return null; + if (gpuTex !== this._depthSrc) { + this._depthSrc = gpuTex; + // depth-only aspect so depth24plus-stencil8 (useStencil) also binds as texture_depth_2d. + this._depthView = gpuTex.createView({ aspect: 'depth-only' }); + } + return this._depthView; + } + + private _writeUniforms(camera: Camera3D): void { + const f = this._uniformData; + f.set(camera.projectionMatrixInv.rawData, 0); + f[16] = camera.near; + f[17] = camera.far; + f[18] = 0; + f[19] = 0; + this._device.queue.writeBuffer(this._uniform, 0, f.buffer, f.byteOffset, UNIFORM_BYTES); + } + + private _createPipeline(useLogDepth: boolean): void { + const device = this._device; + this._uniform = device.createBuffer({ + label: 'SceneLinearDepth:Uniforms', + size: UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + this._layout = device.createBindGroupLayout({ + label: 'SceneLinearDepth:BGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ], + }); + const module = device.createShaderModule({ + label: 'SceneLinearDepth', + code: Preprocessor.parse(SCENE_LINEAR_DEPTH_WGSL, { USE_LOGDEPTH: useLogDepth }), + }); + this._pipeline = device.createRenderPipeline({ + label: 'SceneLinearDepth', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._layout] }), + vertex: { module, entryPoint: 'vs' }, + fragment: { module, entryPoint: 'fs', targets: [{ format: 'r32float' }] }, + primitive: { topology: 'triangle-list', cullMode: 'none' }, + }); + } +} + +const SCENE_LINEAR_DEPTH_WGSL = /* wgsl */` +struct Params { + projInv: mat4x4f, + // x = near, y = far + camera: vec4f, +}; + +@group(0) @binding(0) var p: Params; +@group(0) @binding(1) var sceneDepth: texture_depth_2d; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var v = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(v[vi], 0.0, 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) f32 { + let d = textureLoad(sceneDepth, vec2i(pos.xy), 0); + #if USE_LOGDEPTH + return pow(p.camera.y + 1.0, d) - 1.0; + #else + let v = p.projInv * vec4f(0.0, 0.0, d, 1.0); + return v.z / v.w; + #endif +} +`; diff --git a/src/gfx/renderJob/graph/passes/UnderwaterPass.ts b/src/gfx/renderJob/graph/passes/UnderwaterPass.ts new file mode 100644 index 000000000..58995bb10 --- /dev/null +++ b/src/gfx/renderJob/graph/passes/UnderwaterPass.ts @@ -0,0 +1,383 @@ +import { WaterWaves_wgsl } from '../../../../assets/shader/materials/WaterShader'; +import { WaterFootprintBindings, waterFootprintWGSL } from '../../../../components/renderer/WaterFootprint'; +import { WaterRenderer } from '../../../../components/renderer/WaterRenderer'; +import { WATER_MAX_WAVES } from '../../../../materials/WaterMaterial'; +import { WATER_FFT_PATCHES } from '../../../../components/renderer/WaterFFT'; +import { Camera3D } from '../../../../core/Camera3D'; +import { Matrix4 } from '../../../../math/Matrix4'; +import { RenderTexture } from '../../../../textures/RenderTexture'; +import { Context3D } from '../../../graphics/webGpu/Context3D'; +import { Preprocessor } from '../../../graphics/webGpu/shader/util/Preprocessor'; +import { ComponentCollect } from '../../collect/ComponentCollect'; +import { GBufferFrame } from '../../frame/GBufferFrame'; +import { RenderGraphBuilder, RenderGraphPass, RenderGraphPassContext } from '../RenderGraphPass'; +import { COLOR_BUFFER } from './ColorPass'; +import { MAIN_COLOR_RT } from './GBufferResourcePass'; +import { MAIN_DEPTH_TEXTURE } from './PreDepthPass'; + +/** Must match COLOR_BUFFER's format. */ +const COLOR_FORMAT: GPUTextureFormat = 'rgba16float'; +/** Water surfaces handled per frame. */ +const MAX_WATERS = 4; +/** See UNDERWATER_WGSL for the layout. */ +const HEADER_FLOATS = 40; +const WAVE_FLOATS = WATER_MAX_WAVES * 4; +const WATER_FLOATS = 16 + WAVE_FLOATS + 20; +/** First binding of the footprint masks. */ +const FOOTPRINT_BINDING = 3; +/** Sampler and displacement cascades of the water with FFT waves, after the masks. */ +const FFT_BINDING = FOOTPRINT_BINDING + 5; +const UNIFORM_BYTES = (HEADER_FLOATS + MAX_WATERS * WATER_FLOATS) * 4; + +/** + * Underwater view of {@link WaterRenderer}s: every pixel whose near-plane + * point lies below a wave surface is attenuated along the view ray + * (Beer-Lambert absorption, plus the water's own color scattered in). The + * test is per pixel, so a camera half in the water gets a waterline across + * the screen, drawn as a thin dark band. The water surface writes depth, + * so looking up the attenuated distance ends at the surface. + * + * Up to four surfaces near the camera are handled; where their footprints + * overlap, the one the point is deepest under wins. + * + * {@link ForwardRendererJob} adds it after the transparent passes and + * before post-processing when `setting.render.water` is true. It does + * nothing while the camera is clear of every water surface. + * + * @group Graph + */ +export class UnderwaterPass extends RenderGraphPass { + public readonly name: string = 'UnderwaterPass'; + + private _device!: GPUDevice; + private _pipeline!: GPURenderPipeline; + private _layout!: GPUBindGroupLayout; + private _uniform!: GPUBuffer; + private _uniformData = new Float32Array(UNIFORM_BYTES / 4); + private _waters: WaterRenderer[] = []; + private _near: WaterRenderer[] = []; + private _footprints = new WaterFootprintBindings(); + private _noFFT: GPUTexture | null = null; + private _fftSampler: GPUSampler | null = null; + private _copy: GPUTexture | null = null; + private _depthSrc: GPUTexture | null = null; + private _depthView: GPUTextureView | null = null; + /** Allocated in setup: matrices come from a pool created at engine init. */ + private _invViewProj!: Matrix4; + + public setup(b: RenderGraphBuilder): void { + this._device = b.context3D.device as GPUDevice; + const setting = b.context3D.engine?.setting?.render; + if (setting?.zPrePass) b.read(MAIN_DEPTH_TEXTURE); + b.write(COLOR_BUFFER); + b.useRenderTarget(MAIN_COLOR_RT); + this._invViewProj = new Matrix4(); + this._createPipeline(!!setting?.useLogDepth); + } + + public destroy(): void { + this._uniform?.destroy(); + this._copy?.destroy(); + this._copy = null; + this._footprints.destroy(); + this._noFFT?.destroy(); + this._noFFT = null; + this._waters.length = 0; + this._near.length = 0; + } + + public execute(ctx: RenderGraphPassContext): void { + const view = ctx.view; + const camera = view.camera; + const mask = (this.layerMask & (camera?.cullingMask ?? 0xFFFFFFFF)) >>> 0; + ComponentCollect.collectByTypeLayered(view, WaterRenderer, mask, this._waters); + const near = this._near; + near.length = 0; + for (const w of this._waters) { + if (near.length < MAX_WATERS && w.transform?.enable && this._cameraNear(w, camera)) near.push(w); + } + if (near.length === 0) return; + + const engine = view.engine3D; + const colorTex = ctx.get(COLOR_BUFFER); + const depthView = this._getSceneDepthView(engine.context3D); + if (!colorTex || !depthView) return; + const color = colorTex.getGPUTexture() as GPUTexture; + const copy = this._ensureCopy(color.width, color.height); + this._writeUniforms(near, camera); + + const bg = this._device.createBindGroup({ + layout: this._layout, + entries: [ + { binding: 0, resource: { buffer: this._uniform } }, + { binding: 1, resource: copy.createView() }, + { binding: 2, resource: depthView }, + ...this._footprints.entries(this._device, near.map((w) => w.footprint), FOOTPRINT_BINDING), + ...this._fftEntries(near), + ], + }); + const gpu = engine.context3D.gpuContext; + const command = gpu.beginCommandEncoder(); + command.copyTextureToTexture({ texture: color }, { texture: copy }, [color.width, color.height, 1]); + const enc = command.beginRenderPass({ + label: 'Underwater', + colorAttachments: [{ view: color.createView(), loadOp: 'load', storeOp: 'store' }], + }); + enc.setPipeline(this._pipeline); + enc.setBindGroup(0, bg); + enc.draw(3); + enc.end(); + gpu.endCommandEncoder(command); + } + + /** The cascades of the first water with FFT waves, or placeholders. */ + private _fftEntries(waters: WaterRenderer[]): GPUBindGroupEntry[] { + if (!this._noFFT) { + this._noFFT = this._device.createTexture({ + label: 'Underwater:NoFFT', size: [1, 1, 1], format: 'rgba16float', usage: GPUTextureUsage.TEXTURE_BINDING, + }); + this._fftSampler = this._device.createSampler({ + magFilter: 'linear', minFilter: 'linear', addressModeU: 'repeat', addressModeV: 'repeat', + }); + } + const fft = waters.find((w) => w.fft)?.fft; + const entries: GPUBindGroupEntry[] = [{ binding: FFT_BINDING, resource: this._fftSampler! }]; + for (let c = 0; c < 3; c++) { + const view = fft ? (fft.displacement[c].getGPUTexture() as GPUTexture).createView() : this._noFFT.createView(); + entries.push({ binding: FFT_BINDING + 1 + c, resource: view }); + } + return entries; + } + + /** Whether the near plane can reach below this surface: camera over its footprint and low enough. */ + private _cameraNear(water: WaterRenderer, camera: Camera3D): boolean { + const p = camera.transform.worldPosition; + // The near plane corners reach about near * 2 beyond the camera at common fields of view. + const reach = camera.near * 2; + if (!water.containsXZ(p.x, p.z, reach)) return false; + return p.y - reach < water.baseHeight + water.waveReach; + } + + private _ensureCopy(width: number, height: number): GPUTexture { + if (this._copy && this._copy.width === width && this._copy.height === height) return this._copy; + this._copy?.destroy(); + this._copy = this._device.createTexture({ + label: 'Underwater:SceneColor', + size: [width, height, 1], + format: COLOR_FORMAT, + usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, + }); + return this._copy; + } + + /** Depth after all opaque, water and depth-writing transparent draws. */ + private _getSceneDepthView(context3D: Context3D): GPUTextureView | null { + const frame = GBufferFrame.getGBufferFrame(GBufferFrame.colorPass_GBuffer, context3D); + const tex = (frame.zPreTexture ?? frame.depthTexture) as RenderTexture; + const gpuTex = tex?.getGPUTexture() as GPUTexture; + if (!gpuTex) return null; + if (gpuTex !== this._depthSrc) { + this._depthSrc = gpuTex; + this._depthView = gpuTex.createView({ aspect: 'depth-only' }); + } + return this._depthView; + } + + private _writeUniforms(waters: WaterRenderer[], camera: Camera3D): void { + const f = this._uniformData; + const ivp = this._invViewProj.multiplyMatrices(camera.projectionMatrix, camera.viewMatrix); + ivp.invert(); + f.set(ivp.rawData, 0); + f.set(camera.projectionMatrixInv.rawData, 16); + f[32] = waters.length; + f[33] = camera.far; + const [p0, p1, p2] = WATER_FFT_PATCHES; + f[36] = p0; f[37] = p1; f[38] = p2; f[39] = 0; + const fftWater = waters.find((w) => w.fft); + for (let w = 0; w < waters.length; w++) { + const water = waters[w]; + const o = HEADER_FLOATS + w * WATER_FLOATS; + f.set(water.invWorldMatrix.rawData, o); + for (let i = 0; i < WATER_MAX_WAVES; i++) f.set(water.waveVector(i), o + 16 + i * 4); + // Fields after the waves, in Water struct order. + const q = o + 16 + WAVE_FLOATS; + f[q] = water.baseHeight; + f[q + 1] = water.time; + f[q + 2] = water.waterMaterial.density; + f.set(water.footprintBounds, q + 4); + const a = water.waterMaterial.absorptionColor; + f[q + 8] = a.r; f[q + 9] = a.g; f[q + 10] = a.b; f[q + 11] = 1; + const s = water.waterMaterial.underwaterColor; + f[q + 12] = s.r; f[q + 13] = s.g; f[q + 14] = s.b; f[q + 15] = 1; + f[q + 16] = water.footprint ? 1 : 0; + f[q + 17] = water === fftWater ? 1 : 0; + } + this._device.queue.writeBuffer(this._uniform, 0, f.buffer, f.byteOffset, UNIFORM_BYTES); + } + + private _createPipeline(useLogDepth: boolean): void { + const device = this._device; + this._uniform = device.createBuffer({ + label: 'Underwater:Uniforms', + size: UNIFORM_BYTES, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + this._layout = device.createBindGroupLayout({ + label: 'Underwater:BGL', + entries: [ + { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'depth' } }, + ...WaterFootprintBindings.layoutEntries(FOOTPRINT_BINDING), + { binding: FFT_BINDING, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } }, + ...[1, 2, 3].map((i): GPUBindGroupLayoutEntry => ({ + binding: FFT_BINDING + i, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' }, + })), + ], + }); + const module = device.createShaderModule({ + label: 'Underwater', + code: Preprocessor.parse(UNDERWATER_WGSL, { USE_LOGDEPTH: useLogDepth }), + }); + this._pipeline = device.createRenderPipeline({ + label: 'Underwater', + layout: device.createPipelineLayout({ bindGroupLayouts: [this._layout] }), + vertex: { module, entryPoint: 'vs' }, + fragment: { module, entryPoint: 'fs', targets: [{ format: COLOR_FORMAT }] }, + primitive: { topology: 'triangle-list', cullMode: 'none' }, + }); + } +} + +const UNDERWATER_WGSL = /* wgsl */` +${WaterWaves_wgsl} + +struct Water { + // world to local + invWorld: mat4x4f, + waves: array, + // x = undisplaced surface height, y = wave time, z = absorption density + params: vec4f, + // local xz bounds: min x, min z, max x, max z + bounds: vec4f, + absorption: vec4f, + scatter: vec4f, + // x = 1 when the footprint has a mask (custom surface mesh), y = 1 for the water with FFT waves + mask: vec4f, +}; + +struct Params { + invViewProj: mat4x4f, + projInv: mat4x4f, + // x = water count, y = camera far + info: vec4f, + // FFT cascade patch sizes + fft: vec4f, + waters: array, +}; + +@group(0) @binding(0) var p: Params; +@group(0) @binding(1) var sceneColor: texture_2d; +@group(0) @binding(2) var sceneDepth: texture_depth_2d; +${waterFootprintWGSL(FOOTPRINT_BINDING)} + +// Waterline band: half width in pixels per pixel of screen height, and how dark its center is. +const LINE_WIDTH: f32 = 0.006; +const LINE_SHADE: f32 = 0.25; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + var v = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + return vec4f(v[vi], 0.0, 1.0); +} + +fn nearPoint(ndc: vec2f) -> vec3f { + let h = p.invViewProj * vec4f(ndc, 0.0, 1.0); + return h.xyz / h.w; +} + +@group(0) @binding(${FFT_BINDING}) var fftSampler: sampler; +@group(0) @binding(${FFT_BINDING + 1}) var fftDisplacement0: texture_2d; +@group(0) @binding(${FFT_BINDING + 2}) var fftDisplacement1: texture_2d; +@group(0) @binding(${FFT_BINDING + 3}) var fftDisplacement2: texture_2d; + +fn fftDisplaced(xz: vec2f) -> vec3f { + return textureSampleLevel(fftDisplacement0, fftSampler, xz / p.fft.x, 0.0).xyz + + textureSampleLevel(fftDisplacement1, fftSampler, xz / p.fft.y, 0.0).xyz + + textureSampleLevel(fftDisplacement2, fftSampler, xz / p.fft.z, 0.0).xyz; +} + +// Height of the FFT waves above world xz, through the undisplaced point that lands there. +fn fftHeight(xz: vec2f) -> f32 { + var q = xz; + for (var it = 0; it < 3; it++) { + q = xz - fftDisplaced(q).xz; + } + return fftDisplaced(q).y; +} + +// Height of a world point above water i's displaced surface. +fn heightAbove(i: u32, world: vec3f) -> f32 { + let w = p.waters[i].waves; + let params = p.waters[i].params; + var surface = params.x + waterHeight(w, world.xz, params.y); + if (p.waters[i].mask.y > 0.5) { + surface += fftHeight(world.xz); + } + return world.y - surface; +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let dim = vec2f(textureDimensions(sceneColor)); + let uv = pos.xy / dim; + let ndc = vec2f(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0); + + // Where this pixel's ray starts, and the water it is deepest under (or closest above). + let nearW = nearPoint(ndc); + var h = 1e9; + var idx = 0u; + for (var i = 0u; i < u32(p.info.x); i++) { + if (insideFootprint(i, nearW)) { + let hi = heightAbove(i, nearW); + if (hi < h) { + h = hi; + idx = i; + } + } + } + + // Distance to the waterline in pixels, from the change of h to the neighbouring pixels. + let lineWidth = max(1.5, dim.y * LINE_WIDTH); + let nearX = nearPoint(ndc + vec2f(2.0 / dim.x, 0.0)); + let nearY = nearPoint(ndc - vec2f(0.0, 2.0 / dim.y)); + let pixelSpan = max(length(nearX - nearW), length(nearY - nearW)); + var line = 0.0; + if (abs(h) < 4.0 * lineWidth * pixelSpan) { + let grad = vec2f(heightAbove(idx, nearX) - h, heightAbove(idx, nearY) - h); + line = 1.0 - smoothstep(0.0, lineWidth, abs(h) / max(length(grad), 1e-9)); + } + if (h >= 0.0 && line <= 0.0) { + discard; + } + + var color = textureLoad(sceneColor, vec2i(pos.xy), 0).rgb; + if (h < 0.0) { + // Distance along the ray to whatever was drawn there (the surface itself when looking up). + let d = textureLoad(sceneDepth, vec2i(pos.xy), 0); + let farH = p.projInv * vec4f(ndc, 1.0, 1.0); + let ray = farH.xyz / farH.w; + #if USE_LOGDEPTH + let viewZ = pow(p.info.y + 1.0, d) - 1.0; + #else + let v = p.projInv * vec4f(0.0, 0.0, d, 1.0); + let viewZ = v.z / v.w; + #endif + let dist = viewZ * length(ray) / max(ray.z, 1e-4); + let water = p.waters[idx]; + let transmittance = exp(-water.params.z * dist * (vec3f(1.0) - water.absorption.rgb)); + color = color * transmittance + water.scatter.rgb * (vec3f(1.0) - transmittance); + } + return vec4f(mix(color, color * LINE_SHADE, line), 1.0); +} +`; diff --git a/src/gfx/renderJob/graph/passes/WaterSimulationPass.ts b/src/gfx/renderJob/graph/passes/WaterSimulationPass.ts new file mode 100644 index 000000000..3e51fd4d6 --- /dev/null +++ b/src/gfx/renderJob/graph/passes/WaterSimulationPass.ts @@ -0,0 +1,41 @@ +import { WaterRenderer } from '../../../../components/renderer/WaterRenderer'; +import { Time } from '../../../../util/Time'; +import { ComponentCollect } from '../../collect/ComponentCollect'; +import { RenderGraphBuilder, RenderGraphPass, RenderGraphPassContext } from '../RenderGraphPass'; + +/** + * Advances the simulated water of every {@link WaterRenderer}: its FFT + * waves ({@link WaterRenderer.spectrum}) and interactive ripples + * ({@link WaterRenderer.addRipple}), before anything draws or samples them. + * + * {@link ForwardRendererJob} adds it before the passes that draw or sample + * water when `setting.render.water` is true. + * + * @group Graph + */ +export class WaterSimulationPass extends RenderGraphPass { + public readonly name: string = 'WaterSimulationPass'; + + private _waters: WaterRenderer[] = []; + + public setup(_b: RenderGraphBuilder): void { + } + + public destroy(): void { + this._waters.length = 0; + } + + public execute(ctx: RenderGraphPassContext): void { + const view = ctx.view; + const mask = (this.layerMask & (view.camera?.cullingMask ?? 0xFFFFFFFF)) >>> 0; + ComponentCollect.collectByTypeLayered(view, WaterRenderer, mask, this._waters); + if (!this._waters.some((w) => w.hasSimulation)) return; + const gpu = view.engine3D.context3D.gpuContext; + const command = gpu.beginCommandEncoder(); + for (const water of this._waters) { + if (water.hasSimulation && water.transform?.enable) water.stepSimulation(command, Time.delta * 0.001); + } + gpu.endCommandEncoder(command); + for (const water of this._waters) water.afterSimulationSubmit(); + } +} diff --git a/src/gfx/renderJob/jobs/ForwardRendererJob.ts b/src/gfx/renderJob/jobs/ForwardRendererJob.ts index d13913dea..b2ede6c5f 100644 --- a/src/gfx/renderJob/jobs/ForwardRendererJob.ts +++ b/src/gfx/renderJob/jobs/ForwardRendererJob.ts @@ -2,6 +2,7 @@ import { View3D } from '../../../core/View3D'; import { ClusterLightingPass } from '../graph/passes/ClusterLightingPass'; import { ColorPass } from '../graph/passes/ColorPass'; import { DecalShadowVolumePass } from '../graph/passes/DecalShadowVolumePass'; +import { FluidPass } from '../graph/passes/FluidPass'; import { GBufferResourcePass } from '../graph/passes/GBufferResourcePass'; import { GIPass } from '../graph/passes/GIPass'; import { GPUCullPass } from '../graph/passes/GPUCullPass'; @@ -14,6 +15,7 @@ import { PreDepthPass } from '../graph/passes/PreDepthPass'; import { ReflectionPass } from '../graph/passes/ReflectionPass'; import { SceneCapturePass } from '../graph/passes/SceneCapturePass'; import { SceneColorPyramidPass } from '../graph/passes/SceneColorPyramidPass'; +import { SceneLinearDepthPass } from '../graph/passes/SceneLinearDepthPass'; import { ShadowPass } from '../graph/passes/ShadowPass'; import { SkyPass } from '../graph/passes/SkyPass'; import { SortedTransparentPass } from '../graph/passes/SortedTransparentPass'; @@ -22,6 +24,9 @@ import { TransparentDualDepthPeelingPass } from '../graph/passes/TransparentDual import { TransparentDualDepthPeelingResolvePass } from '../graph/passes/TransparentDualDepthPeelingResolvePass'; import { TransparentOITPass } from '../graph/passes/TransparentOITPass'; import { TransparentResolvePass } from '../graph/passes/TransparentResolvePass'; +import { UnderwaterPass } from '../graph/passes/UnderwaterPass'; +import { CausticsPass } from '../graph/passes/CausticsPass'; +import { WaterSimulationPass } from '../graph/passes/WaterSimulationPass'; import { RendererJob } from './RendererJob'; /** @@ -30,12 +35,12 @@ import { RendererJob } from './RendererJob'; * * ClusterLighting → [PreDepth] → HiZ → MotionVector → [GPUCull] * → Shadow → PointShadow → Reflection → [GI] → Color - * → SceneColorPyramid → TransmissionOpaque + * → SceneColorPyramid → TransmissionOpaque → [Decal] → [Fluid] * → SortedTransparent (+ optional WBOIT / DDP transparent path) * → Post → GUI(present) * * Bracketed passes are gated on engine settings (`zPrePass`, - * `gpuCull`, `gi.enable`, `useOIT`). + * `gpuCull`, `gi.enable`, `decals`, , `water`, `fluid`, `useOIT`). * * @group GFX */ @@ -47,6 +52,8 @@ export class ForwardRendererJob extends RendererJob { const useOIT = !!(setting.render as any).useOIT; const useGPUCull = !!(setting.render as any).gpuCull; const useDecals = !!(setting.render as any).decals; + const useWater = !!setting.render.water; + const useFluid = !!setting.render.fluid; // Cluster lighting — runs first so downstream passes can // sample _ClusterLightingBuffer. @@ -101,6 +108,12 @@ export class ForwardRendererJob extends RendererJob { // same g-buffer without any of them being the resource creator. this.graph.add(GBufferResourcePass); + // Simulated water (FFT waves, interactive ripples), stepped before the + // passes that draw or sample it (opt-in via `setting.render.water`). + if (useWater) { + this.graph.add(WaterSimulationPass); + } + // Main color pass. Reads cluster + shadow + reflection inputs + // the shared GBuffer published by GBufferResourcePass. Pure // opaque draw — sky lives in its own pass below. @@ -114,9 +127,21 @@ export class ForwardRendererJob extends RendererJob { // pipeline; the rest of the graph keeps working. this.graph.add(SkyPass); + // Sunlight caustics under water surfaces, on the opaque scene before + // the pyramid captures it (opt-in via `setting.render.water`). + if (useWater) { + this.graph.add(CausticsPass); + } + // Scene color pyramid snapshot for transmission / refraction. this.graph.add(SceneColorPyramidPass); + // Linear depth of the opaque scene for water (sampled by its material + // in the transmission pass, while the depth texture is attached). + if (useWater) { + this.graph.add(SceneLinearDepthPass); + } + // Transmission split: opaque-with-transmission deferred to // after the pyramid so refraction samples the world behind. this.graph.add(TransmissionOpaquePass); @@ -131,6 +156,12 @@ export class ForwardRendererJob extends RendererJob { this.graph.add(DecalShadowVolumePass); } + // Screen-space fluid — opt-in via `setting.render.fluid`. Clipped + // by opaque depth; transparents draw over it. + if (useFluid) { + this.graph.add(FluidPass); + } + // Transparent half. With useOIT, sorted gets the 'sorted' // filter (skips weighted-OIT materials); without it, sorted // renders every transparent node. @@ -142,6 +173,12 @@ export class ForwardRendererJob extends RendererJob { this.graph.add(TransparentDualDepthPeelingResolvePass); } + // Underwater view of water surfaces — after every color write, + // before post (opt-in via `setting.render.water`). + if (useWater) { + this.graph.add(UnderwaterPass); + } + // Post chain (FXAA + Tonemap default; user adds more via // PostProcessingComponent → RendererJob.addPost). this.graph.add(PostPass); diff --git a/src/gfx/renderJob/post/LensPost.ts b/src/gfx/renderJob/post/LensPost.ts new file mode 100644 index 000000000..24fc54907 --- /dev/null +++ b/src/gfx/renderJob/post/LensPost.ts @@ -0,0 +1,115 @@ +import { ShaderLib } from '../../../assets/shader/ShaderLib'; +import { LensShader } from '../../../assets/shader/post/LensShader'; +import { View3D } from '../../../core/View3D'; +import { ViewQuad } from '../../../core/ViewQuad'; +import { Color } from '../../../math/Color'; +import { Vector4 } from '../../../math/Vector4'; +import { RenderTexture } from '../../../textures/RenderTexture'; +import { Time } from '../../../util/Time'; +import { GPUTextureFormat } from '../../graphics/webGpu/WebGPUConst'; +import { PostBase } from './PostBase'; + +/** + * Lens effects in a single fullscreen pass: vignette, chromatic aberration + * and film grain. Runs in scene-linear HDR ahead of the final tonemap, so + * the grain and the darkened corners go through the same tone curve as the + * rest of the image. + * + * ```ts + * const post = scene.addComponent(PostProcessingComponent); + * const lens = post.addPost(LensPost); + * lens.vignetteIntensity = 0.45; + * lens.chromaticAberration = 0.08; + * lens.grainIntensity = 0.12; + * ``` + * @group Post Effects + */ +export class LensPost extends PostBase { + public postQuad: ViewQuad; + public renderTexture: RenderTexture; + + private _vignetteParams = new Vector4(); + private _lensParams = new Vector4(); + private _vignetteColor = new Vector4(); + + constructor() { + super(); + ShaderLib.register('Lens_Shader', LensShader); + } + + protected createResource(view: View3D) { + let [w, h] = this._boundCtx!.presentationSize; + this.renderTexture = this.createRTTexture(`LensPost`, w, h, GPUTextureFormat.rgba16float); + this.postQuad = this.createViewQuad(`lens`, 'Lens_Shader', this.renderTexture); + this.applyUniforms(); + } + + public onResize() { + let [w, h] = this._boundCtx!.presentationSize; + this.renderTexture?.resize(w, h); + } + + /** @internal */ + public onAttach(view: View3D) { + this.setting.render.postProcessing.lens.enable = true; + } + + /** @internal */ + public onDetach(view: View3D) { + this.setting.render.postProcessing.lens.enable = false; + } + + private get _s() { + return this.setting.render.postProcessing.lens; + } + + /** Vignette strength, 0 = off. */ + public get vignetteIntensity(): number { return this._s.vignetteIntensity; } + public set vignetteIntensity(v: number) { this._s.vignetteIntensity = Math.max(0, v); } + + /** Vignette falloff softness, 0..1. */ + public get vignetteSmoothness(): number { return this._s.vignetteSmoothness; } + public set vignetteSmoothness(v: number) { this._s.vignetteSmoothness = Math.min(Math.max(v, 0), 1); } + + /** 1 = circular, 0 = follows the screen rectangle. */ + public get vignetteRoundness(): number { return this._s.vignetteRoundness; } + public set vignetteRoundness(v: number) { this._s.vignetteRoundness = Math.min(Math.max(v, 0), 1); } + + /** Color the corners fade to. */ + public get vignetteColor(): Color { return this._s.vignetteColor; } + public set vignetteColor(v: Color) { this._s.vignetteColor.copy(v); } + + /** Chromatic aberration strength, 0 = off. */ + public get chromaticAberration(): number { return this._s.chromaticAberration; } + public set chromaticAberration(v: number) { this._s.chromaticAberration = Math.max(0, v); } + + /** Film grain strength, 0 = off. */ + public get grainIntensity(): number { return this._s.grainIntensity; } + public set grainIntensity(v: number) { this._s.grainIntensity = Math.max(0, v); } + + /** Freeze the grain pattern. */ + public get grainStatic(): boolean { return this._s.grainStatic; } + public set grainStatic(v: boolean) { this._s.grainStatic = v; } + + public render(view: View3D, command: GPUCommandEncoder) { + this.applyUniforms(); + this.rtViewQuad.forEach((viewQuad) => { + let lastTexture = this._boundCtx!.gpuContext.lastRenderPassState.getLastRenderTexture(this._boundCtx!); + viewQuad.renderToViewQuad(view, viewQuad, command, lastTexture); + }); + } + + private applyUniforms() { + if (!this.postQuad) return; + const s = this._s; + const [w, h] = this._boundCtx!.presentationSize; + const c = s.vignetteColor; + this._vignetteColor.set(c.r, c.g, c.b, 1); + this._vignetteParams.set(s.vignetteIntensity, s.vignetteSmoothness, s.vignetteRoundness, h > 0 ? w / h : 1); + this._lensParams.set(s.chromaticAberration, s.grainIntensity, s.grainStatic ? 0 : (Time.frame % 1024), 0); + const shader = this.postQuad.quadShader; + shader.setUniform('vignetteColor', this._vignetteColor); + shader.setUniform('vignetteParams', this._vignetteParams); + shader.setUniform('lensParams', this._lensParams); + } +} diff --git a/src/gfx/renderJob/post/MotionBlurPost.ts b/src/gfx/renderJob/post/MotionBlurPost.ts new file mode 100644 index 000000000..6a62356a4 --- /dev/null +++ b/src/gfx/renderJob/post/MotionBlurPost.ts @@ -0,0 +1,153 @@ +import { MotionBlur_cs } from '../../../assets/shader/compute/MotionBlur_cs'; +import { View3D } from '../../../core/View3D'; +import { Matrix4 } from '../../../math/Matrix4'; +import { Vector4 } from '../../../math/Vector4'; +import { VirtualTexture } from '../../../textures/VirtualTexture'; +import { MotionBlurUtil } from '../../../util/MotionBlurUtil'; +import { Time } from '../../../util/Time'; +import { GlobalBindGroup } from '../../graphics/webGpu/core/bindGroups/GlobalBindGroup'; +import { UniformGPUBuffer } from '../../graphics/webGpu/core/buffer/UniformGPUBuffer'; +import { RTDescriptor } from '../../graphics/webGpu/descriptor/RTDescriptor'; +import { WebGPUDescriptorCreator } from '../../graphics/webGpu/descriptor/WebGPUDescriptorCreator'; +import { ComputeShader } from '../../graphics/webGpu/shader/ComputeShader'; +import { GPUTextureFormat } from '../../graphics/webGpu/WebGPUConst'; +import { GBufferFrame } from '../frame/GBufferFrame'; +import { RTFrame } from '../frame/RTFrame'; +import { RendererPassState } from '../passRenderer/state/RendererPassState'; +import { PostBase } from './PostBase'; + +/** + * Camera motion blur. Each pixel is averaged along the screen-space path it + * travelled since the previous frame (reconstructed from depth and the + * previous view-projection), so panning, orbiting and dollying the camera + * streak the image the way a real shutter does. + * + * Limitation: only camera motion is blurred — objects that move on their own + * stay sharp, because the G-buffer carries no per-object velocity. + * + * ```ts + * const post = scene.addComponent(PostProcessingComponent); + * const blur = post.addPost(MotionBlurPost); + * blur.intensity = 0.5; // 180° shutter + * ``` + * @group Post Effects + */ +export class MotionBlurPost extends PostBase { + /** @internal */ + public outTexture: VirtualTexture; + private _compute: ComputeShader; + private _data: UniformGPUBuffer; + private _rtFrame: RTFrame; + private _prevViewProj: Matrix4 = new Matrix4().identity(); + private _currViewProj: Matrix4 = new Matrix4().identity(); + private _hasPrev: boolean = false; + private _params: Vector4 = new Vector4(); + + /** @internal */ + public onAttach(view: View3D) { + this.setting.render.postProcessing.motionBlur.enable = true; + this._hasPrev = false; + } + + /** @internal */ + public onDetach(view: View3D) { + this.setting.render.postProcessing.motionBlur.enable = false; + } + + private get _s() { + return this.setting.render.postProcessing.motionBlur; + } + + /** Shutter scale, 0 = off, 0.5 = 180° shutter, 1 = full frame. */ + public get intensity(): number { return this._s.intensity; } + public set intensity(v: number) { this._s.intensity = Math.max(0, v); } + + /** Samples along the blur vector (2…32). */ + public get samples(): number { return this._s.samples; } + public set samples(v: number) { this._s.samples = Math.min(Math.max(Math.round(v), 2), 32); } + + /** Maximum blur length in pixels. */ + public get maxBlurPixels(): number { return this._s.maxBlurPixels; } + public set maxBlurPixels(v: number) { this._s.maxBlurPixels = Math.max(0, v); } + + /** Keep the blur length independent of the frame rate. */ + public get frameRateIndependent(): boolean { return this._s.frameRateIndependent; } + public set frameRateIndependent(v: boolean) { this._s.frameRateIndependent = v; } + + /** + * Forget the previous camera pose, so the next frame is not blurred. + * Call after a camera cut / teleport. + */ + public resetHistory(): void { + this._hasPrev = false; + } + + /** The view-projection used as "previous" on the last rendered frame. */ + public get prevViewProj(): Matrix4 { return this._prevViewProj; } + /** The view-projection of the last rendered frame. */ + public get currViewProj(): Matrix4 { return this._currViewProj; } + + private _create(view: View3D) { + const ctx = this._boundCtx!; + const [w, h] = ctx.presentationSize; + this.outTexture = new VirtualTexture(w, h, GPUTextureFormat.rgba16float, false, GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.TEXTURE_BINDING, 1, 0, 1, ctx); + this.outTexture.name = 'motionBlurTex'; + const desc = new RTDescriptor(); + desc.loadOp = 'load'; + this._rtFrame = new RTFrame([this.outTexture], [desc]); + + this._compute = new ComputeShader(MotionBlur_cs); + // mat4 (16 floats) + vec4 (4 floats) + this._data = new UniformGPUBuffer(16 + 4); + this._compute.setUniformBuffer('motionBlurData', this._data); + this._compute.setUniformBuffer('globalUniform', GlobalBindGroup.getCameraGroup(view.camera).uniformGPUBuffer); + const gbuffer = GBufferFrame.getGBufferFrame(GBufferFrame.colorPass_GBuffer, ctx); + this._compute.setSamplerTexture('gBufferTexture', gbuffer.getCompressGBufferTexture()); + this._compute.setSamplerTexture('inTex', this.getLastRenderTexture()); + this._compute.setStorageTexture('outTex', this.outTexture); + + this.rendererPassState = WebGPUDescriptorCreator.createRendererPassState(ctx, this._rtFrame, null); + this.rendererPassState.label = 'MotionBlur'; + this._updateWorkerSize(); + } + + private _updateWorkerSize() { + this._compute.workerSizeX = Math.ceil(this.outTexture.width / 8); + this._compute.workerSizeY = Math.ceil(this.outTexture.height / 8); + this._compute.workerSizeZ = 1; + } + + /** @internal */ + public render(view: View3D, command: GPUCommandEncoder) { + if (!this._compute) this._create(view); + this.bindUpstream(this._compute, 'inTex'); + + const camera = view.camera; + this._currViewProj.multiplyMatrices(camera.projectionMatrix, camera.viewMatrix); + // First frame (or after resetHistory): previous == current → zero velocity. + if (!this._hasPrev) { + this._prevViewProj.copy(this._currViewProj); + this._hasPrev = true; + } + + const s = this._s; + const scale = MotionBlurUtil.shutterScale(s.intensity, Time.delta, s.frameRateIndependent); + this._params.set(scale, s.samples, s.maxBlurPixels, 0); + this._data.setMatrix('prevViewProj', this._prevViewProj); + this._data.setVector4('params', this._params); + this._data.apply(); + + this._boundCtx!.gpuContext.computeCommand(command, [this._compute]); + this._boundCtx!.gpuContext.lastRenderPassState = this.rendererPassState; + + this._prevViewProj.copy(this._currViewProj); + } + + public onResize() { + if (!this.outTexture) return; + const [w, h] = this._boundCtx!.presentationSize; + this.outTexture.resize(w, h); + this._updateWorkerSize(); + this._hasPrev = false; + } +} diff --git a/src/gfx/renderJob/post/TonemapPost.ts b/src/gfx/renderJob/post/TonemapPost.ts index ca81c8e21..2827b0d2b 100644 --- a/src/gfx/renderJob/post/TonemapPost.ts +++ b/src/gfx/renderJob/post/TonemapPost.ts @@ -5,10 +5,12 @@ import { ViewQuad } from '../../../core/ViewQuad'; import { GPUTextureFormat } from '../../graphics/webGpu/WebGPUConst'; import { RenderTexture } from '../../../textures/RenderTexture'; import { PostBase } from './PostBase'; +import { TonemapUtil } from '../../../util/TonemapUtil'; /** - * Final HDR → LDR tonemap pass. Applies an ACES Filmic curve (or - * passthrough) and writes to an `rgba16float` RT — keeping the chain + * Final HDR → LDR tonemap pass. Applies the curve selected by + * `setting.render.tonemap.mode` (ACES, Reinhard, Uncharted2, AgX, Khronos + * Neutral or passthrough) and writes to an `rgba16float` RT — keeping the chain * HDR-correct so the swapchain (in sRGB hardware-encode mode) does * the linear→sRGB step. Reads the chain cursor via * `lastRenderPassState.getLastRenderTexture`, identical to FXAAPost. @@ -68,8 +70,12 @@ export class TonemapPost extends PostBase { if (!this.postQuad) return; const tm = this.setting.render.tonemap; const exposure = tm ? tm.exposure : 1.0; - const mode = tm && tm.mode === 'None' ? 0.0 : 1.0; + const mode = TonemapUtil.modeIndex(tm?.mode); this.postQuad.quadShader.setUniform('exposure', exposure); this.postQuad.quadShader.setUniform('mode', mode); + this.postQuad.quadShader.setUniform('whitePoint', tm?.whitePoint ?? 4.0); + // Every MaterialUniform field needs a value before the bind group is + // generated, including the alignment pad. + this.postQuad.quadShader.setUniform('tonemapPad', 0.0); } } diff --git a/src/index.ts b/src/index.ts index 2f81ff86a..e9a259c5b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,6 +22,7 @@ export * from "./assets/shader/compute/GodRay_cs" export * from "./assets/shader/compute/HiZGenerate_cs" export * from "./assets/shader/compute/IBLEnvMapCreator_cs" export * from "./assets/shader/compute/MergeRGBA_cs" +export * from "./assets/shader/compute/MotionBlur_cs" export * from "./assets/shader/compute/MotionVector_cs" export * from "./assets/shader/compute/MultiBouncePass_cs" export * from "./assets/shader/compute/OutLineBlendColor_cs" @@ -74,6 +75,8 @@ export * from "./assets/shader/core/struct/VertexAttributeIndexShader" export * from "./assets/shader/core/struct/VertexAttributes" export * from "./assets/shader/core/struct/VertexOutput" export * from "./assets/shader/env/ReflectionCG" +export * from "./assets/shader/fluid/FluidAnisotropy_shader" +export * from "./assets/shader/fluid/FluidParticle_shader" export * from "./assets/shader/glsl/Quad_glsl" export * from "./assets/shader/glsl/Sky_glsl" export * from "./assets/shader/glsl/post/LUT_glsl" @@ -103,11 +106,14 @@ export * from "./assets/shader/materials/ReflectionShader_shader" export * from "./assets/shader/materials/Sprite_shader" export * from "./assets/shader/materials/UnLit" export * from "./assets/shader/materials/UnLitTextureArray" +export * from "./assets/shader/materials/WaterShader" export * from "./assets/shader/materials/program/BxdfDebug_frag" export * from "./assets/shader/materials/program/Clearcoat_frag" export * from "./assets/shader/materials/program/ClusterDebug_frag" +export * from "./assets/shader/materials/program/Iridescence_frag" export * from "./assets/shader/materials/program/NormalMap_frag" export * from "./assets/shader/materials/program/ShadowMapping_frag" +export * from "./assets/shader/materials/program/Sheen_frag" export * from "./assets/shader/materials/uniforms/MaterialUniform" export * from "./assets/shader/materials/uniforms/PhysicMaterialUniform_frag" export * from "./assets/shader/materials/uniforms/UnLitMaterialUniform_frag" @@ -118,6 +124,7 @@ export * from "./assets/shader/math/MatrixShader" export * from "./assets/shader/post/DDPResolveShader" export * from "./assets/shader/post/FXAAShader" export * from "./assets/shader/post/GlobalFog_shader" +export * from "./assets/shader/post/LensShader" export * from "./assets/shader/post/OITResolveShader" export * from "./assets/shader/post/TonemapShader" export * from "./assets/shader/quad/Quad_shader" @@ -193,8 +200,11 @@ export * from "./components/matrix/WasmMatrix" export * from "./components/post/PostProcessingComponent" export * from "./components/renderer/EarthAtmRenderer" export * from "./components/renderer/EarthSkyRenderer" +export * from "./components/renderer/FluidRenderer" export * from "./components/renderer/GlobalIlluminationComponent" export * from "./components/renderer/InstanceDrawComponent" +export * from "./components/renderer/LODGroup" +export * from "./components/renderer/MaterialVariants" export * from "./components/renderer/MeshFilter" export * from "./components/renderer/MeshRenderer" export * from "./components/renderer/Reflection" @@ -205,6 +215,12 @@ export * from "./components/renderer/SkyRenderer" export * from "./components/renderer/SphereReflection" export * from "./components/renderer/SpriteBatch" export * from "./components/renderer/SpriteRenderer" +export * from "./components/renderer/WaterFFT" +export * from "./components/renderer/WaterFoamTexture" +export * from "./components/renderer/WaterFootprint" +export * from "./components/renderer/WaterRenderer" +export * from "./components/renderer/WaterRipples" +export * from "./components/renderer/WaterSpectrum" export * from "./components/shape/BoxColliderShape" export * from "./components/shape/CapsuleColliderShape" export * from "./components/shape/ColliderShape" @@ -241,6 +257,7 @@ export * from "./core/pool/ObjectPool" export * from "./core/pool/memory/MatrixDO" export * from "./core/pool/memory/MemoryDO" export * from "./core/pool/memory/MemoryInfo" +export * from "./core/tree/bvh/MeshBVH" export * from "./core/tree/kdTree/IKDTreeUserData" export * from "./core/tree/kdTree/KDTreeEntity" export * from "./core/tree/kdTree/KDTreeNode" @@ -352,10 +369,12 @@ export * from "./gfx/renderJob/graph/RenderGraphPass" export * from "./gfx/renderJob/graph/RenderGraphRenderPass" export * from "./gfx/renderJob/graph/RenderGraphRenderTarget" export * from "./gfx/renderJob/graph/RenderGraphResourcePool" +export * from "./gfx/renderJob/graph/passes/CausticsPass" export * from "./gfx/renderJob/graph/passes/ClearDepthPass" export * from "./gfx/renderJob/graph/passes/ClusterLightingPass" export * from "./gfx/renderJob/graph/passes/ColorPass" export * from "./gfx/renderJob/graph/passes/DecalShadowVolumePass" +export * from "./gfx/renderJob/graph/passes/FluidPass" export * from "./gfx/renderJob/graph/passes/GBufferResourcePass" export * from "./gfx/renderJob/graph/passes/GIPass" export * from "./gfx/renderJob/graph/passes/GPUCullPass" @@ -368,6 +387,7 @@ export * from "./gfx/renderJob/graph/passes/PreDepthPass" export * from "./gfx/renderJob/graph/passes/ReflectionPass" export * from "./gfx/renderJob/graph/passes/SceneCapturePass" export * from "./gfx/renderJob/graph/passes/SceneColorPyramidPass" +export * from "./gfx/renderJob/graph/passes/SceneLinearDepthPass" export * from "./gfx/renderJob/graph/passes/ShadowPass" export * from "./gfx/renderJob/graph/passes/SkyPass" export * from "./gfx/renderJob/graph/passes/SortedTransparentPass" @@ -376,6 +396,8 @@ export * from "./gfx/renderJob/graph/passes/TransparentDualDepthPeelingPass" export * from "./gfx/renderJob/graph/passes/TransparentDualDepthPeelingResolvePass" export * from "./gfx/renderJob/graph/passes/TransparentOITPass" export * from "./gfx/renderJob/graph/passes/TransparentResolvePass" +export * from "./gfx/renderJob/graph/passes/UnderwaterPass" +export * from "./gfx/renderJob/graph/passes/WaterSimulationPass" export * from "./gfx/renderJob/graph/transient/LifetimeAnalyzer" export * from "./gfx/renderJob/graph/transient/ResourceDesc" export * from "./gfx/renderJob/graph/transient/ResourceHandle" @@ -410,6 +432,8 @@ export * from "./gfx/renderJob/post/GBufferPost" export * from "./gfx/renderJob/post/GTAOPost" export * from "./gfx/renderJob/post/GlobalFog" export * from "./gfx/renderJob/post/GodRayPost" +export * from "./gfx/renderJob/post/LensPost" +export * from "./gfx/renderJob/post/MotionBlurPost" export * from "./gfx/renderJob/post/OutlinePost" export * from "./gfx/renderJob/post/PostBase" export * from "./gfx/renderJob/post/SSGIPost" @@ -427,6 +451,10 @@ export * from "./io/PickResult" export * from "./io/RayCastMeshDetail" export * from "./io/TouchData" export * from "./io/picker/PickCompute" +export * from "./io/raycast/MeshDeformer" +export * from "./io/raycast/MeshRaycast" +export * from "./io/raycast/RaycastHit" +export * from "./io/raycast/Raycaster" export * from "./loader/FileLoader" export * from "./loader/LoaderBase" export * from "./loader/LoaderFunctions" @@ -463,6 +491,7 @@ export * from "./loader/parser/gltf/extends/KHR_lights_punctual" export * from "./loader/parser/gltf/extends/KHR_materials_clearcoat" export * from "./loader/parser/gltf/extends/KHR_materials_emissive_strength" export * from "./loader/parser/gltf/extends/KHR_materials_ior" +export * from "./loader/parser/gltf/extends/KHR_materials_iridescence" export * from "./loader/parser/gltf/extends/KHR_materials_sheen" export * from "./loader/parser/gltf/extends/KHR_materials_specular" export * from "./loader/parser/gltf/extends/KHR_materials_transmission" @@ -525,6 +554,7 @@ export * from "./materials/SoftParticleMaterial" export * from "./materials/SpriteMaterial" export * from "./materials/UnLitMaterial" export * from "./materials/UnLitTexArrayMaterial" +export * from "./materials/WaterMaterial" export * from "./materials/multiPass/CastPointShadowMaterialPass" export * from "./materials/multiPass/CastShadowMaterialPass" export * from "./materials/multiPass/DDPBackPass" @@ -540,10 +570,13 @@ export * from "./math/AnimationCurveT" export * from "./math/Bezier2D" export * from "./math/Bezier3D" export * from "./math/BiMap" +export * from "./math/Box2" +export * from "./math/CatmullRomCurve3" export * from "./math/Color" export * from "./math/ColorGradient" export * from "./math/CubicBezierCurve" export * from "./math/CubicBezierPath" +export * from "./math/Cylindrical" export * from "./math/DoublePrecision" export * from "./math/HaltonSeq" export * from "./math/Line" @@ -564,6 +597,7 @@ export * from "./math/Rand" export * from "./math/Random" export * from "./math/Ray" export * from "./math/Rect" +export * from "./math/Spherical" export * from "./math/TimeInterpolator" export * from "./math/Triangle" export * from "./math/UV" @@ -604,6 +638,8 @@ export * from "./setting/post/DepthOfViewSetting" export * from "./setting/post/GTAOSetting" export * from "./setting/post/GlobalFogSetting" export * from "./setting/post/GodRaySetting" +export * from "./setting/post/LensSetting" +export * from "./setting/post/MotionBlurSetting" export * from "./setting/post/OutlineSetting" export * from "./setting/post/SSGISetting" export * from "./setting/post/SSRSetting" @@ -646,7 +682,10 @@ export * from "./util/DelayUtil" export * from "./util/GeometryUtil" export * from "./util/Global" export * from "./util/GridObject" +export * from "./util/IridescenceUtil" export * from "./util/KelvinUtil" +export * from "./util/LensUtil" +export * from "./util/MotionBlurUtil" export * from "./util/Object3DUtil" export * from "./util/ProfilerUtil" export * from "./util/Reference" @@ -654,6 +693,7 @@ export * from "./util/SerializeDecoration" export * from "./util/StorageUtil" export * from "./util/StringUtil" export * from "./util/Time" +export * from "./util/TonemapUtil" export * from "./util/UIUtil" export * from "./util/Vector3Ex" export * from "./util/ZSorterUtil" diff --git a/src/io/PickFire.ts b/src/io/PickFire.ts index 8fbe9ff8b..99f06a098 100644 --- a/src/io/PickFire.ts +++ b/src/io/PickFire.ts @@ -9,6 +9,7 @@ import { View3D } from '../core/View3D'; import { PointerEvent3D } from '../event/eventConst/PointerEvent3D'; import { HitInfo } from '../components/shape/ColliderShape'; import { ComponentCollect, Matrix4 } from '..'; +import { VisibleLayer } from '../gfx/renderJob/config/VisibleLayer'; /** * Management and triggering for picking 3D objects @@ -41,6 +42,15 @@ export class PickFire extends CEventDispatcher { * a map records the association information between meshID(matrix id) and ColliderComponent */ public mouseEnableMap: Map; + + /** + * `bound` mode: only colliders whose `visibleLayer` shares a bit with + * this mask are picked. + */ + public layerMask: number = VisibleLayer.All; + + /** `bound` mode: optional per-collider filter; return false to skip a collider. */ + public filter: ((collider: ColliderComponent) => boolean) | null = null; private _view: View3D; constructor(view: View3D) { @@ -162,11 +172,22 @@ export class PickFire extends CEventDispatcher { } else { let intersection = this._interestList[0]; if (intersection) { + // Hit objects are created fresh by each pick, so handing them + // out does not let the next pick overwrite them. return { worldPos: intersection.intersectPoint, worldNormal: intersection.normal, meshID: intersection.collider.transform.worldMatrix.index, distance: intersection.distance, + localPos: intersection.localPoint, + faceNormal: intersection.faceNormal, + faceIndex: intersection.faceIndex, + barycentric: intersection.barycentric, + uv: intersection.uv, + uv1: intersection.uv1, + subGeometryIndex: intersection.subGeometryIndex, + frontFace: intersection.frontFace, + hits: this._interestList.slice(), }; } return { @@ -281,7 +302,7 @@ export class PickFire extends CEventDispatcher { if (colliders) { for (const item of colliders) { let collider = item[0]; - if (collider.enable) { + if (collider.enable && (collider.visibleLayer & this.layerMask) !== 0 && (!this.filter || this.filter(collider))) { intersect = collider.rayPick(this.ray); if (intersect) { intersect.collider = collider; diff --git a/src/io/raycast/MeshDeformer.ts b/src/io/raycast/MeshDeformer.ts new file mode 100644 index 000000000..bf9d505ba --- /dev/null +++ b/src/io/raycast/MeshDeformer.ts @@ -0,0 +1,321 @@ +import { GeometryBase } from '../../core/geometry/GeometryBase'; +import { VertexAttributeData } from '../../core/geometry/VertexAttributeData'; +import { VertexAttributeName } from '../../core/geometry/VertexAttributeName'; +import { MeshAttributeView, MeshBVH } from '../../core/tree/bvh/MeshBVH'; +import { MeshRenderer } from '../../components/renderer/MeshRenderer'; +import { Matrix4 } from '../../math/Matrix4'; + +/** + * How ray queries treat meshes the GPU deforms (skinning, morph targets): + * - `cpu`: deform the vertices on the CPU the way the vertex shader does, + * then intersect the result (default) + * - `bindPose`: intersect the undeformed geometry + * - `skip`: ignore deformed meshes + * @group IO + */ +export type RaycastDeformation = 'cpu' | 'bindPose' | 'skip'; + +/** Result of `MeshDeformer.deform`. */ +export interface DeformedMesh { + /** + * CPU-only geometry holding the deformed positions/normals (shares the + * source indices, uvs and sub-geometries). Reused across calls. + */ + geometry: GeometryBase; + /** True when positions are already in world space (skinned); false → mesh local space (morph only). */ + worldSpace: boolean; +} + +/** + * A geometry that only lives on the CPU: attributes are kept in a plain + * map, so no GPU index/vertex buffers are ever created for it. + */ +class CpuGeometry extends GeometryBase { + private _cpuAttributes = new Map(); + private _cpuVersion = 0; + + public setCpuAttribute(name: string, data: ArrayLike) { + this._cpuAttributes.set(name, { attribute: name, data: data as any }); + } + + public getAttribute(attribute: string): VertexAttributeData { + return this._cpuAttributes.get(attribute); + } + + public hasAttribute(attribute: string): boolean { + return this._cpuAttributes.has(attribute); + } + + public get version(): number { + return this._cpuVersion; + } + + public touch() { + this._cpuVersion++; + } +} + +/** Skin data gathered from a skinned renderer and its skeleton/animator component. */ +interface SkinSource { + /** Per skin joint: inverse bind matrix (column-major). */ + inverseBind: ArrayLike[]; + /** Per skin joint: bone ID in the skeleton (-1 when unmapped). */ + jointToBone: number[]; + /** Per bone ID: global `Matrix4.index` of the bone's world matrix. */ + boneMatrixIndex: ArrayLike; + joints0: MeshAttributeView; + weights0: MeshAttributeView; + joints1: MeshAttributeView | null; + weights1: MeshAttributeView | null; +} + +/** Morph data gathered from a renderer's `MorphTargetData`. */ +interface MorphSource { + influences: Float32Array; + base: number; + positions: ArrayLike[]; + normals: ArrayLike[] | null; + vIndex: MeshAttributeView | null; +} + +interface DeformState { + source: GeometryBase; + geometry: CpuGeometry; + positions: Float32Array; + normals: Float32Array | null; + /** Skinning matrices + morph weights the current positions were computed with. */ + signature: Float64Array; + sourceVersion: number; + jointToBone: number[]; + jointMapOwner: any; +} + +/** + * CPU replica of the vertex-shader deformation (morph targets, then + * skinning) used by ray queries, so picks match what is drawn. + * + * Skinning reads each bone's current world matrix from the same global + * matrix slot the shader reads (`models.matrix[...]`), multiplies by the + * skin's inverse bind matrix and blends with `joints0/weights0` (and + * `joints1/weights1`), producing world-space positions exactly as the + * shader's `getSkeletonWorldMatrix_*`. Morphing applies + * `position * baseInfluence + Σ influence_i * a_morphPositions_i`. + * + * Results are cached per renderer and recomputed only when the skinning + * matrices or morph weights changed; the cost is O(vertices) per change. + * Normals are deformed with the blended matrix (exact for rotation and + * uniform scale). + * @group IO + */ +export class MeshDeformer { + private static _states: WeakMap = new WeakMap(); + + /** Whether the GPU currently deforms this renderer's geometry (bound skin, or non-trivial morph weights). */ + public static isDeformed(renderer: MeshRenderer): boolean { + return !!MeshDeformer._skin(renderer, MeshDeformer._states.get(renderer)) || !!MeshDeformer._morph(renderer); + } + + /** + * Deform the renderer's geometry as the vertex shader does and return the + * cached CPU geometry, or null when nothing deforms it. + */ + public static deform(renderer: MeshRenderer): DeformedMesh | null { + const source = renderer.geometry; + if (!source) return null; + let state = MeshDeformer._states.get(renderer); + if (state && state.source !== source) state = null; + const skin = MeshDeformer._skin(renderer, state); + const morph = MeshDeformer._morph(renderer); + if (!skin && !morph) return null; + + const pos = MeshBVH.getAttributeView(source, VertexAttributeName.position); + if (!pos) return null; + const vertexCount = ((pos.data.length - pos.offset) / pos.stride) | 0; + if (!state || state.positions.length !== vertexCount * 3) { + state = MeshDeformer._createState(source, vertexCount); + MeshDeformer._states.set(renderer, state); + } + if (skin) { state.jointToBone = skin.jointToBone; state.jointMapOwner = (renderer as any).skeletonAnimation; } + + // Skinning matrices for every skin joint, then the change signature. + const jointCount = skin ? skin.inverseBind.length : 0; + const skinMats = new Float64Array(jointCount * 16); + if (skin) MeshDeformer._skinMatrices(skin, skinMats); + const morphCount = morph ? morph.positions.length : 0; + const sigLength = skinMats.length + morphCount + 2; + let changed = state.sourceVersion !== source.version || state.signature.length !== sigLength; + const sig = changed ? new Float64Array(sigLength) : state.signature; + let k = 0; + for (let i = 0; i < skinMats.length; i++, k++) { if (sig[k] !== skinMats[i]) { sig[k] = skinMats[i]; changed = true; } } + for (let i = 0; i < morphCount; i++, k++) { const w = morph.influences[i]; if (sig[k] !== w) { sig[k] = w; changed = true; } } + const flags = [skin ? 1 : 0, morph ? morph.base : NaN]; + for (let i = 0; i < 2; i++, k++) { if (!Object.is(sig[k], flags[i])) { sig[k] = flags[i]; changed = true; } } + + if (changed) { + state.signature = sig; + state.sourceVersion = source.version; + MeshDeformer._compute(state, source, pos, vertexCount, skin, skinMats, morph); + state.geometry.touch(); + } + return { geometry: state.geometry, worldSpace: !!skin }; + } + + private static _createState(source: GeometryBase, vertexCount: number): DeformState { + const geometry = new CpuGeometry(); + geometry.name = (source.name || '') + '#deformed'; + geometry.subGeometries = source.subGeometries; + const positions = new Float32Array(vertexCount * 3); + geometry.setCpuAttribute(VertexAttributeName.position, positions); + const idx = source.getAttribute(VertexAttributeName.indices); + if (idx && idx.data && idx.data.length > 0) geometry.setCpuAttribute(VertexAttributeName.indices, idx.data as ArrayLike); + let normals: Float32Array = null; + if (MeshBVH.getAttributeView(source, VertexAttributeName.normal)) { + normals = new Float32Array(vertexCount * 3); + geometry.setCpuAttribute(VertexAttributeName.normal, normals); + } + // UVs do not deform: copy them once into plain arrays (they may be interleaved). + for (const name of [VertexAttributeName.uv, VertexAttributeName.TEXCOORD_1]) { + const view = MeshBVH.getAttributeView(source, name); + if (!view) continue; + const out = new Float32Array(vertexCount * 2); + for (let i = 0; i < vertexCount; i++) { + out[i * 2] = view.data[i * view.stride + view.offset]; + out[i * 2 + 1] = view.data[i * view.stride + view.offset + 1]; + } + geometry.setCpuAttribute(name, out); + } + return { source, geometry, positions, normals, signature: new Float64Array(0), sourceVersion: -1, jointToBone: null, jointMapOwner: null }; + } + + private static _skin(renderer: MeshRenderer, state: DeformState | null): SkinSource | null { + const r = renderer as any; + const anim = r.skeletonAnimation; + const inverseBind: ArrayLike[] = r.skinInverseBindMatrices; + const names: string[] = r.skinJointsName; + if (!anim || !inverseBind || !names || inverseBind.length === 0) return null; + // AnimatorComponent (glTF) keeps the table directly; SkeletonAnimationComponent (prefab) on its pose. + const boneMatrixIndex: ArrayLike = anim.jointMatrixIndexTable ?? anim.finalSkeletonPose?.jointMatrixIndexTable; + if (!boneMatrixIndex) return null; + const geometry = renderer.geometry; + const joints0 = MeshBVH.getAttributeView(geometry, VertexAttributeName.joints0); + const weights0 = MeshBVH.getAttributeView(geometry, VertexAttributeName.weights0); + if (!joints0 || !weights0) return null; + const jointToBone = state && state.jointMapOwner === anim && state.jointToBone ? state.jointToBone : anim.getJointIndexTable(names); + return { + inverseBind, jointToBone, boneMatrixIndex, joints0, weights0, + joints1: MeshBVH.getAttributeView(geometry, VertexAttributeName.joints1), + weights1: MeshBVH.getAttributeView(geometry, VertexAttributeName.weights1), + }; + } + + private static _morph(renderer: MeshRenderer): MorphSource | null { + const md = renderer.morphData; + if (!md || !md.enable || !md.morphTargetCount) return null; + const influences = md.influences; + const base = md.baseInfluence; + let active = base !== 1; + for (let i = 0; i < md.morphTargetCount && !active; i++) active = influences[i] !== 0; + if (!active) return null; + const geometry = renderer.geometry; + const positions: ArrayLike[] = []; + const normals: ArrayLike[] = []; + for (let i = 0; i < md.morphTargetCount; i++) { + const p = geometry.getAttribute('a_morphPositions_' + i); + if (!p) return null; + positions.push(p.data as ArrayLike); + const n = geometry.getAttribute('a_morphNormals_' + i); + if (n) normals.push(n.data as ArrayLike); + } + return { + influences, base, positions, + normals: normals.length === positions.length ? normals : null, + vIndex: MeshBVH.getAttributeView(geometry, VertexAttributeName.vIndex), + }; + } + + /** skinMats[j] = boneWorld[jointToBone[j]] × inverseBind[j] (column-major), zero for unmapped joints. */ + private static _skinMatrices(skin: SkinSource, out: Float64Array): void { + const refs = Matrix4.dynamicGlobalMatrixRef; + for (let j = 0; j < skin.inverseBind.length; j++) { + const bone = skin.jointToBone[j]; + const mi = bone >= 0 ? skin.boneMatrixIndex[bone] : -1; + const A = mi >= 0 && refs ? refs[mi]?.rawData : null; + const B = skin.inverseBind[j]; + const o = j * 16; + if (!A || !B) { for (let i = 0; i < 16; i++) out[o + i] = 0; continue; } + for (let c = 0; c < 4; c++) { + for (let r = 0; r < 4; r++) { + out[o + c * 4 + r] = A[r] * B[c * 4] + A[4 + r] * B[c * 4 + 1] + A[8 + r] * B[c * 4 + 2] + A[12 + r] * B[c * 4 + 3]; + } + } + } + } + + private static _compute(state: DeformState, source: GeometryBase, pos: MeshAttributeView, n: number, + skin: SkinSource | null, S: Float64Array, morph: MorphSource | null): void { + const P = pos.data, ps = pos.stride, po = pos.offset; + const nrm = state.normals ? MeshBVH.getAttributeView(source, VertexAttributeName.normal) : null; + const outP = state.positions, outN = state.normals; + const m = new Float64Array(12); + const jointCount = skin ? skin.inverseBind.length : 0; + const activeTargets: number[] = []; + if (morph) for (let t = 0; t < morph.positions.length; t++) if (morph.influences[t] !== 0) activeTargets.push(t); + + for (let i = 0; i < n; i++) { + let x = P[i * ps + po], y = P[i * ps + po + 1], z = P[i * ps + po + 2]; + let nx = 0, ny = 0, nz = 0; + if (nrm) { const b = i * nrm.stride + nrm.offset; nx = nrm.data[b]; ny = nrm.data[b + 1]; nz = nrm.data[b + 2]; } + + if (morph) { + const vi = morph.vIndex ? morph.vIndex.data[i * morph.vIndex.stride + morph.vIndex.offset] : i; + const b = morph.base; + x *= b; y *= b; z *= b; + if (nrm) { nx *= b; ny *= b; nz *= b; } + for (const t of activeTargets) { + const w = morph.influences[t], D = morph.positions[t], o = vi * 3; + x += w * D[o]; y += w * D[o + 1]; z += w * D[o + 2]; + if (nrm && morph.normals) { const N = morph.normals[t]; nx += w * N[o]; ny += w * N[o + 1]; nz += w * N[o + 2]; } + } + } + + if (skin) { + m.fill(0); + MeshDeformer._blend(m, S, skin.joints0, skin.weights0, i, jointCount); + if (skin.joints1 && skin.weights1) MeshDeformer._blend(m, S, skin.joints1, skin.weights1, i, jointCount); + // m holds the upper 3×4 of the blended column-major matrix: [c0.xyz, c1.xyz, c2.xyz, c3.xyz]. + const sx = m[0] * x + m[3] * y + m[6] * z + m[9]; + const sy = m[1] * x + m[4] * y + m[7] * z + m[10]; + const sz = m[2] * x + m[5] * y + m[8] * z + m[11]; + x = sx; y = sy; z = sz; + if (nrm) { + const tx = m[0] * nx + m[3] * ny + m[6] * nz; + const ty = m[1] * nx + m[4] * ny + m[7] * nz; + const tz = m[2] * nx + m[5] * ny + m[8] * nz; + nx = tx; ny = ty; nz = tz; + } + } + + outP[i * 3] = x; outP[i * 3 + 1] = y; outP[i * 3 + 2] = z; + if (outN) { + const l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; + outN[i * 3] = nx / l; outN[i * 3 + 1] = ny / l; outN[i * 3 + 2] = nz / l; + } + } + } + + /** m += Σ_k weight_k × S[joint_k] (upper 3×4) for one vertex's 4 joint slots. */ + private static _blend(m: Float64Array, S: Float64Array, joints: MeshAttributeView, weights: MeshAttributeView, i: number, jointCount: number): void { + const jb = i * joints.stride + joints.offset, wb = i * weights.stride + weights.offset; + for (let k = 0; k < 4; k++) { + const w = weights.data[wb + k]; + if (w === 0) continue; + const j = joints.data[jb + k] | 0; + if (j < 0 || j >= jointCount) continue; + const o = j * 16; + m[0] += w * S[o]; m[1] += w * S[o + 1]; m[2] += w * S[o + 2]; + m[3] += w * S[o + 4]; m[4] += w * S[o + 5]; m[5] += w * S[o + 6]; + m[6] += w * S[o + 8]; m[7] += w * S[o + 9]; m[8] += w * S[o + 10]; + m[9] += w * S[o + 12]; m[10] += w * S[o + 13]; m[11] += w * S[o + 14]; + } + } +} diff --git a/src/io/raycast/MeshRaycast.ts b/src/io/raycast/MeshRaycast.ts new file mode 100644 index 000000000..cc774f08d --- /dev/null +++ b/src/io/raycast/MeshRaycast.ts @@ -0,0 +1,218 @@ +import { GeometryBase } from '../../core/geometry/GeometryBase'; +import { VertexAttributeName } from '../../core/geometry/VertexAttributeName'; +import { MeshAttributeView, MeshBVH, MeshBVHCull, MeshBVHHit, MeshBVHRayOptions } from '../../core/tree/bvh/MeshBVH'; +import { Matrix4 } from '../../math/Matrix4'; +import { Ray } from '../../math/Ray'; +import { Vector2 } from '../../math/Vector2'; +import { Vector3 } from '../../math/Vector3'; +import { RaycastHit } from './RaycastHit'; +import { MeshDeformer, RaycastDeformation } from './MeshDeformer'; +import { MeshRenderer } from '../../components/renderer/MeshRenderer'; + +/** + * When a ray query uses a geometry's `MeshBVH`: + * - `auto`: when one has been built (`MeshBVH.build` / `MeshBVH.get`), + * otherwise test every triangle + * - `always`: build one on first use + * - `never`: always test every triangle + * @group IO + */ +export type RaycastBVHMode = 'auto' | 'always' | 'never'; + +/** + * Options for `MeshRaycast.intersect`. Distances are world space. + * @group IO + */ +export interface MeshRaycastOptions { + /** Ignore hits closer than this. Default 0. */ + near?: number; + /** Ignore hits farther than this. Default Infinity. */ + far?: number; + /** + * Faces to ignore, as they appear in the world (a mirroring transform + * flips the local winding; that is accounted for). Default `'none'`. + */ + cull?: MeshBVHCull | boolean; + /** Default `'auto'`. */ + useBVH?: RaycastBVHMode; + /** Report every hit instead of only the closest. Default false. */ + all?: boolean; + /** How skinned / morphed renderers are handled by `intersectRenderer`. Default `'cpu'`. */ + deformation?: RaycastDeformation; + /** + * Per-hit predicate, given the local hit and whether it is a front face + * in world space. Rejected hits do not hide hits behind them. + */ + accept?: (hit: MeshBVHHit, frontFace: boolean) => boolean; +} + +/** + * World-space ray queries against one geometry under a transform. Shared by + * `Raycaster` and `MeshColliderShape`, so both report the same hit data. + * @group IO + */ +export class MeshRaycast { + // Matrix4 storage comes from a pool that exists only after engine init: create lazily. + private static _inv: Matrix4; + private static _o: Vector3 = new Vector3(); + private static _d: Vector3 = new Vector3(); + private static _opts: MeshBVHRayOptions = {}; + + /** + * Intersect `ray` (world space) with `geometry` placed by `worldMatrix` + * and append the hits to `out` (closest only unless `options.all`). + * Hits are not sorted across calls; the ones added by one call are. + * @returns number of hits appended + */ + public static intersect(geometry: GeometryBase, worldMatrix: Matrix4, ray: Ray, options: MeshRaycastOptions, out: RaycastHit[]): number { + if (!geometry || !MeshBVH.getAttributeView(geometry, VertexAttributeName.position)) return 0; + + const inv = (MeshRaycast._inv ||= new Matrix4()).copy(worldMatrix).invert(); + const o = Matrix4.transformPoint(inv, ray.origin, MeshRaycast._o); + const d = Matrix4.transformVector(inv, ray.direction, MeshRaycast._d); + const len = d.length; + if (!(len > 0) || !isFinite(len)) return 0; + d.set(d.x / len, d.y / len, d.z / len); + // A world distance s along the unit world direction is s * len along the unit local one. + const near = options.near ?? 0, far = options.far ?? Infinity; + + // A mirroring transform reverses the winding the rasterizer sees. + const mirrored = MeshRaycast._determinant3(worldMatrix) < 0; + let cull = options.cull === true ? 'back' : (options.cull || 'none') as MeshBVHCull; + if (mirrored && cull !== 'none') cull = cull === 'back' ? 'front' : 'back'; + + const opts = MeshRaycast._opts; + opts.near = near * len; + opts.far = far * len; + opts.cull = cull; + + const mode = options.useBVH ?? 'auto'; + const bvh = mode === 'always' || (mode === 'auto' && MeshBVH.has(geometry)) ? MeshBVH.get(geometry) : null; + + let local: MeshBVHHit[]; + if (options.all || options.accept) { + local = bvh ? bvh.raycastAll(o, d, opts) : MeshBVH.raycastGeometryAll(geometry, o, d, opts); + if (options.accept) local = local.filter(h => options.accept(h, h.frontFace !== mirrored)); + if (!options.all && local.length > 1) local.length = 1; + } else { + const h = bvh ? bvh.raycast(o, d, opts) : MeshBVH.raycastGeometry(geometry, o, d, opts); + local = h ? [h] : []; + } + if (local.length === 0) return 0; + + const normals = MeshBVH.getAttributeView(geometry, VertexAttributeName.normal); + const uvs = MeshBVH.getAttributeView(geometry, VertexAttributeName.uv); + const uvs1 = MeshBVH.getAttributeView(geometry, VertexAttributeName.TEXCOORD_1); + const idx = geometry.getAttribute(VertexAttributeName.indices); + const I = idx && idx.data && idx.data.length > 0 ? idx.data as ArrayLike : null; + for (const h of local) { + out.push(MeshRaycast._toWorld(h, worldMatrix, inv, ray, I, normals, uvs, uvs1, mirrored)); + } + return local.length; + } + + /** + * Intersect a renderer's mesh as it is drawn. Skinned and morph-target + * meshes are deformed on the CPU first (see `MeshDeformer`) unless + * `options.deformation` says otherwise; a deformed mesh is always + * queried through a (refit) BVH unless `useBVH` is `'never'`. For + * skinned meshes `localPoint` is the hit expressed in the renderer's + * local space (the deformed surface, not the bind pose). + * @returns number of hits appended + */ + public static intersectRenderer(renderer: MeshRenderer, ray: Ray, options: MeshRaycastOptions, out: RaycastHit[]): number { + const world = renderer.transform.worldMatrix; + const mode = options.deformation ?? 'cpu'; + if (mode !== 'bindPose' && MeshDeformer.isDeformed(renderer)) { + if (mode === 'skip') return 0; + const deformed = MeshDeformer.deform(renderer); + if (deformed) { + const opts: MeshRaycastOptions = { ...options, useBVH: options.useBVH === 'never' ? 'never' : 'always' }; + if (!deformed.worldSpace) return MeshRaycast.intersect(deformed.geometry, world, ray, opts, out); + const first = out.length; + const n = MeshRaycast.intersect(deformed.geometry, MeshRaycast._identity(), ray, opts, out); + const inv = (MeshRaycast._inv2 ||= new Matrix4()).copy(world).invert(); + for (let i = first; i < out.length; i++) Matrix4.transformPoint(inv, out[i].point, out[i].localPoint); + return n; + } + } + return MeshRaycast.intersect(renderer.geometry, world, ray, options, out); + } + + private static _inv2: Matrix4; + private static _ident: Matrix4; + private static _identity(): Matrix4 { + return (MeshRaycast._ident ||= new Matrix4()).identity(); + } + + private static _toWorld(h: MeshBVHHit, world: Matrix4, inv: Matrix4, ray: Ray, I: ArrayLike | null, + normals: MeshAttributeView | null, uvs: MeshAttributeView | null, uvs1: MeshAttributeView | null, mirrored: boolean): RaycastHit { + const k = h.triIndex * 3; + const i0 = I ? I[k] : k, i1 = I ? I[k + 1] : k + 1, i2 = I ? I[k + 2] : k + 2; + const w0 = 1 - h.u - h.v, w1 = h.u, w2 = h.v; + + const point = Matrix4.transformPoint(world, h.point, new Vector3()); + const faceNormal = MeshRaycast.transformNormal(inv, h.faceNormal, new Vector3()); + let normal: Vector3; + if (normals) { + const N = normals.data, s = normals.stride, f = normals.offset; + const a = i0 * s + f, b = i1 * s + f, c = i2 * s + f; + normal = new Vector3( + N[a] * w0 + N[b] * w1 + N[c] * w2, + N[a + 1] * w0 + N[b + 1] * w1 + N[c + 1] * w2, + N[a + 2] * w0 + N[b + 2] * w1 + N[c + 2] * w2, + ); + MeshRaycast.transformNormal(inv, normal, normal); + if (normal.length === 0) normal.copy(faceNormal); + } else { + normal = faceNormal.clone(); + } + + return { + distance: Vector3.distance(ray.origin, point), + point, + localPoint: h.point.clone(), + normal, + faceNormal, + faceIndex: h.triIndex, + barycentric: new Vector3(w0, w1, w2), + frontFace: h.frontFace !== mirrored, + uv: MeshRaycast._lerp2(uvs, i0, i1, i2, w0, w1, w2), + uv1: MeshRaycast._lerp2(uvs1, i0, i1, i2, w0, w1, w2), + subGeometryIndex: h.subGeometryIndex, + object3D: null, + renderer: null, + }; + } + + private static _lerp2(view: MeshAttributeView | null, i0: number, i1: number, i2: number, w0: number, w1: number, w2: number): Vector2 | null { + if (!view) return null; + const D = view.data, s = view.stride, f = view.offset; + const a = i0 * s + f, b = i1 * s + f, c = i2 * s + f; + return new Vector2(D[a] * w0 + D[b] * w1 + D[c] * w2, D[a + 1] * w0 + D[b + 1] * w1 + D[c + 1] * w2); + } + + /** + * Transform a local-space normal to world space with the inverse + * transpose of the local → world matrix (normals stay perpendicular + * under non-uniform scale), then normalize. + * @param invMatrix inverse of the local → world matrix + * @param n local-space normal + * @param out result (may alias `n`) + */ + public static transformNormal(invMatrix: Matrix4, n: Vector3, out: Vector3): Vector3 { + const d = invMatrix.rawData; + const x = n.x, y = n.y, z = n.z; + out.set( + x * d[0] + y * d[1] + z * d[2], + x * d[4] + y * d[5] + z * d[6], + x * d[8] + y * d[9] + z * d[10], + ); + return out.normalize(); + } + + private static _determinant3(m: Matrix4): number { + const d = m.rawData; + return d[0] * (d[5] * d[10] - d[6] * d[9]) - d[4] * (d[1] * d[10] - d[2] * d[9]) + d[8] * (d[1] * d[6] - d[2] * d[5]); + } +} diff --git a/src/io/raycast/RaycastHit.ts b/src/io/raycast/RaycastHit.ts new file mode 100644 index 000000000..f3229fc76 --- /dev/null +++ b/src/io/raycast/RaycastHit.ts @@ -0,0 +1,43 @@ +import { Object3D } from '../../core/entities/Object3D'; +import { Vector2 } from '../../math/Vector2'; +import { Vector3 } from '../../math/Vector3'; +import { MeshRenderer } from '../../components/renderer/MeshRenderer'; + +/** + * One ray/triangle intersection reported by `Raycaster` (and, mapped onto + * `HitInfo`, by `MeshColliderShape`). Every result is a new object owned by + * the caller. + * @group IO + */ +export interface RaycastHit { + /** World-space distance from the ray origin to `point`. */ + distance: number; + /** Hit point in world space. */ + point: Vector3; + /** Hit point in the mesh's local space. */ + localPoint: Vector3; + /** + * World-space surface normal: the barycentric interpolation of the + * vertex normals, or `faceNormal` when the geometry has none. Not + * flipped towards the ray for back-face hits. + */ + normal: Vector3; + /** World-space geometric normal of the hit triangle (from its winding). */ + faceNormal: Vector3; + /** Triangle index into the index buffer (`indices[faceIndex*3 .. +2]`). */ + faceIndex: number; + /** Barycentric weights (w0, w1, w2) of the triangle's three vertices. */ + barycentric: Vector3; + /** Whether the ray hit the triangle's front (counter-clockwise, as rendered) side. */ + frontFace: boolean; + /** Interpolated `uv` (TEXCOORD_0), or null when the geometry has none. */ + uv: Vector2 | null; + /** Interpolated `TEXCOORD_1`, or null when the geometry has none. */ + uv1: Vector2 | null; + /** Sub-geometry of the triangle; the renderer draws it with `materials[subGeometryIndex]`. */ + subGeometryIndex: number; + /** Object that owns the mesh (null for a bare geometry query). */ + object3D: Object3D | null; + /** Renderer that was hit (null for a bare geometry query). */ + renderer: MeshRenderer | null; +} diff --git a/src/io/raycast/Raycaster.ts b/src/io/raycast/Raycaster.ts new file mode 100644 index 000000000..3ee492b42 --- /dev/null +++ b/src/io/raycast/Raycaster.ts @@ -0,0 +1,227 @@ +import { Camera3D } from '../../core/Camera3D'; +import { Object3D } from '../../core/entities/Object3D'; +import { MeshBVHCull, MeshBVHHit } from '../../core/tree/bvh/MeshBVH'; +import { InstanceDrawComponent } from '../../components/renderer/InstanceDrawComponent'; +import { MeshRenderer } from '../../components/renderer/MeshRenderer'; +import { VisibleLayer } from '../../gfx/renderJob/config/VisibleLayer'; +import { Material } from '../../materials/Material'; +import { Ray } from '../../math/Ray'; +import { Vector3 } from '../../math/Vector3'; +import { CameraUtil } from '../../util/CameraUtil'; +import { MeshRaycast, MeshRaycastOptions, RaycastBVHMode } from './MeshRaycast'; +import { RaycastDeformation } from './MeshDeformer'; +import { RaycastHit } from './RaycastHit'; + +/** + * Which faces a `Raycaster` can hit: + * - `material`: whatever each sub-mesh's material renders (its `cullMode`) + * - `front` / `back`: only front / only back faces + * - `double`: both + * @group IO + */ +export type RaycastSide = 'material' | 'front' | 'back' | 'double'; + +/** + * CPU ray picking against mesh triangles, build a ray (from the camera or by hand), + * then intersect objects and get sorted hits with point, distance, + * normals, face index, barycentric coordinates and UVs. Unlike `PickFire`, + * no `ColliderComponent` is needed: any `MeshRenderer` in the given hierarchy is tested. + * + * Geometry with a `MeshBVH` (see `MeshBVH.build`) is tested through the + * tree; other geometry is scanned triangle by triangle unless `useBVH` is + * `'always'`. + * + * ```ts + * const raycaster = new Raycaster(); + * raycaster.setFromCamera(view.camera, input.mouseX, input.mouseY); + * const hits = raycaster.intersectObject(view.scene); + * if (hits.length) console.log(hits[0].object3D.name, hits[0].point, hits[0].uv); + * ``` + * + * Skinned and morph-target meshes are deformed on the CPU as the vertex + * shader does (see `deformation` and `MeshDeformer`). Renderers + * batched by an `InstanceDrawComponent` are tested even though the batch + * disables them individually. + * @group IO + */ +export class Raycaster { + /** The world-space ray (direction normalized). */ + public ray: Ray = new Ray(); + /** Hits closer than this are ignored. */ + public near: number = 0; + /** Hits farther than this are ignored. */ + public far: number = Infinity; + /** Only renderers whose `visibleLayer` shares a bit with this mask are tested. */ + public layerMask: number = VisibleLayer.All; + /** Which faces can be hit. Default `'material'`. */ + public side: RaycastSide = 'material'; + /** Report only the closest hit per mesh instead of every crossing. */ + public firstHitOnly: boolean = false; + /** When to use a geometry's `MeshBVH`. Default `'auto'`. */ + public useBVH: RaycastBVHMode = 'auto'; + /** + * Skinned / morph-target meshes: `'cpu'` (default) deforms them on the + * CPU like the vertex shader so hits match what is drawn; `'bindPose'` + * tests the undeformed geometry; `'skip'` ignores them. + */ + public deformation: RaycastDeformation = 'cpu'; + /** Optional per-renderer filter; return false to skip a renderer. */ + public filter: ((renderer: MeshRenderer) => boolean) | null = null; + + private static _a: Vector3 = new Vector3(); + private static _b: Vector3 = new Vector3(); + + /** + * @param origin optional world-space ray origin + * @param direction optional world-space ray direction (normalized here) + */ + constructor(origin?: Vector3, direction?: Vector3) { + if (origin && direction) this.set(origin, direction); + } + + /** Set the ray from an origin and a direction (normalized here). */ + public set(origin: Vector3, direction: Vector3): this { + this.ray.origin.copy(origin); + this.ray.direction = direction; + return this; + } + + /** + * Set the ray through a canvas pixel (CSS pixels relative to the canvas' + * top-left, as in `InputSystem.mouseX/Y` and `PointerEvent3D.mouseX/Y`). + */ + public setFromCamera(camera: Camera3D, screenX: number, screenY: number): this { + const r = camera.screenPointToRay(screenX, screenY); + this.ray.origin.copy(r.origin); + this.ray.direction = r.direction; + return this; + } + + /** Set the ray through a point in normalized device coordinates (x, y in [-1, 1], y up). */ + public setFromCameraNDC(camera: Camera3D, ndcX: number, ndcY: number): this { + const a = CameraUtil.UnProjectionNDC(ndcX, ndcY, 0.01, camera, Raycaster._a); + const b = CameraUtil.UnProjectionNDC(ndcX, ndcY, 1.0, camera, Raycaster._b); + this.ray.origin.copy(a); + this.ray.direction = new Vector3(b.x - a.x, b.y - a.y, b.z - a.z); + return this; + } + + /** + * Intersect an object (and, if `recursive`, its descendants). Hits are + * appended to `out`, which is then sorted by distance. + */ + public intersectObject(object: Object3D, recursive: boolean = true, out: RaycastHit[] = []): RaycastHit[] { + this._collect(object, recursive, renderer => { this._intersectRenderer(renderer, this.far, !this.firstHitOnly, out); }); + out.sort((x, y) => x.distance - y.distance); + return out; + } + + /** `intersectObject` over several roots; `out` is sorted by distance. */ + public intersectObjects(objects: Object3D[], recursive: boolean = true, out: RaycastHit[] = []): RaycastHit[] { + for (const object of objects) { + this._collect(object, recursive, renderer => { this._intersectRenderer(renderer, this.far, !this.firstHitOnly, out); }); + } + out.sort((x, y) => x.distance - y.distance); + return out; + } + + /** + * Closest hit over one or more roots, or null. Cheaper than + * `intersectObjects(...)[0]`: each mesh is only searched up to the best + * distance found so far. + */ + public intersectFirst(objects: Object3D | Object3D[], recursive: boolean = true): RaycastHit | null { + const roots = Array.isArray(objects) ? objects : [objects]; + const tmp: RaycastHit[] = []; + let best: RaycastHit = null; + for (const object of roots) { + this._collect(object, recursive, renderer => { + tmp.length = 0; + this._intersectRenderer(renderer, best ? best.distance : this.far, false, tmp); + if (tmp.length && (!best || tmp[0].distance < best.distance)) best = tmp[0]; + }); + } + return best; + } + + private _collect(object: Object3D, recursive: boolean, visit: (renderer: MeshRenderer) => void): void { + // Renderers batched by an InstanceDrawComponent are disabled + // individually but still drawn, so they stay pickable. + let instanced = false; + for (let p = object.transform.parent?.object3D; p && !instanced; p = p.transform.parent?.object3D) instanced = Raycaster._batches(p); + const walk = (obj: Object3D, inBatch: boolean) => { + // Detached objects report enable=false; only honour it inside a scene. + if (obj.transform.scene3D && !obj.transform.enable) return; + inBatch = inBatch || Raycaster._batches(obj); + obj.components.forEach(c => { + if (!(c instanceof MeshRenderer)) return; + if ((!c.enable && !inBatch) || !c.geometry) return; + if ((c.visibleLayer & this.layerMask) === 0) return; + if (this.filter && !this.filter(c)) return; + visit(c); + }); + if (!recursive) return; + for (const child of obj.entityChildren) { + if (child instanceof Object3D) walk(child, inBatch); + } + }; + walk(object, instanced); + } + + private static _batches(obj: Object3D): boolean { + const c = obj.getComponent(InstanceDrawComponent); + return !!c && c.enable; + } + + private _intersectRenderer(renderer: MeshRenderer, far: number, all: boolean, out: RaycastHit[]): void { + const opts: MeshRaycastOptions = { near: this.near, far, useBVH: this.useBVH, all, deformation: this.deformation }; + const subs = Math.max(1, renderer.geometry.subGeometries.length); + const materials = renderer.materials || []; + const materialOf = (sub: number): Material => materials[sub] || materials[0] || null; + + // Work out whether every sub-mesh can share one cull mode. + let uniform: MeshBVHCull | null = null, mixed = false; + for (let i = 0; i < subs; i++) { + const m = materialOf(i); + if (!Raycaster._drawsTriangles(m)) { mixed = true; break; } + const c = this._cullFor(m); + if (uniform === null) uniform = c; + else if (uniform !== c) { mixed = true; break; } + } + if (!mixed) { + opts.cull = uniform ?? 'none'; + } else { + opts.cull = 'none'; + opts.accept = (h: MeshBVHHit, frontFace: boolean) => { + const m = materialOf(h.subGeometryIndex); + if (!Raycaster._drawsTriangles(m)) return false; + const c = this._cullFor(m); + return c === 'none' || (c === 'back' ? frontFace : !frontFace); + }; + } + + const first = out.length; + MeshRaycast.intersectRenderer(renderer, this.ray, opts, out); + for (let i = first; i < out.length; i++) { + out[i].object3D = renderer.object3D; + out[i].renderer = renderer; + } + } + + private _cullFor(material: Material | null): MeshBVHCull { + switch (this.side) { + case 'front': return 'back'; + case 'back': return 'front'; + case 'double': return 'none'; + } + const mode = material ? material.cullMode : 'back'; + return mode === 'front' ? 'front' : mode === 'none' ? 'none' : 'back'; + } + + private static _drawsTriangles(material: Material | null): boolean { + if (!material) return true; + if (material.enable === false) return false; + const topology = material.topology; + return !topology || topology === 'triangle-list'; + } +} diff --git a/src/loader/parser/gltf/GLTFSubParser.ts b/src/loader/parser/gltf/GLTFSubParser.ts index fe5c47034..17ffecf64 100644 --- a/src/loader/parser/gltf/GLTFSubParser.ts +++ b/src/loader/parser/gltf/GLTFSubParser.ts @@ -1,3 +1,4 @@ +import { KHR_materials_variants } from './extends/KHR_materials_variants'; import { Skeleton } from '../../../components/anim/skeletonAnim/Skeleton'; import { Object3D } from '../../../core/entities/Object3D'; import { StringUtil } from '../../../util/StringUtil'; @@ -346,6 +347,7 @@ export class GLTFSubParser { const skins = []; const cameras = []; await this.traverse(rootNode, nodes); + KHR_materials_variants.attach(this.gltf, rootNode); let animas; // apply skins diff --git a/src/loader/parser/gltf/GLTFSubParserConverter.ts b/src/loader/parser/gltf/GLTFSubParserConverter.ts index dca48cf4b..185a1b639 100644 --- a/src/loader/parser/gltf/GLTFSubParserConverter.ts +++ b/src/loader/parser/gltf/GLTFSubParserConverter.ts @@ -16,6 +16,10 @@ import { GLTF_Info, GLTF_Node } from "./GLTFInfo"; import { GLTFSubParser } from "./GLTFSubParser"; import { GLTFType } from "./GLTFType"; import { KHR_materials_clearcoat } from "./extends/KHR_materials_clearcoat"; +import { KHR_materials_sheen } from "./extends/KHR_materials_sheen"; +import { KHR_materials_iridescence } from "./extends/KHR_materials_iridescence"; +import { KHR_materials_specular } from "./extends/KHR_materials_specular"; +import { KHR_materials_variants } from "./extends/KHR_materials_variants"; import { KHR_materials_emissive_strength } from "./extends/KHR_materials_emissive_strength"; import { KHR_materials_ior } from "./extends/KHR_materials_ior"; import { KHR_materials_transmission } from "./extends/KHR_materials_transmission"; @@ -199,127 +203,7 @@ export class GLTFSubParserConverter { // } // } - let md = primitive.material; - if (md.name == undefined) { - md.name = UUID(); - } - let mat: Material; - - let materialKey = `matkey_${md.name}`; - - if (md && this.gltf.resources[materialKey]) { - mat = this.gltf.resources[materialKey]; - } else { - let newMat: Material = (mat = new LitMaterial()); - // let newMat: MaterialBase = (mat = new UnLitMaterial()); - this.gltf.resources[materialKey] = newMat; - // newMat.doubleSided - newMat.name = md.name; - - let gltfMat = md as GLTFMaterial; - if (gltfMat) { - const { baseColorTexture, baseColorFactor, metallicFactor, roughnessFactor, doubleSided, metallicRoughnessTexture, normalTexture, occlusionTexture, emissiveTexture, emissiveFactor, enableBlend, alphaCutoff } = gltfMat; - - let physicMaterial = (newMat = this.applyMaterialExtensions(gltfMat, newMat)); - if (`enableBlend` in gltfMat) { - if (gltfMat[`enableBlend`]) { - let defines = gltfMat.defines; - if (defines?.includes('ALPHA_BLEND')) { - physicMaterial.blendMode = BlendMode.ALPHA; - } else { - physicMaterial.blendMode = BlendMode.NORMAL; - } - physicMaterial.castShadow = false; - } else { - physicMaterial.blendMode = BlendMode.NONE; - } - } - - if (`alphaCutoff` in gltfMat && alphaCutoff > 0 && alphaCutoff < 1) { - physicMaterial.setUniformFloat("alphaCutoff", alphaCutoff); - physicMaterial.blendMode = BlendMode.NORMAL; - physicMaterial.transparent = true; - // physicMaterial.castShadow = false; - // physicMaterial.depthWriteEnabled = false; - } - - if (gltfMat.baseMapOffsetSize) { - physicMaterial.setUniformVector4("baseMapOffsetSize", gltfMat.baseMapOffsetSize); - } - if (gltfMat.normalMapOffsetSize) { - physicMaterial.setUniformVector4("normalMapOffsetSize", gltfMat.normalMapOffsetSize); - } - if (gltfMat.emissiveMapOffsetSize) { - physicMaterial.setUniformVector4("emissiveMapOffsetSize", gltfMat.emissiveMapOffsetSize); - } - if (gltfMat.roughnessMapOffsetSize) { - physicMaterial.setUniformVector4("roughnessMapOffsetSize", gltfMat.roughnessMapOffsetSize); - } - if (gltfMat.metallicMapOffsetSize) { - physicMaterial.setUniformVector4("metallicMapOffsetSize", gltfMat.metallicMapOffsetSize); - } - if (gltfMat.aoMapOffsetSize) { - physicMaterial.setUniformVector4("aoMapOffsetSize", gltfMat.aoMapOffsetSize); - } - - - physicMaterial.setUniformColor("baseColor", new Color(baseColorFactor[0], baseColorFactor[1], baseColorFactor[2], baseColorFactor[3])); - physicMaterial.setUniformFloat("roughness", roughnessFactor); - physicMaterial.setUniformFloat("metallic", metallicFactor); - physicMaterial.setUniformFloat("ao", 1); - physicMaterial.doubleSide = doubleSided; - - if (baseColorTexture) { - physicMaterial.setTexture("baseMap", baseColorTexture); - // Only flip USE_SRGB_ALBEDO when the underlying - // GPU texture format is `rgba8unorm-srgb` (set - // by the GLB embedded path in - // GLTFSubParser.parseTexture). The external- - // .gltf URL path still preloads via - // FileLoader.loadAsyncBitmapTexture without a - // colorSpace argument → format stays - // `rgba8unorm`, and the shader needs its - // software `gammaToLiner` decode. Mismatching - // here would render the asset double-decoded - // (too dark) or non-decoded (too bright). - if ((baseColorTexture as any).format === 'rgba8unorm-srgb') { - physicMaterial.shader.setDefine("USE_SRGB_ALBEDO", true); - } - } - - if (normalTexture) { - physicMaterial.setTexture("normalMap", normalTexture); - } - - if (metallicRoughnessTexture) { - physicMaterial.setTexture("maskMap", metallicRoughnessTexture); - } - - if (occlusionTexture && (metallicRoughnessTexture != occlusionTexture)) { - // physicMaterial.setTexture("aoMap", occlusionTexture); - // physicMaterial.shader.getDefaultColorShader().setDefine(`USE_AOTEX`, true); - } - - if (emissiveTexture) { - physicMaterial.setTexture("emissiveMap", emissiveTexture); - } - - if (emissiveFactor && (emissiveFactor[0] > 0 || emissiveFactor[1] > 0 || emissiveFactor[2] > 0)) { - if (!physicMaterial.shader.getTexture("emissiveMap")) { - physicMaterial.shader.setTexture("emissiveMap", Engine3D.resFor(this.subParser.ctx).whiteTexture); - } - physicMaterial.shader.setDefine('USE_EMISSIVEMAP', true); - physicMaterial.setUniformColor("emissiveColor", new Color(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], emissiveFactor[3])); - if (physicMaterial.blendMode != BlendMode.NONE) { - physicMaterial.blendMode = BlendMode.ADD; - } - let emissiveIntensity = mat.getUniformFloat('emissiveIntensity') - if (!emissiveIntensity || emissiveIntensity <= 0) { - mat.setUniformFloat('emissiveIntensity', 1.0); - } - } - } - } + let mat: Material = this.getOrCreateMaterial(primitive.material); const { attribArrays, modelName, drawMode } = primitive; let geometry: GeometryBase; @@ -335,7 +219,9 @@ export class GLTFSubParserConverter { indices.push(a + 1); } attribArrays[`indices`] = { - data: new Uint8Array(indices), + // Uint8 silently wrapped every index above 255, scrambling any + // non-indexed mesh with more than 85 triangles. + data: indices.length > 65535 ? new Uint32Array(indices) : new Uint16Array(indices), normalize: false, numComponents: 1, }; @@ -426,6 +312,7 @@ export class GLTFSubParserConverter { // pass instances whose USE_SKELETON is set once // (geometry has joints0) and never mutated again. smr.material = mat.clone(); + KHR_materials_variants.bind(this.gltf, primitive, smr, true, (m) => this.getOrCreateMaterial(m)); // smr.skinJointsName = this.parseSkinJoints(nodeInfo.skin); // smr.skinInverseBindMatrices = nodeInfo.skin.inverseBindMatrices; @@ -475,6 +362,7 @@ export class GLTFSubParserConverter { mc.castGI = true; mc.geometry = geometry; mc.material = mat; + KHR_materials_variants.bind(this.gltf, primitive, mc, false, (m) => this.getOrCreateMaterial(m)); // Reference glTF loaders mark every primitive of a // skin-referencing node as skinned, even when the @@ -714,9 +602,142 @@ export class GLTFSubParserConverter { return geometry; } + /** + * Engine material for a parsed glTF material (`dmaterial`), created on + * first use and cached by material name so every primitive — and every + * KHR_materials_variants mapping — that names the same glTF material + * shares one instance. + */ + private getOrCreateMaterial(md: any): Material { + if (md.name == undefined) { + md.name = UUID(); + } + let mat: Material; + + let materialKey = `matkey_${md.name}`; + + if (md && this.gltf.resources[materialKey]) { + mat = this.gltf.resources[materialKey]; + } else { + let newMat: Material = (mat = new LitMaterial()); + // let newMat: MaterialBase = (mat = new UnLitMaterial()); + this.gltf.resources[materialKey] = newMat; + // newMat.doubleSided + newMat.name = md.name; + + let gltfMat = md as GLTFMaterial; + if (gltfMat) { + const { baseColorTexture, baseColorFactor, metallicFactor, roughnessFactor, doubleSided, metallicRoughnessTexture, normalTexture, occlusionTexture, emissiveTexture, emissiveFactor, enableBlend, alphaCutoff } = gltfMat; + + let physicMaterial = (newMat = this.applyMaterialExtensions(gltfMat, newMat)); + if (`enableBlend` in gltfMat) { + if (gltfMat[`enableBlend`]) { + let defines = gltfMat.defines; + if (defines?.includes('ALPHA_BLEND')) { + physicMaterial.blendMode = BlendMode.ALPHA; + } else { + physicMaterial.blendMode = BlendMode.NORMAL; + } + physicMaterial.castShadow = false; + } else { + physicMaterial.blendMode = BlendMode.NONE; + } + } + + if (`alphaCutoff` in gltfMat && alphaCutoff > 0 && alphaCutoff < 1) { + physicMaterial.setUniformFloat("alphaCutoff", alphaCutoff); + physicMaterial.blendMode = BlendMode.NORMAL; + physicMaterial.transparent = true; + // physicMaterial.castShadow = false; + // physicMaterial.depthWriteEnabled = false; + } + + if (gltfMat.baseMapOffsetSize) { + physicMaterial.setUniformVector4("baseMapOffsetSize", gltfMat.baseMapOffsetSize); + } + if (gltfMat.normalMapOffsetSize) { + physicMaterial.setUniformVector4("normalMapOffsetSize", gltfMat.normalMapOffsetSize); + } + if (gltfMat.emissiveMapOffsetSize) { + physicMaterial.setUniformVector4("emissiveMapOffsetSize", gltfMat.emissiveMapOffsetSize); + } + if (gltfMat.roughnessMapOffsetSize) { + physicMaterial.setUniformVector4("roughnessMapOffsetSize", gltfMat.roughnessMapOffsetSize); + } + if (gltfMat.metallicMapOffsetSize) { + physicMaterial.setUniformVector4("metallicMapOffsetSize", gltfMat.metallicMapOffsetSize); + } + if (gltfMat.aoMapOffsetSize) { + physicMaterial.setUniformVector4("aoMapOffsetSize", gltfMat.aoMapOffsetSize); + } + + + physicMaterial.setUniformColor("baseColor", new Color(baseColorFactor[0], baseColorFactor[1], baseColorFactor[2], baseColorFactor[3])); + physicMaterial.setUniformFloat("roughness", roughnessFactor); + physicMaterial.setUniformFloat("metallic", metallicFactor); + physicMaterial.setUniformFloat("ao", 1); + physicMaterial.doubleSide = doubleSided; + + if (baseColorTexture) { + physicMaterial.setTexture("baseMap", baseColorTexture); + // Only flip USE_SRGB_ALBEDO when the underlying + // GPU texture format is `rgba8unorm-srgb` (set + // by the GLB embedded path in + // GLTFSubParser.parseTexture). The external- + // .gltf URL path still preloads via + // FileLoader.loadAsyncBitmapTexture without a + // colorSpace argument → format stays + // `rgba8unorm`, and the shader needs its + // software `gammaToLiner` decode. Mismatching + // here would render the asset double-decoded + // (too dark) or non-decoded (too bright). + if ((baseColorTexture as any).format === 'rgba8unorm-srgb') { + physicMaterial.shader.setDefine("USE_SRGB_ALBEDO", true); + } + } + + if (normalTexture) { + physicMaterial.setTexture("normalMap", normalTexture); + } + + if (metallicRoughnessTexture) { + physicMaterial.setTexture("maskMap", metallicRoughnessTexture); + } + + if (occlusionTexture && (metallicRoughnessTexture != occlusionTexture)) { + // physicMaterial.setTexture("aoMap", occlusionTexture); + // physicMaterial.shader.getDefaultColorShader().setDefine(`USE_AOTEX`, true); + } + + if (emissiveTexture) { + physicMaterial.setTexture("emissiveMap", emissiveTexture); + } + + if (emissiveFactor && (emissiveFactor[0] > 0 || emissiveFactor[1] > 0 || emissiveFactor[2] > 0)) { + if (!physicMaterial.shader.getTexture("emissiveMap")) { + physicMaterial.shader.setTexture("emissiveMap", Engine3D.resFor(this.subParser.ctx).whiteTexture); + } + physicMaterial.shader.setDefine('USE_EMISSIVEMAP', true); + physicMaterial.setUniformColor("emissiveColor", new Color(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], emissiveFactor[3])); + if (physicMaterial.blendMode != BlendMode.NONE) { + physicMaterial.blendMode = BlendMode.ADD; + } + let emissiveIntensity = mat.getUniformFloat('emissiveIntensity') + if (!emissiveIntensity || emissiveIntensity <= 0) { + mat.setUniformFloat('emissiveIntensity', 1.0); + } + } + } + } + return mat; + } + private applyMaterialExtensions(dmaterial: any, mat: Material): Material { if (dmaterial.extensions) { KHR_materials_clearcoat.apply(this.gltf, dmaterial, mat); + KHR_materials_sheen.apply(this.gltf, dmaterial, mat); + KHR_materials_iridescence.apply(this.gltf, dmaterial, mat); + KHR_materials_specular.apply(this.gltf, dmaterial, mat); KHR_materials_unlit.apply(this.gltf, dmaterial, mat); KHR_materials_emissive_strength.apply(this.gltf, dmaterial, mat, this.subParser.ctx); // IOR must come before transmission so the transmission diff --git a/src/loader/parser/gltf/GLTFSubParserMesh.ts b/src/loader/parser/gltf/GLTFSubParserMesh.ts index 172be370e..c2c96cfe1 100644 --- a/src/loader/parser/gltf/GLTFSubParserMesh.ts +++ b/src/loader/parser/gltf/GLTFSubParserMesh.ts @@ -4,6 +4,8 @@ import { GLTFParser } from "./GLTFParser"; import { GLTFSubParser } from "./GLTFSubParser"; import { GLTFType } from "./GLTFType"; import { KHR_draco_mesh_compression } from "./extends/KHR_draco_mesh_compression"; +import { KHR_mesh_quantization } from './extends/KHR_mesh_quantization'; +import { KHR_materials_variants } from './extends/KHR_materials_variants'; /** * @internal @@ -119,6 +121,8 @@ export class GLTFSubParserMesh { attribName = attribute; } + // KHR_mesh_quantization: expand integer positions / normals / UVs to float. + if (KHR_mesh_quantization.isQuantizable(attribute)) KHR_mesh_quantization.dequantize(accessor); dprimitive.attribArrays[attribName] = accessor; } } @@ -135,6 +139,7 @@ export class GLTFSubParserMesh { } const dmaterial = await this.parseMaterial(material); + await KHR_materials_variants.parsePrimitive(primitive, dprimitive, (id) => this.parseMaterial(id)); if (dmaterial) { dprimitive.material = dmaterial; dprimitive.defines = dprimitive.defines.concat(dmaterial.defines); diff --git a/src/loader/parser/gltf/extends/KHR_materials_iridescence.ts b/src/loader/parser/gltf/extends/KHR_materials_iridescence.ts new file mode 100644 index 000000000..1d3cd5bab --- /dev/null +++ b/src/loader/parser/gltf/extends/KHR_materials_iridescence.ts @@ -0,0 +1,27 @@ +// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_iridescence + +import { LitMaterial } from '../../../../materials/LitMaterial'; + +/** + * @internal + * @group Loader + */ +export class KHR_materials_iridescence { + /** + * Applies `iridescenceFactor`, `iridescenceIor` and the film thickness. + * Without a thickness texture the spec says the maximum applies, so + * `iridescenceThicknessMaximum` (default 400 nm) is used. The texture + * variants are not sampled yet. + */ + public static apply(gltf: any, dmaterial: any, tMaterial: any) { + const ext = dmaterial.extensions?.[`KHR_materials_iridescence`]; + if (!ext) return; + const mat = tMaterial as LitMaterial; + dmaterial.iridescenceFactor = typeof ext.iridescenceFactor === 'number' ? ext.iridescenceFactor : 0; + dmaterial.iridescenceIor = typeof ext.iridescenceIor === 'number' ? ext.iridescenceIor : 1.3; + dmaterial.iridescenceThickness = typeof ext.iridescenceThicknessMaximum === 'number' ? ext.iridescenceThicknessMaximum : 400; + mat.iridescenceIOR = dmaterial.iridescenceIor; + mat.iridescenceThickness = dmaterial.iridescenceThickness; + mat.iridescence = dmaterial.iridescenceFactor; + } +} diff --git a/src/loader/parser/gltf/extends/KHR_materials_sheen.ts b/src/loader/parser/gltf/extends/KHR_materials_sheen.ts index 66b7ba384..ac3a641a5 100644 --- a/src/loader/parser/gltf/extends/KHR_materials_sheen.ts +++ b/src/loader/parser/gltf/extends/KHR_materials_sheen.ts @@ -1,8 +1,26 @@ -//https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen +// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen + +import { LitMaterial } from '../../../../materials/LitMaterial'; +import { Color } from '../../../../math/Color'; /** * @internal * @group Loader */ export class KHR_materials_sheen { + /** + * Applies `sheenColorFactor` / `sheenRoughnessFactor`. The texture + * variants (`sheenColorTexture`, `sheenRoughnessTexture`) are not + * sampled yet — the factors alone are used. + */ + public static apply(gltf: any, dmaterial: any, tMaterial: any) { + const ext = dmaterial.extensions?.[`KHR_materials_sheen`]; + if (!ext) return; + const mat = tMaterial as LitMaterial; + const c = ext.sheenColorFactor ?? [0, 0, 0]; + dmaterial.sheenColorFactor = c; + dmaterial.sheenRoughnessFactor = ext.sheenRoughnessFactor ?? 0; + mat.sheenRoughness = dmaterial.sheenRoughnessFactor; + mat.sheenColor = new Color(c[0], c[1], c[2], 1); + } } diff --git a/src/loader/parser/gltf/extends/KHR_materials_specular.ts b/src/loader/parser/gltf/extends/KHR_materials_specular.ts index 3170ba29e..3fb77f563 100644 --- a/src/loader/parser/gltf/extends/KHR_materials_specular.ts +++ b/src/loader/parser/gltf/extends/KHR_materials_specular.ts @@ -1,8 +1,27 @@ -//https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_specular +// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_specular + +import { Material } from '../../../../materials/Material'; +import { Color } from '../../../../math/Color'; /** * @internal * @group Loader */ export class KHR_materials_specular { + /** + * `specularColorFactor` tints the dielectric F0 and `specularFactor` + * scales the specular layer. Both land in the PBR `specularColor` + * uniform (rgb = F0 modulator, a = specular strength). The texture + * variants (`specularTexture`, `specularColorTexture`) are not sampled + * yet — the factors alone are used. + */ + public static apply(gltf: any, dmaterial: any, tMaterial: any) { + const ext = dmaterial.extensions?.[`KHR_materials_specular`]; + if (!ext) return; + const c = Array.isArray(ext.specularColorFactor) ? ext.specularColorFactor : [1, 1, 1]; + const f = typeof ext.specularFactor === 'number' ? ext.specularFactor : 1; + dmaterial.specularColorFactor = c; + dmaterial.specularFactor = f; + (tMaterial as Material).setUniformColor(`specularColor`, new Color(c[0], c[1], c[2], f)); + } } diff --git a/src/loader/parser/gltf/extends/KHR_materials_variants.ts b/src/loader/parser/gltf/extends/KHR_materials_variants.ts index b5563fd15..f74354c31 100644 --- a/src/loader/parser/gltf/extends/KHR_materials_variants.ts +++ b/src/loader/parser/gltf/extends/KHR_materials_variants.ts @@ -1,8 +1,61 @@ -//https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_variants +// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_variants + +import { MaterialVariants } from '../../../../components/renderer/MaterialVariants'; +import { Object3D } from '../../../../core/entities/Object3D'; +import { Material } from '../../../../materials/Material'; /** * @internal * @group Loader */ export class KHR_materials_variants { + /** Variant names declared at the asset root, or [] when the extension is absent. */ + public static variantNames(gltf: any): string[] { + const list = gltf?.extensions?.[`KHR_materials_variants`]?.variants; + return Array.isArray(list) ? list.map((v: any, i: number) => v?.name ?? `variant_${i}`) : []; + } + + /** + * Mesh-parser step: resolve each mapping's material index into a parsed + * glTF material and stash the result on the parsed primitive. + */ + public static async parsePrimitive(primitive: any, dprimitive: any, parseMaterial: (id: number) => Promise): Promise { + const mappings = primitive.extensions?.[`KHR_materials_variants`]?.mappings; + if (!Array.isArray(mappings)) return; + const out: { variants: number[]; material: any }[] = []; + for (const m of mappings) { + if (m.material === undefined || !Array.isArray(m.variants)) continue; + const dmaterial = await parseMaterial(m.material); + if (dmaterial) out.push({ variants: m.variants, material: dmaterial }); + } + if (out.length) dprimitive.variantMappings = out; + } + + /** + * Converter step: remember which renderer takes which engine material + * per variant. `skinned` renderers get their own clone (see the + * USE_SKELETON note in the converter). + */ + public static bind(gltf: any, dprimitive: any, renderer: { material: Material }, skinned: boolean, toMaterial: (dmaterial: any) => Material): void { + const mappings = dprimitive?.variantMappings; + if (!mappings) return; + const byVariant = new Map(); + for (const m of mappings) { + let mat = toMaterial(m.material); + if (skinned) mat = mat.clone(); + for (const v of m.variants) byVariant.set(v, mat); + } + (gltf._variantBindings ||= []).push({ renderer, original: renderer.material, byVariant }); + } + + /** Root step: attach a `MaterialVariants` component when the asset uses the extension. */ + public static attach(gltf: any, root: Object3D): void { + const names = KHR_materials_variants.variantNames(gltf); + const bindings = gltf._variantBindings; + if (!names.length && !bindings?.length) return; + const comp = root.addComponent(MaterialVariants); + comp.variantNames = names; + if (bindings) for (const b of bindings) comp.addBinding(b); + gltf._variantBindings = null; + } } diff --git a/src/loader/parser/gltf/extends/KHR_mesh_quantization.ts b/src/loader/parser/gltf/extends/KHR_mesh_quantization.ts index 9fc43e37f..6e0875ef2 100644 --- a/src/loader/parser/gltf/extends/KHR_mesh_quantization.ts +++ b/src/loader/parser/gltf/extends/KHR_mesh_quantization.ts @@ -1,8 +1,44 @@ -//https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_mesh_quantization +// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_mesh_quantization /** * @internal * @group Loader */ export class KHR_mesh_quantization { + /** Attributes the extension allows to be stored as (normalized) integers. */ + public static isQuantizable(attribute: string): boolean { + return attribute === 'POSITION' || attribute === 'NORMAL' || attribute === 'TANGENT' || attribute.startsWith('TEXCOORD_'); + } + + /** + * Promote an integer vertex attribute to Float32, applying the glTF + * normalization rule when the accessor is flagged `normalized` + * (signed: max(c / MAX, -1), unsigned: c / MAX). The engine's geometry + * and picking code assume float positions / normals / UVs, so + * quantized assets are expanded at load time; the node transform the + * exporter wrote undoes the quantization scale as usual. + * + * Idempotent: a Float32 accessor is returned untouched. + */ + public static dequantize(accessor: { data: any; normalize?: boolean; numComponents?: number }): void { + const src = accessor?.data; + if (!src || src instanceof Float32Array) return; + const dst = new Float32Array(src.length); + if (accessor.normalize) { + let max = 1, signed = false; + if (src instanceof Int8Array) { max = 127; signed = true; } + else if (src instanceof Uint8Array) max = 255; + else if (src instanceof Int16Array) { max = 32767; signed = true; } + else if (src instanceof Uint16Array) max = 65535; + else if (src instanceof Uint32Array) max = 4294967295; + for (let i = 0; i < src.length; i++) { + const v = src[i] / max; + dst[i] = signed && v < -1 ? -1 : v; + } + } else { + for (let i = 0; i < src.length; i++) dst[i] = src[i]; + } + accessor.data = dst; + accessor.normalize = false; + } } diff --git a/src/loader/parser/prefab/mats/shader/StandShader.ts b/src/loader/parser/prefab/mats/shader/StandShader.ts index 2eb660c7b..5f1aa2f24 100644 --- a/src/loader/parser/prefab/mats/shader/StandShader.ts +++ b/src/loader/parser/prefab/mats/shader/StandShader.ts @@ -80,6 +80,10 @@ export class StandShader extends Shader { this.setUniformFloat(`attenuationDistance`, 1.0e20); this.setUniformFloat(`transmissionAlphaMode`, 0.0); this.setUniformColor(`attenuationColor`, new Color(1, 1, 1, 1)); + // KHR_materials_sheen: rgb = sheen color (0 = no sheen), a = sheen roughness. + this.setUniformColor(`sheenColor`, new Color(0, 0, 0, 0)); + // KHR_materials_iridescence: x = factor (0 = off), y = film IOR, z = film thickness (nm), w unused. + this.setUniformVector4(`iridescence`, new Vector4(0, 1.3, 400, 0)); this.setUniformVector4(`baseMapOffsetSize`, new Vector4(0, 0, 1, 1)); this.setUniformVector4(`normalMapOffsetSize`, new Vector4(0, 0, 1, 1)); diff --git a/src/materials/LitMaterial.ts b/src/materials/LitMaterial.ts index ed8766864..9a35c3a9c 100644 --- a/src/materials/LitMaterial.ts +++ b/src/materials/LitMaterial.ts @@ -4,6 +4,7 @@ import { RTResourceMap } from "../gfx/renderJob/frame/RTResourceMap"; import { StandShader } from "../loader/parser/prefab/mats/shader/StandShader"; import { BlendMode } from "./BlendMode"; import { Color } from "../math/Color"; +import { Vector4 } from "../math/Vector4"; import { Engine3D } from "../Engine3D"; import { Material } from "./Material"; @@ -63,6 +64,8 @@ export class LitMaterial extends Material { colorPass.setUniform(`clearcoatColor`, sourceShader.getUniform(`clearcoatColor`)); colorPass.setUniform(`clearcoatWeight`, sourceShader.getUniform(`clearcoatWeight`)); colorPass.setUniform(`clearcoatIor`, sourceShader.getUniform(`clearcoatIor`)); + colorPass.setUniform(`sheenColor`, sourceShader.getUniform(`sheenColor`)); + colorPass.setUniform(`iridescence`, sourceShader.getUniform(`iridescence`)); colorPass.setTexture(`baseMap`, sourceShader.getTexture(`baseMap`)); colorPass.setTexture(`normalMap`, sourceShader.getTexture(`normalMap`)); @@ -131,6 +134,80 @@ export class LitMaterial extends Material { return this.shader.getTexture(`aoMap`); } + /** + * Sheen tint (KHR_materials_sheen), linear RGB. Setting any non-black + * color enables the sheen lobe; black disables it again. The color's + * alpha channel is ignored — use `sheenRoughness`. + */ + public set sheenColor(value: Color) { + const c = this.shader.getUniformColor(`sheenColor`); + const roughness = c ? c.a : 0; + this.shader.setUniformColor(`sheenColor`, new Color(value.r, value.g, value.b, roughness)); + this.shader.setDefine(`USE_SHEEN`, value.r > 0 || value.g > 0 || value.b > 0); + } + + /** Get the sheen tint (alpha carries the sheen roughness). */ + public get sheenColor(): Color { + return this.shader.getUniformColor(`sheenColor`); + } + + /** Sheen roughness, 0 (tight rim) … 1 (broad velvet glow). */ + public set sheenRoughness(value: number) { + const c = this.shader.getUniformColor(`sheenColor`) ?? new Color(0, 0, 0, 0); + this.shader.setUniformColor(`sheenColor`, new Color(c.r, c.g, c.b, Math.min(Math.max(value, 0), 1))); + } + + /** Get the sheen roughness. */ + public get sheenRoughness(): number { + const c = this.shader.getUniformColor(`sheenColor`); + return c ? c.a : 0; + } + + private _iridescenceParams(): Vector4 { + const v = this.shader.getUniformVector4(`iridescence`) as Vector4; + return v ? new Vector4(v.x, v.y, v.z, v.w) : new Vector4(0, 1.3, 400, 0); + } + + /** + * Thin-film iridescence strength (KHR_materials_iridescence), 0…1. + * Any value above 0 enables the effect; 0 disables it. + */ + public set iridescence(value: number) { + const v = this._iridescenceParams(); + v.x = Math.min(Math.max(value, 0), 1); + this.shader.setUniformVector4(`iridescence`, v); + this.shader.setDefine(`USE_IRIDESCENCE`, v.x > 0); + } + + /** Get the iridescence strength. */ + public get iridescence(): number { + return this._iridescenceParams().x; + } + + /** Index of refraction of the thin film (default 1.3). */ + public set iridescenceIOR(value: number) { + const v = this._iridescenceParams(); + v.y = Math.max(value, 1.0); + this.shader.setUniformVector4(`iridescence`, v); + } + + /** Get the thin-film index of refraction. */ + public get iridescenceIOR(): number { + return this._iridescenceParams().y; + } + + /** Thin-film thickness in nanometres (typically 100…1000; default 400). */ + public set iridescenceThickness(value: number) { + const v = this._iridescenceParams(); + v.z = Math.max(value, 0); + this.shader.setUniformVector4(`iridescence`, v); + } + + /** Get the thin-film thickness in nanometres. */ + public get iridescenceThickness(): number { + return this._iridescenceParams().z; + } + /** Set the clearcoat roughness texture and enable the clearcoat shader path. */ public set clearCoatRoughnessMap(texture: Texture) { this.shader.setTexture(`clearCoatRoughnessMap`, texture); diff --git a/src/materials/WaterMaterial.ts b/src/materials/WaterMaterial.ts new file mode 100644 index 000000000..b917dea76 --- /dev/null +++ b/src/materials/WaterMaterial.ts @@ -0,0 +1,304 @@ +import { WATER_MAX_WAVES, WaterShader } from '../assets/shader/materials/WaterShader'; +import { WATER_FFT_PATCHES, WaterFFT } from '../components/renderer/WaterFFT'; +import { ShaderLib } from '../assets/shader/ShaderLib'; +import { Texture } from '../gfx/graphics/webGpu/core/texture/Texture'; +import { RenderShaderPass } from '../gfx/graphics/webGpu/shader/RenderShaderPass'; +import { Shader } from '../gfx/graphics/webGpu/shader/Shader'; +import { GPUCullMode } from '../gfx/graphics/webGpu/WebGPUConst'; +import { PassType } from '../gfx/renderJob/passRenderer/state/PassType'; +import { Color } from '../math/Color'; +import { Vector4 } from '../math/Vector4'; +import { BlendMode } from './BlendMode'; +import { Material } from './Material'; + +export { WATER_MAX_WAVES }; +const WAVE_UNIFORMS = ['waveA', 'waveB', 'waveC', 'waveD', 'waveE', 'waveF', 'waveG', 'waveH']; + +/** + * Surface material of {@link WaterRenderer}: Gerstner-wave displacement, + * refraction of the opaque scene behind, absorption, environment + * reflection and a sun highlight. Drawn by the transmission pass, after + * the opaque scene has been captured into the scene color pyramid. + * @group Material + */ +export class WaterMaterial extends Material { + /** Fade distance, undisturbed height, detail scale, detail strength (WaterShader surface). */ + private _surface = new Vector4(0, 0, 1, 0); + /** Foam intensity, reflection roughness, subsurface intensity, underwater clarity (WaterShader look). */ + private _look = new Vector4(1, 0.02, 1, 0.5); + + constructor() { + super(); + ShaderLib.register('WaterShader', WaterShader); + const shader = new Shader(); + const colorPass = new RenderShaderPass('WaterShader', 'WaterShader'); + colorPass.passType = PassType.COLOR; + colorPass.setShaderEntry('VertMain', 'FragMain'); + const state = colorPass.shaderState; + state.useLight = true; + state.receiveEnv = true; + state.acceptShadow = false; + state.castShadow = false; + state.acceptGI = false; + state.blendMode = BlendMode.NONE; + shader.addRenderPass(colorPass); + this.shader = shader; + // Back faces are the surface seen from below. + this.cullMode = GPUCullMode.none; + + this.absorptionColor = new Color(0.12, 0.62, 0.72, 1); + this.underwaterColor = new Color(0.03, 0.16, 0.2, 1); + this.density = 0.15; + this.refractionStrength = 1; + this.waterDepth = 2; + this.specularPower = 2000; + this.specularIntensity = 2; + this.reflectionIntensity = 1; + this.fresnelClamp = 1; + this.waveTime = 0; + for (let i = 0; i < WATER_MAX_WAVES; i++) this.setWave(i, 0, 0, 0, 0); + this.setRippleTransform([1, 0, 0], [0, 1, 0], [0, 0, 1, 1]); + this.shader.setUniformVector4('surface', this._surface); + this.shader.setUniformVector4('look', this._look); + const [p0, p1, p2] = WATER_FFT_PATCHES; + this.shader.setUniformVector4('fftPatch', new Vector4(p0, p1, p2, 0)); + } + + /** Drawn by the transmission pass so the scene color pyramid already holds the scene behind. */ + public get transmissionFactor(): number { + return 1; + } + + /** @internal Opaque scene color with mips, sampled for refraction. */ + public set sceneColorPyramid(texture: Texture) { + this.shader.setTexture('sceneColorPyramid', texture); + } + public get sceneColorPyramid(): Texture { + return this.shader.getTexture('sceneColorPyramid'); + } + + /** + * @internal Opaque scene linear view depth (SceneLinearDepthPass). With it the water uses + * the real distance to the bottom; without it, {@link waterDepth}. + */ + public set sceneLinearDepth(texture: Texture | null) { + if (texture) { + // r32float: read with textureLoad, not filterable. + texture.textureBindingLayout.sampleType = 'unfilterable-float'; + this.shader.setTexture('sceneLinearDepth', texture); + } + this.shader.setDefine('USE_SCENEDEPTH', !!texture); + } + + /** @internal FFT wave cascades and their foam (WaterFFT), or null without. */ + public set fft(fft: WaterFFT | null) { + if (fft) { + for (let c = 0; c < WATER_FFT_PATCHES.length; c++) { + this.shader.setTexture(`fftDisplacement${c}`, fft.displacement[c]); + this.shader.setTexture(`fftSlope${c}`, fft.slope[c]); + } + this.shader.setTexture('fftFoam', fft.foam); + } + this.shader.setDefine('USE_FFT', !!fft); + } + + /** Tileable foam (r) drawn where whitecaps form; null falls back to plain noise patches. */ + public set foamTexture(texture: Texture | null) { + if (texture) this.shader.setTexture('foamTexture', texture); + this.shader.setDefine('USE_FOAM_TEXTURE', !!texture); + } + public get foamTexture(): Texture | null { + return this.shader.getTexture('foamTexture') ?? null; + } + + /** @internal Typical crest height of the FFT waves, for the crests' scattering. Set by WaterRenderer. */ + public set fftCrest(value: number) { + const v = this.shader.getUniformVector4('fftPatch'); + this.shader.setUniformVector4('fftPatch', new Vector4(v.x, v.y, v.z, value)); + } + + /** + * @internal Interactive ripple heights (WaterRipples, r = height), or null without ripples. + */ + public set rippleMap(texture: Texture | null) { + if (texture) this.shader.setTexture('rippleMap', texture); + this.shader.setDefine('USE_RIPPLES', !!texture); + } + + /** + * @internal Maps world xz to the ripple grid: local x = dot(toLocalX.xy, xz) + toLocalX.z, + * likewise z; bounds are the local xz the grid covers (min x, min z, max x, max z). + */ + public setRippleTransform(toLocalX: number[], toLocalZ: number[], bounds: number[]): void { + this.shader.setUniformVector4('rippleX', new Vector4(toLocalX[0], toLocalX[1], toLocalX[2], 0)); + this.shader.setUniformVector4('rippleZ', new Vector4(toLocalZ[0], toLocalZ[1], toLocalZ[2], 0)); + this.shader.setUniformVector4('rippleBounds', new Vector4(bounds[0], bounds[1], bounds[2], bounds[3])); + } + + /** + * Sets one Gerstner wave. A wavelength of 0 disables it. + * @param index 0 to {@link WATER_MAX_WAVES} - 1 + * @param dirX direction of travel, x + * @param dirZ direction of travel, z + * @param steepness 0 to 1; the sum over all waves should stay below 1 to avoid loops + * @param wavelength crest-to-crest distance in world units + */ + public setWave(index: number, dirX: number, dirZ: number, steepness: number, wavelength: number): void { + if (index < 0 || index >= WATER_MAX_WAVES) return; + this.shader.setUniformVector4(WAVE_UNIFORMS[index], new Vector4(dirX, dirZ, steepness, wavelength)); + } + + /** + * @internal Distance from the camera, in wavelengths, at which a wave has faded out + * (from half of it on); 0 keeps every wave at any distance. Set through WaterRenderer. + */ + public get waveFadeDistance(): number { + return this._surface.x; + } + public set waveFadeDistance(value: number) { + this._surface.x = value; + this.shader.setUniformVector4('surface', this._surface); + } + + /** @internal World height of the undisturbed surface, for the crests' scattering. Set by WaterRenderer. */ + public set baseHeight(value: number) { + this._surface.y = value; + this.shader.setUniformVector4('surface', this._surface); + } + + /** @internal Base wavelength of the fine ripples. Set through WaterRenderer.detailScale. */ + public set detailScale(value: number) { + this._surface.z = value; + this.shader.setUniformVector4('surface', this._surface); + } + + /** @internal How much the fine ripples bend the surface normal. Set through WaterRenderer.detailStrength. */ + public set detailStrength(value: number) { + this._surface.w = value; + this.shader.setUniformVector4('surface', this._surface); + } + + /** Whitecaps where the waves pinch into sharp crests (0 to 1); calm water has none. */ + public get foamIntensity(): number { + return this._look.x; + } + public set foamIntensity(value: number) { + this._look.x = value; + this.shader.setUniformVector4('look', this._look); + } + + /** + * Roughness of the surface below the scale of the fine ripples (0 to 1), + * blurring the reflection; ripples too fine for a pixel add to it. + */ + public get reflectionRoughness(): number { + return this._look.y; + } + public set reflectionRoughness(value: number) { + this._look.y = value; + this.shader.setUniformVector4('look', this._look); + } + + /** Sunlight glowing through the crests of tall waves when looking toward the sun. */ + public get subsurfaceIntensity(): number { + return this._look.z; + } + public set subsurfaceIntensity(value: number) { + this._look.z = value; + this.shader.setUniformVector4('look', this._look); + } + + /** + * How clearly the world above shows through the surface from underwater + * (0 to 1). 0 is physical: Snell's window spans 48.6 degrees from straight + * up and the rest of the surface mirrors the water below; higher widens + * the window and weakens the mirror. + */ + public get underwaterClarity(): number { + return this._look.w; + } + public set underwaterClarity(value: number) { + this._look.w = value; + this.shader.setUniformVector4('look', this._look); + } + + /** Light passing through the water is tinted toward this color. */ + public get absorptionColor(): Color { + return this.shader.getUniformColor('absorptionColor'); + } + public set absorptionColor(value: Color) { + this.shader.setUniformColor('absorptionColor', value); + } + + /** Color of deep water: anything seen through the water, from above or below, fades into it with distance. */ + public get underwaterColor(): Color { + return this.shader.getUniformColor('underwaterColor'); + } + public set underwaterColor(value: Color) { + this.shader.setUniformColor('underwaterColor', value); + } + + /** Absorption per world unit of path through the water. */ + public get density(): number { + return this.shader.getUniformFloat('density'); + } + public set density(value: number) { + this.shader.setUniformFloat('density', value); + } + + /** Scale of the wave distortion seen through the surface: 1 is physical, 0 disables it. */ + public get refractionStrength(): number { + return this.shader.getUniformFloat('refractionStrength'); + } + public set refractionStrength(value: number) { + this.shader.setUniformFloat('refractionStrength', value); + } + + /** Depth of the bottom below the surface, in world units; used when setting.render.water is off (no scene depth). */ + public get waterDepth(): number { + return this.shader.getUniformFloat('waterDepth'); + } + public set waterDepth(value: number) { + this.shader.setUniformFloat('waterDepth', value); + } + + /** Sun highlight exponent; higher is smaller and sharper. */ + public get specularPower(): number { + return this.shader.getUniformFloat('specularPower'); + } + public set specularPower(value: number) { + this.shader.setUniformFloat('specularPower', value); + } + + /** Sun highlight strength. */ + public get specularIntensity(): number { + return this.shader.getUniformFloat('specularIntensity'); + } + public set specularIntensity(value: number) { + this.shader.setUniformFloat('specularIntensity', value); + } + + /** Environment reflection strength. */ + public get reflectionIntensity(): number { + return this.shader.getUniformFloat('reflectionIntensity'); + } + public set reflectionIntensity(value: number) { + this.shader.setUniformFloat('reflectionIntensity', value); + } + + /** Upper bound of the fresnel reflection weight (0 to 1). */ + public get fresnelClamp(): number { + return this.shader.getUniformFloat('fresnelClamp'); + } + public set fresnelClamp(value: number) { + this.shader.setUniformFloat('fresnelClamp', value); + } + + /** @internal Wave phase time in seconds, driven by WaterRenderer. */ + public get waveTime(): number { + return this.shader.getUniformFloat('waveTime'); + } + public set waveTime(value: number) { + this.shader.setUniformFloat('waveTime', value); + } +} diff --git a/src/math/Box2.ts b/src/math/Box2.ts new file mode 100644 index 000000000..20d180749 --- /dev/null +++ b/src/math/Box2.ts @@ -0,0 +1,136 @@ +import { Vector2 } from './Vector2'; + +/** + * Axis-aligned 2D box (min / max corners). Mirrors three.js `Box2`: screen + * rectangles, UV bounds, 2D culling, marquee selection. + * @group Math + */ +export class Box2 { + public min: Vector2; + public max: Vector2; + + /** Defaults to an empty box (min = +∞, max = −∞) so the first `expandByPoint` defines it. */ + constructor(min?: Vector2, max?: Vector2) { + this.min = min ?? new Vector2(Infinity, Infinity); + this.max = max ?? new Vector2(-Infinity, -Infinity); + } + + public set(min: Vector2, max: Vector2): this { + this.min.copy(min); + this.max.copy(max); + return this; + } + + public setFromPoints(points: Vector2[]): this { + this.makeEmpty(); + for (const p of points) this.expandByPoint(p); + return this; + } + + public setFromCenterAndSize(center: Vector2, size: Vector2): this { + const hx = size.x * 0.5, hy = size.y * 0.5; + this.min.set(center.x - hx, center.y - hy); + this.max.set(center.x + hx, center.y + hy); + return this; + } + + public clone(): Box2 { + return new Box2(this.min.clone(), this.max.clone()); + } + + public copy(box: Box2): this { + return this.set(box.min, box.max); + } + + public makeEmpty(): this { + this.min.set(Infinity, Infinity); + this.max.set(-Infinity, -Infinity); + return this; + } + + /** True when the box encloses no points (max < min on either axis). */ + public isEmpty(): boolean { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + + public getCenter(out: Vector2 = new Vector2()): Vector2 { + return this.isEmpty() ? out.set(0, 0) : out.set((this.min.x + this.max.x) * 0.5, (this.min.y + this.max.y) * 0.5); + } + + public getSize(out: Vector2 = new Vector2()): Vector2 { + return this.isEmpty() ? out.set(0, 0) : out.set(this.max.x - this.min.x, this.max.y - this.min.y); + } + + public expandByPoint(p: Vector2): this { + if (p.x < this.min.x) this.min.x = p.x; + if (p.y < this.min.y) this.min.y = p.y; + if (p.x > this.max.x) this.max.x = p.x; + if (p.y > this.max.y) this.max.y = p.y; + return this; + } + + public expandByVector(v: Vector2): this { + this.min.set(this.min.x - v.x, this.min.y - v.y); + this.max.set(this.max.x + v.x, this.max.y + v.y); + return this; + } + + public expandByScalar(s: number): this { + this.min.set(this.min.x - s, this.min.y - s); + this.max.set(this.max.x + s, this.max.y + s); + return this; + } + + public containsPoint(p: Vector2): boolean { + return p.x >= this.min.x && p.x <= this.max.x && p.y >= this.min.y && p.y <= this.max.y; + } + + public containsBox(box: Box2): boolean { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + + /** Overlap test; touching edges count as intersecting. */ + public intersectsBox(box: Box2): boolean { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + + /** Position of `p` inside the box as 0..1 on each axis. */ + public getParameter(p: Vector2, out: Vector2 = new Vector2()): Vector2 { + return out.set((p.x - this.min.x) / (this.max.x - this.min.x), (p.y - this.min.y) / (this.max.y - this.min.y)); + } + + public clampPoint(p: Vector2, out: Vector2 = new Vector2()): Vector2 { + return out.set(Math.max(this.min.x, Math.min(this.max.x, p.x)), Math.max(this.min.y, Math.min(this.max.y, p.y))); + } + + /** 0 when `p` is inside or on the box. */ + public distanceToPoint(p: Vector2): number { + const dx = Math.max(this.min.x - p.x, 0, p.x - this.max.x); + const dy = Math.max(this.min.y - p.y, 0, p.y - this.max.y); + return Math.sqrt(dx * dx + dy * dy); + } + + /** Shrink to the overlap with `box`; becomes empty if they do not overlap. */ + public intersect(box: Box2): this { + this.min.set(Math.max(this.min.x, box.min.x), Math.max(this.min.y, box.min.y)); + this.max.set(Math.min(this.max.x, box.max.x), Math.min(this.max.y, box.max.y)); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + + public union(box: Box2): this { + this.min.set(Math.min(this.min.x, box.min.x), Math.min(this.min.y, box.min.y)); + this.max.set(Math.max(this.max.x, box.max.x), Math.max(this.max.y, box.max.y)); + return this; + } + + public translate(offset: Vector2): this { + this.min.set(this.min.x + offset.x, this.min.y + offset.y); + this.max.set(this.max.x + offset.x, this.max.y + offset.y); + return this; + } + + public equals(box: Box2): boolean { + return box.min.x === this.min.x && box.min.y === this.min.y && box.max.x === this.max.x && box.max.y === this.max.y; + } +} diff --git a/src/math/CatmullRomCurve3.ts b/src/math/CatmullRomCurve3.ts new file mode 100644 index 000000000..57d6ee303 --- /dev/null +++ b/src/math/CatmullRomCurve3.ts @@ -0,0 +1,231 @@ +import { Vector3 } from './Vector3'; + +/** Parameterization of a Catmull-Rom spline. */ +export type CatmullRomType = 'centripetal' | 'chordal' | 'catmullrom'; + +/** + * Smooth 3D spline that passes THROUGH every control point (unlike a Bezier + * path, whose inner handles are off-curve). API and math follow three.js + * `CatmullRomCurve3`: + * + * - `getPoint(t)` — position at curve parameter t ∈ [0,1] (uneven speed). + * - `getPointAt(u)` — position at arc-length fraction u ∈ [0,1] (constant + * speed; this is what camera paths and followers want). + * - `getTangent(t)` / `getTangentAt(u)` — unit direction of travel. + * - `getLength()`, `getPoints(n)`, `getSpacedPoints(n)`. + * + * `'centripetal'` (default) never forms cusps or self-intersections inside a + * segment; `'chordal'` is looser; `'catmullrom'` is the classic uniform + * spline with a `tension` knob (0 = loose … 1 = straight segments). + * @group Math + */ +export class CatmullRomCurve3 { + public points: Vector3[]; + public closed: boolean; + public curveType: CatmullRomType; + public tension: number; + /** Number of samples used for the arc-length table. */ + public arcLengthDivisions: number = 200; + + private _lengths: number[] | null = null; + private _lengthsKey: string = ''; + + constructor(points: Vector3[] = [], closed: boolean = false, curveType: CatmullRomType = 'centripetal', tension: number = 0.5) { + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + + /** Position at curve parameter `t` ∈ [0,1]. */ + public getPoint(t: number, out: Vector3 = new Vector3()): Vector3 { + const points = this.points; + const l = points.length; + if (l === 0) return out.set(0, 0, 0); + if (l === 1) return out.copy(points[0]); + + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + + let p0: Vector3, p3: Vector3; + const tmp = CatmullRomCurve3._tmp; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + // Extrapolate a phantom point before the first one. + p0 = tmp.set(points[0].x * 2 - points[1].x, points[0].y * 2 - points[1].y, points[0].z * 2 - points[1].z); + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + const tmp2 = CatmullRomCurve3._tmp2; + p3 = tmp2.set(points[l - 1].x * 2 - points[l - 2].x, points[l - 1].y * 2 - points[l - 2].y, points[l - 1].z * 2 - points[l - 2].z); + } + + const px = CatmullRomCurve3._px, py = CatmullRomCurve3._py, pz = CatmullRomCurve3._pz; + if (this.curveType === 'centripetal' || this.curveType === 'chordal') { + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow(CatmullRomCurve3._distSq(p0, p1), pow); + let dt1 = Math.pow(CatmullRomCurve3._distSq(p1, p2), pow); + let dt2 = Math.pow(CatmullRomCurve3._distSq(p2, p3), pow); + // Guard against repeated control points. + if (dt1 < 1e-4) dt1 = 1.0; + if (dt0 < 1e-4) dt0 = dt1; + if (dt2 < 1e-4) dt2 = dt1; + px.initNonuniform(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniform(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniform(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + return out.set(px.calc(weight), py.calc(weight), pz.calc(weight)); + } + + /** Position at arc-length fraction `u` ∈ [0,1] (constant speed along the curve). */ + public getPointAt(u: number, out: Vector3 = new Vector3()): Vector3 { + return this.getPoint(this.getUtoTmapping(u), out); + } + + /** `divisions + 1` points at equal steps of the curve parameter. */ + public getPoints(divisions: number = 5): Vector3[] { + const pts: Vector3[] = []; + for (let d = 0; d <= divisions; d++) pts.push(this.getPoint(d / divisions)); + return pts; + } + + /** `divisions + 1` points at equal arc-length steps. */ + public getSpacedPoints(divisions: number = 5): Vector3[] { + const pts: Vector3[] = []; + for (let d = 0; d <= divisions; d++) pts.push(this.getPointAt(d / divisions)); + return pts; + } + + /** Total arc length (approximated with `arcLengthDivisions` chords). */ + public getLength(): number { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + + /** Cumulative chord lengths at `divisions + 1` evenly spaced parameters. Cached until the curve changes. */ + public getLengths(divisions: number = this.arcLengthDivisions): number[] { + const key = this._cacheKey(divisions); + if (this._lengths && this._lengthsKey === key) return this._lengths; + const cache: number[] = [0]; + const last = this.getPoint(0), cur = new Vector3(); + let sum = 0; + for (let p = 1; p <= divisions; p++) { + this.getPoint(p / divisions, cur); + sum += Math.sqrt(CatmullRomCurve3._distSq(cur, last)); + cache.push(sum); + last.copy(cur); + } + this._lengths = cache; + this._lengthsKey = key; + return cache; + } + + /** Force the arc-length table to be rebuilt (call after mutating a control point in place). */ + public updateArcLengths(): void { + this._lengths = null; + } + + /** Map an arc-length fraction `u` to the curve parameter `t`. */ + public getUtoTmapping(u: number, distance?: number): number { + const arcLengths = this.getLengths(); + const il = arcLengths.length; + const target = distance !== undefined ? distance : u * arcLengths[il - 1]; + + // Binary search for the largest index whose length is ≤ target. + let low = 0, high = il - 1; + while (low <= high) { + const i = Math.floor(low + (high - low) / 2); + const comparison = arcLengths[i] - target; + if (comparison < 0) low = i + 1; + else if (comparison > 0) high = i - 1; + else { high = i; break; } + } + const i = Math.max(high, 0); + if (arcLengths[i] === target) return i / (il - 1); + const before = arcLengths[i], after = arcLengths[Math.min(i + 1, il - 1)]; + const segment = after - before; + const frac = segment > 0 ? (target - before) / segment : 0; + return (i + frac) / (il - 1); + } + + /** Unit tangent at curve parameter `t`. */ + public getTangent(t: number, out: Vector3 = new Vector3()): Vector3 { + const delta = 0.0001; + const t1 = Math.max(0, t - delta), t2 = Math.min(1, t + delta); + const a = this.getPoint(t1, CatmullRomCurve3._ta), b = this.getPoint(t2, CatmullRomCurve3._tb); + out.set(b.x - a.x, b.y - a.y, b.z - a.z); + const len = Math.sqrt(out.x * out.x + out.y * out.y + out.z * out.z); + return len > 0 ? out.set(out.x / len, out.y / len, out.z / len) : out; + } + + /** Unit tangent at arc-length fraction `u`. */ + public getTangentAt(u: number, out: Vector3 = new Vector3()): Vector3 { + return this.getTangent(this.getUtoTmapping(u), out); + } + + public clone(): CatmullRomCurve3 { + return new CatmullRomCurve3(this.points.map(p => p.clone()), this.closed, this.curveType, this.tension); + } + + private _cacheKey(divisions: number): string { + let k = `${divisions}|${this.closed}|${this.curveType}|${this.tension}|${this.points.length}`; + for (const p of this.points) k += `|${p.x},${p.y},${p.z}`; + return k; + } + + private static _distSq(a: Vector3, b: Vector3): number { + const dx = a.x - b.x, dy = a.y - b.y, dz = a.z - b.z; + return dx * dx + dy * dy + dz * dz; + } + + private static _tmp = new Vector3(); + private static _tmp2 = new Vector3(); + private static _ta = new Vector3(); + private static _tb = new Vector3(); + private static _px = CatmullRomCurve3._poly(); + private static _py = CatmullRomCurve3._poly(); + private static _pz = CatmullRomCurve3._poly(); + + /** Cubic polynomial c0 + c1·t + c2·t² + c3·t³ with Hermite-style initializers. */ + private static _poly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + const init = (x0: number, x1: number, t0: number, t1: number) => { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + }; + return { + initCatmullRom(x0: number, x1: number, x2: number, x3: number, tension: number) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniform(x0: number, x1: number, x2: number, x3: number, dt0: number, dt1: number, dt2: number) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc(t: number) { + const t2 = t * t, t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + }, + }; + } +} diff --git a/src/math/Cylindrical.ts b/src/math/Cylindrical.ts new file mode 100644 index 000000000..46bb02436 --- /dev/null +++ b/src/math/Cylindrical.ts @@ -0,0 +1,54 @@ +import { Vector3 } from './Vector3'; + +/** + * Cylindrical coordinates (radius from the Y axis, azimuth `theta` around +Y + * measured from +Z toward +X, height `y`). Same convention as three.js. + * @group Math + */ +export class Cylindrical { + /** Distance from the Y axis. */ + public radius: number; + /** Azimuth around +Y from +Z, radians. */ + public theta: number; + /** Height along Y. */ + public y: number; + + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + } + + public set(radius: number, theta: number, y: number): this { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + + public copy(other: Cylindrical): this { + return this.set(other.radius, other.theta, other.y); + } + + public clone(): Cylindrical { + return new Cylindrical(this.radius, this.theta, this.y); + } + + public setFromVector3(v: Vector3): this { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + + public setFromCartesianCoords(x: number, y: number, z: number): this { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + + public toVector3(out: Vector3 = new Vector3()): Vector3 { + out.x = this.radius * Math.sin(this.theta); + out.y = this.y; + out.z = this.radius * Math.cos(this.theta); + return out; + } +} diff --git a/src/math/Plane.ts b/src/math/Plane.ts index 0b6eb2a3d..343ddcb2e 100644 --- a/src/math/Plane.ts +++ b/src/math/Plane.ts @@ -69,8 +69,13 @@ export class Plane { */ public intersectsRay(ray: Ray, targetPoint?: Vector3) { targetPoint ||= this._tmpVecA; + var denom = this.normal.dotProduct(ray.direction); + if (denom === 0) { + // ray is parallel to the plane, there is no single hit point + return false; + } Vector3.sub(this.point, ray.origin, targetPoint); - var t = this.normal.dotProduct(targetPoint) / this.normal.dotProduct(ray.direction); + var t = this.normal.dotProduct(targetPoint) / denom; var intersects = t >= 0; if (intersects) { diff --git a/src/math/Spherical.ts b/src/math/Spherical.ts new file mode 100644 index 000000000..a9f097776 --- /dev/null +++ b/src/math/Spherical.ts @@ -0,0 +1,85 @@ +import { clamp } from './MathUtil'; +import { Vector3 } from './Vector3'; + +const EPS = Math.PI / 180 / 100; + +/** + * Spherical coordinates (radius, polar angle `phi` from +Y, azimuth `theta` + * around +Y measured from +Z). Same convention as three.js `Spherical`, and + * what `OrbitController` uses to orbit a target. + * @group Math + */ +export class Spherical { + /** Distance from the origin. */ + public radius: number; + /** Polar angle from the +Y axis, radians, 0..π. */ + public phi: number; + /** Azimuth around +Y measured from +Z toward +X, radians. */ + public theta: number; + /** Scratch vector returned by `getCoords()`. */ + public coords: Vector3; + + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + this.coords = new Vector3(); + } + + public set(radius: number, phi: number, theta: number): this { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + + public copy(other: Spherical): this { + return this.set(other.radius, other.phi, other.theta); + } + + public clone(): Spherical { + return new Spherical(this.radius, this.phi, this.theta); + } + + /** Keep `phi` strictly inside (0, π) so the up vector never degenerates. */ + public makeSafe(): this { + this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi)); + return this; + } + + public setFromVector3(v: Vector3): this { + return this.setCoords(v.x, v.y, v.z); + } + + /** Set from cartesian coordinates. */ + public setCoords(x: number, y: number, z: number): this { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp(y / this.radius, -1, 1)); + } + return this; + } + + /** three.js-compatible alias of `setCoords`. */ + public setFromCartesianCoords(x: number, y: number, z: number): this { + return this.setCoords(x, y, z); + } + + /** Cartesian position, written into the shared `coords` scratch vector. */ + public getCoords(): Vector3 { + return this.toVector3(this.coords); + } + + /** Cartesian position written into `out` (no shared state). */ + public toVector3(out: Vector3 = new Vector3()): Vector3 { + const sinPhiRadius = Math.sin(this.phi) * this.radius; + out.x = sinPhiRadius * Math.sin(this.theta); + out.y = Math.cos(this.phi) * this.radius; + out.z = sinPhiRadius * Math.cos(this.theta); + return out; + } +} diff --git a/src/math/Vector2.ts b/src/math/Vector2.ts index e61232cb7..32c6c1804 100644 --- a/src/math/Vector2.ts +++ b/src/math/Vector2.ts @@ -97,8 +97,8 @@ export class Vector2 { public static lerp(from: Vector2, to: Vector2, t: number) { Vector2.HELP_0.copy(from); Vector2.HELP_1.copy(to); - Vector2.HELP_0.multiplyScalar(t); - Vector2.HELP_1.multiplyScalar(1.0 - t); + Vector2.HELP_0.multiplyScalar(1.0 - t); + Vector2.HELP_1.multiplyScalar(t); return new Vector2(Vector2.HELP_0.x + Vector2.HELP_1.x, Vector2.HELP_0.y + Vector2.HELP_1.y); } diff --git a/src/setting/RenderSetting.ts b/src/setting/RenderSetting.ts index a34e2852e..d6fdb3638 100644 --- a/src/setting/RenderSetting.ts +++ b/src/setting/RenderSetting.ts @@ -3,6 +3,8 @@ import { GlobalFogSetting } from "./post/GlobalFogSetting"; import { GTAOSetting } from "./post/GTAOSetting"; import { OutlineSetting } from "./post/OutlineSetting"; import { SkylineSetting } from "./post/SkylineSetting"; +import { LensSetting } from "./post/LensSetting"; +import { MotionBlurSetting } from "./post/MotionBlurSetting"; import { SSRSetting } from "./post/SSRSetting"; import { TAASetting } from "./post/TAASetting"; import { BloomSetting } from "./post/BloomSetting"; @@ -51,6 +53,19 @@ export type RenderSetting = { * projects its texture onto the opaque scene via stencil shadow * volumes. Default false. */ decals?: boolean; + /** Opt-in water support. When true, ForwardRendererJob adds + * `SceneLinearDepthPass` after the scene color pyramid, so + * `WaterRenderer` surfaces use the real distance to the bottom for + * absorption and refraction, `CausticsPass` before the pyramid for + * sunlight caustics under the surface, and `UnderwaterPass` before + * post-processing for the view with the camera in the water. + * Default false. */ + water?: boolean; + /** Opt-in screen-space fluid rendering. When true, ForwardRendererJob + * inserts `FluidPass` between the opaque/transmission half and the + * sorted transparent half, drawing every active `FluidRenderer`. + * Default false. */ + fluid?: boolean; /** Opt-in 8-bit stencil buffer on the main color pass. * When true, `GBufferFrame` allocates its depth attachment as * `depth24plus-stencil8` instead of the default `depth32float`, @@ -92,6 +107,8 @@ export type RenderSetting = { outline?: OutlineSetting; globalFog?: GlobalFogSetting; skyline?: SkylineSetting; + lens?: LensSetting; + motionBlur?: MotionBlurSetting; godRay?: GodRaySetting; fxaa?: { enable: boolean; diff --git a/src/setting/post/LensSetting.ts b/src/setting/post/LensSetting.ts new file mode 100644 index 000000000..7cd9594f3 --- /dev/null +++ b/src/setting/post/LensSetting.ts @@ -0,0 +1,30 @@ +import { Color } from "../../math/Color"; + +/** + * Lens Setting — vignette, chromatic aberration and film grain, applied by + * `LensPost` in scene-linear HDR (before the tonemap). + * @group Setting + */ +export type LensSetting = { + /** Master switch (set by attaching / detaching `LensPost`). */ + enable: boolean; + /** Vignette strength. 0 = off; 0.4 is a gentle darkening of the corners; 1 is heavy. */ + vignetteIntensity: number; + /** Falloff softness, 0 (hard edge) … 1 (very gradual). */ + vignetteSmoothness: number; + /** 1 = circular vignette regardless of aspect ratio, 0 = follows the screen rectangle. */ + vignetteRoundness: number; + /** Color the corners fade to (usually black). */ + vignetteColor: Color; + /** + * Chromatic aberration strength: red and blue are sampled along the + * radius from the screen center, offset by `c·|c|²·0.4·intensity` + * (c = uv − 0.5), i.e. intensity 1 shifts them by about 5 % of the + * screen at the left/right edge. 0 = off; 0.1 subtle; 1 obvious fringing. + */ + chromaticAberration: number; + /** Film grain strength, 0 = off; 0.1 subtle; 0.5 heavy. Multiplicative, so it scales with exposure. */ + grainIntensity: number; + /** Freeze the grain pattern (useful for screenshots / tests). */ + grainStatic: boolean; +}; diff --git a/src/setting/post/MotionBlurSetting.ts b/src/setting/post/MotionBlurSetting.ts new file mode 100644 index 000000000..c6ce44550 --- /dev/null +++ b/src/setting/post/MotionBlurSetting.ts @@ -0,0 +1,23 @@ +/** + * Motion Blur Setting — camera-motion blur applied by `MotionBlurPost`. + * @group Setting + */ +export type MotionBlurSetting = { + /** Master switch (set by attaching / detaching `MotionBlurPost`). */ + enable: boolean; + /** + * Shutter scale. 1 blurs each pixel along the full distance it travelled + * since the previous frame (a 360° shutter at 60 Hz); 0.5 is the classic + * 180° film shutter; 0 disables the blur. + */ + intensity: number; + /** Samples taken along the velocity vector, 2…32. More = smoother, slower. */ + samples: number; + /** Upper bound on the blur length, in pixels, so a camera cut or teleport does not smear the whole frame. */ + maxBlurPixels: number; + /** + * Normalize the blur length to a 60 Hz frame so it looks the same at + * any frame rate. Turn off to blur by the raw per-frame displacement. + */ + frameRateIndependent: boolean; +}; diff --git a/src/setting/post/TonemapSetting.ts b/src/setting/post/TonemapSetting.ts index 3046f3e5c..63b98ce1d 100644 --- a/src/setting/post/TonemapSetting.ts +++ b/src/setting/post/TonemapSetting.ts @@ -1,3 +1,17 @@ +/** + * Tone curve applied by `TonemapPost`. + * + * - `'None'` passthrough (exposure still applies); output is clamped by the swapchain. + * - `'ACES'` Narkowicz ACES Filmic fit — punchy, saturated highlights drift toward white. Engine default. + * - `'Reinhard'` Extended Reinhard with a white point: `c·(1 + c/w²)/(1 + c)`. Soft, low contrast. + * - `'Uncharted2'` Hable filmic (Uncharted 2) with W = 11.2, exposure bias 2. + * - `'AgX'` Blender 4 / three.js AgX (base look). Desaturates bright saturated colors instead of clipping hues. + * - `'Neutral'` Khronos PBR Neutral — leaves colors below ~0.76 untouched; meant for product / e-commerce rendering where base colors must match the authored sRGB values. + * + * @group Setting + */ +export type TonemapMode = 'None' | 'ACES' | 'Reinhard' | 'Uncharted2' | 'AgX' | 'Neutral'; + /** * Tonemap Setting — final HDR→LDR curve applied after every other * post-effect, just before the swapchain receives the frame. Defaults @@ -13,8 +27,9 @@ export type TonemapSetting = { /** Linear scale multiplied onto the HDR color before the curve. * 1.0 is the neutral default (no exposure compensation). */ exposure: number; - /** Curve selector. 'ACES' applies the Filmic Narkowicz fit; - * 'None' is straight passthrough (same effect as enable=false - * but keeps exposure scaling). */ - mode: 'ACES' | 'None'; + /** Curve selector, see {@link TonemapMode}. */ + mode: TonemapMode; + /** Scene-linear value that maps to pure white in `'Reinhard'` mode. + * Ignored by the other curves. Default 4. */ + whitePoint?: number; }; diff --git a/src/textures/BitmapTexture2D.ts b/src/textures/BitmapTexture2D.ts index 66f541d4e..ebb309f7c 100644 --- a/src/textures/BitmapTexture2D.ts +++ b/src/textures/BitmapTexture2D.ts @@ -118,21 +118,15 @@ export class BitmapTexture2D extends Texture { } this.name = StringUtil.getURLName(url); if (url.indexOf(';base64') != -1) { - const img = document.createElement('img'); + // Decode through a Blob + createImageBitmap, the same path every + // other texture takes. The previous `.decode()` on a detached + // element is deferred by Chrome while the document is hidden, so + // loading a base64 texture in a background tab (or an iframe of + // one) never resolved and whatever awaited it hung forever. let start = url.indexOf('data:image'); let uri = url.substring(start, url.length); - img.src = uri; - await img.decode(); - img.width = Math.max(img.width, 32); - img.height = Math.max(img.height, 32); - const imageBitmap = await createImageBitmap(img, { - resizeWidth: img.width, - resizeHeight: img.height, - imageOrientation: this.flipY ? "flipY" : "from-image", - premultiplyAlpha: 'none' - }); - this.format = this._ldrFormat; - this.generate(imageBitmap); + const blob = await (await fetch(uri)).blob(); + await this.loadFromBlob(blob); } else { return new Promise((succ, fial) => { fetch(url, { diff --git a/src/util/CameraUtil.ts b/src/util/CameraUtil.ts index 6a4c5a7e7..6aed0bcfb 100644 --- a/src/util/CameraUtil.ts +++ b/src/util/CameraUtil.ts @@ -50,20 +50,31 @@ export class CameraUtil { * @returns */ public static UnProjection(sX: number, sY: number, sZ: number = 1, camera?: Camera3D) { - let mouse = new Vector3(sX, sY, 0); - let sc = 1; - let ina: Vector3 = Vector3.HELP_0; - + // sX/sY are canvas-relative (InputSystem.mouseX/Y already subtract + // the canvas rect), matching Projection(); don't subtract the canvas + // offset a second time. let ctx = ctxOf(camera); - let ox = ctx.canvas.offsetLeft; - let oy = ctx.canvas.offsetTop; let w = ctx.canvas.clientWidth; let h = ctx.canvas.clientHeight; - ina.x = (((mouse.x - ox) * sc) / w - 0.5) * 2; - ina.y = -(((mouse.y - oy) * sc) / h - 0.5) * 2; + return CameraUtil.UnProjectionNDC((sX / w - 0.5) * 2, -(sY / h - 0.5) * 2, sZ, camera); + } + + /** + * Unproject a normalized-device-coordinate point (x, y in [-1, 1], y up) + * at depth `sZ` to world space. + * @param ndcX NDC x + * @param ndcY NDC y + * @param sZ NDC depth + * @param camera camera to unproject through + * @param target optional output + */ + public static UnProjectionNDC(ndcX: number, ndcY: number, sZ: number, camera: Camera3D, target?: Vector3) { + let ina: Vector3 = Vector3.HELP_0; + ina.x = ndcX; + ina.y = ndcY; ina.z = sZ; - let outP = new Vector3(0, 0, 0); + let outP = target || new Vector3(0, 0, 0); let projectWorld = Matrix4.helpMatrix2; projectWorld.copy(camera.projectionMatrix); projectWorld.invert(); diff --git a/src/util/IridescenceUtil.ts b/src/util/IridescenceUtil.ts new file mode 100644 index 000000000..e25266248 --- /dev/null +++ b/src/util/IridescenceUtil.ts @@ -0,0 +1,88 @@ +/** + * CPU mirror of `Iridescence_frag` (thin-film interference, Belcour & Barla + * 2017). Keep in sync with the WGSL. Useful for previews, LUT baking and + * GPU-vs-CPU validation. + * @group Util + */ +export class IridescenceUtil { + private static _schlick(f0: number, cosTheta: number): number { + const x = Math.min(Math.max(1 - cosTheta, 0), 1); + return f0 + (1 - f0) * x * x * x * x * x; + } + + private static _sensitivity(OPD: number, shift: number[]): number[] { + const TWO_PI = 6.28318530718; + const phase = TWO_PI * OPD * 1.0e-9; + const val = [5.4856e-13, 4.4201e-13, 5.2481e-13]; + const pos = [1.6810e+06, 1.7953e+06, 2.2084e+06]; + const vr = [4.3278e+09, 9.3046e+09, 6.6121e+09]; + const xyz = [0, 1, 2].map(i => val[i] * Math.sqrt(TWO_PI * vr[i]) * Math.cos(pos[i] * phase + shift[i]) * Math.exp(-phase * phase * vr[i])); + xyz[0] += 9.7470e-14 * Math.sqrt(TWO_PI * 4.5282e+09) * Math.cos(2.2399e+06 * phase + shift[0]) * Math.exp(-4.5282e+09 * phase * phase); + for (let i = 0; i < 3; i++) xyz[i] /= 1.0685e-7; + // Column-major XYZ → Rec.709 + const m = [3.2404542, -0.9692660, 0.0556434, -1.5371385, 1.8760108, -0.2040259, -0.4985314, 0.0415560, 1.0572252]; + return [ + m[0] * xyz[0] + m[3] * xyz[1] + m[6] * xyz[2], + m[1] * xyz[0] + m[4] * xyz[1] + m[7] * xyz[2], + m[2] * xyz[0] + m[5] * xyz[1] + m[8] * xyz[2], + ]; + } + + /** + * Fresnel reflectance (linear RGB) of a base surface with Schlick F0 + * `baseF0` under a thin film of index `filmIor` and thickness + * `thicknessNm`, seen at `cosTheta` (N·V). + */ + public static evalIridescence(outsideIOR: number, filmIor: number, cosTheta: number, thicknessNm: number, baseF0: [number, number, number]): [number, number, number] { + const smooth = (() => { const t = Math.min(Math.max(thicknessNm / 0.03, 0), 1); return t * t * (3 - 2 * t); })(); + const iridescenceIOR = outsideIOR + (filmIor - outsideIOR) * smooth; + const sinTheta2Sq = Math.pow(outsideIOR / iridescenceIOR, 2) * (1 - cosTheta * cosTheta); + const cosTheta2Sq = 1 - sinTheta2Sq; + if (cosTheta2Sq < 0) return [1, 1, 1]; + const cosTheta2 = Math.sqrt(cosTheta2Sq); + + const R0 = Math.pow((iridescenceIOR - outsideIOR) / (iridescenceIOR + outsideIOR), 2); + const R12 = IridescenceUtil._schlick(R0, cosTheta); + const T121 = 1 - R12; + const phi12 = iridescenceIOR < outsideIOR ? Math.PI : 0; + const phi21 = Math.PI - phi12; + + const out: number[] = [0, 0, 0]; + const R23: number[] = [], phi: number[] = [], R123: number[] = [], r123: number[] = [], Rs: number[] = []; + for (let i = 0; i < 3; i++) { + const f0 = Math.min(Math.max(baseF0[i], 0), 0.9999); + const s = Math.sqrt(f0); + const baseIOR = (1 + s) / (1 - s); + const R1 = Math.pow((baseIOR - iridescenceIOR) / (baseIOR + iridescenceIOR), 2); + R23[i] = IridescenceUtil._schlick(R1, cosTheta2); + phi[i] = phi21 + (baseIOR < iridescenceIOR ? Math.PI : 0); + R123[i] = Math.min(Math.max(R12 * R23[i], 1e-5), 0.9999); + r123[i] = Math.sqrt(R123[i]); + Rs[i] = (T121 * T121 * R23[i]) / (1 - R123[i]); + out[i] = R12 + Rs[i]; + } + const OPD = 2 * iridescenceIOR * thicknessNm * cosTheta2; + const Cm = [0, 1, 2].map(i => Rs[i] - T121); + for (let m = 1; m <= 2; m++) { + for (let i = 0; i < 3; i++) Cm[i] *= r123[i]; + const Sm = IridescenceUtil._sensitivity(m * OPD, phi.map(p => m * p)); + for (let i = 0; i < 3; i++) out[i] += Cm[i] * 2 * Sm[i]; + } + return [Math.max(out[0], 0), Math.max(out[1], 0), Math.max(out[2], 0)]; + } + + /** + * The F0 the PBR shader ends up using: film Fresnel converted back to a + * Schlick F0 and blended with the base F0 by `factor`. + */ + public static filmF0(baseF0: [number, number, number], NoV: number, factor: number, filmIor: number, thicknessNm: number): [number, number, number] { + const fresnel = IridescenceUtil.evalIridescence(1.0, filmIor, NoV, thicknessNm, baseF0); + const x = Math.min(Math.max(1 - NoV, 0), 1); + const x5 = Math.min(Math.max(x * x * x * x * x, 0), 0.9999); + const f = Math.min(Math.max(factor, 0), 1); + return [0, 1, 2].map(i => { + const film = Math.min(Math.max((fresnel[i] - x5) / (1 - x5), 0), 1); + return baseF0[i] + (film - baseF0[i]) * f; + }) as [number, number, number]; + } +} diff --git a/src/util/LensUtil.ts b/src/util/LensUtil.ts new file mode 100644 index 000000000..468193119 --- /dev/null +++ b/src/util/LensUtil.ts @@ -0,0 +1,26 @@ +/** + * CPU mirror of the vignette / chromatic-aberration math in `LensShader`, + * for tooling and GPU-vs-CPU validation. Keep in sync with the WGSL. + * @group Util + */ +export class LensUtil { + /** + * Vignette multiplier at a screen UV (0..1, origin irrelevant — symmetric). + * 1 = untouched, 0 = fully replaced by the vignette color. + */ + public static vignette(u: number, v: number, aspect: number, intensity: number, smoothness: number, roundness: number): number { + if (intensity <= 0) return 1; + let dx = (u - 0.5) * 2 * intensity; + const dy = (v - 0.5) * 2 * intensity; + dx *= 1 + (aspect - 1) * roundness; + const base = Math.min(Math.max(1 - (dx * dx + dy * dy), 0), 1); + return Math.pow(base, smoothness * 5 + 0.01); + } + + /** UV offset applied to the red channel (blue gets the negation). */ + public static chromaticOffset(u: number, v: number, intensity: number): [number, number] { + const cx = u - 0.5, cy = v - 0.5; + const k = (cx * cx + cy * cy) * 0.4 * intensity; + return [cx * k, cy * k]; + } +} diff --git a/src/util/MotionBlurUtil.ts b/src/util/MotionBlurUtil.ts new file mode 100644 index 000000000..5af9a18ef --- /dev/null +++ b/src/util/MotionBlurUtil.ts @@ -0,0 +1,44 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Vector3 } from '../math/Vector3'; + +/** + * CPU mirror of the velocity math in `MotionBlur_cs`, for tooling and tests. + * @group Util + */ +export class MotionBlurUtil { + /** + * Project a world position to screen UV (0..1, origin top-left) with a + * column-major view-projection matrix. Returns null behind the camera. + */ + public static projectToUV(worldPos: Vector3, viewProj: Matrix4): [number, number] | null { + const m = viewProj.rawData; + const x = worldPos.x, y = worldPos.y, z = worldPos.z; + const cx = m[0] * x + m[4] * y + m[8] * z + m[12]; + const cy = m[1] * x + m[5] * y + m[9] * z + m[13]; + const cw = m[3] * x + m[7] * y + m[11] * z + m[15]; + if (cw <= 0) return null; + return [(cx / cw) * 0.5 + 0.5, -(cy / cw) * 0.5 + 0.5]; + } + + /** + * Blur vector in pixels for a world-space point: how far it moved on + * screen between the previous and the current view-projection, times + * `scale`, clamped to `maxBlurPixels`. + */ + public static velocityPixels(worldPos: Vector3, currViewProj: Matrix4, prevViewProj: Matrix4, width: number, height: number, scale: number = 1, maxBlurPixels: number = Infinity): [number, number] { + const cur = MotionBlurUtil.projectToUV(worldPos, currViewProj); + const prev = MotionBlurUtil.projectToUV(worldPos, prevViewProj); + if (!cur || !prev) return [0, 0]; + let vx = (cur[0] - prev[0]) * width * scale, vy = (cur[1] - prev[1]) * height * scale; + const len = Math.hypot(vx, vy); + if (len > maxBlurPixels && len > 0) { vx *= maxBlurPixels / len; vy *= maxBlurPixels / len; } + return [vx, vy]; + } + + /** Shutter scale actually sent to the shader for a given frame time. */ + public static shutterScale(intensity: number, deltaMs: number, frameRateIndependent: boolean): number { + if (!frameRateIndependent) return intensity; + const dt = Math.min(Math.max(deltaMs, 1), 100); + return intensity * ((1000 / 60) / dt); + } +} diff --git a/src/util/TonemapUtil.ts b/src/util/TonemapUtil.ts new file mode 100644 index 000000000..326477833 --- /dev/null +++ b/src/util/TonemapUtil.ts @@ -0,0 +1,99 @@ +import { TonemapMode } from '../setting/post/TonemapSetting'; + +/** + * CPU reference of the curves in `TonemapShader`, kept line-for-line in sync + * with the WGSL. Used to map a mode name to the shader's integer selector, + * and by tooling / tests that need the expected LDR value for an HDR input + * (color pickers, LUT bakers, GPU-vs-CPU validation). + * @group Util + */ +export class TonemapUtil { + /** Shader selector per mode. Order is part of the shader contract. */ + public static readonly MODE_INDEX: Record = { + None: 0, + ACES: 1, + Reinhard: 2, + Uncharted2: 3, + AgX: 4, + Neutral: 5, + }; + + /** All mode names, in selector order. */ + public static readonly MODES: TonemapMode[] = ['None', 'ACES', 'Reinhard', 'Uncharted2', 'AgX', 'Neutral']; + + /** Selector for a mode name; unknown names fall back to ACES (the engine default). */ + public static modeIndex(mode: string | undefined): number { + const i = (TonemapUtil.MODE_INDEX as any)[mode as any]; + return i === undefined ? TonemapUtil.MODE_INDEX.ACES : i; + } + + /** + * Apply exposure + tone curve to a scene-linear RGB triple. + * @returns linear display-referred RGB (before the sRGB encode) + */ + public static apply(mode: TonemapMode, rgb: [number, number, number], exposure: number = 1, whitePoint: number = 4): [number, number, number] { + const c: [number, number, number] = [rgb[0] * exposure, rgb[1] * exposure, rgb[2] * exposure]; + switch (mode) { + case 'ACES': return c.map(TonemapUtil._aces) as any; + case 'Reinhard': { const w2 = whitePoint * whitePoint; return c.map(x => (x * (1 + x / w2)) / (1 + x)) as any; } + case 'Uncharted2': { const W = TonemapUtil._hable(11.2); return c.map(x => TonemapUtil._hable(x * 2) / W) as any; } + case 'AgX': return TonemapUtil._agx(c); + case 'Neutral': return TonemapUtil._neutral(c); + default: return c; + } + } + + private static _aces(x: number): number { + return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); + } + + private static _hable(x: number): number { + const A = 0.15, B = 0.50, C = 0.10, D = 0.20, E = 0.02, F = 0.30; + return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; + } + + // Column-major 3×3 (same layout as the WGSL mat3x3 constructors). + private static _mul(m: number[], v: number[]): [number, number, number] { + return [ + m[0] * v[0] + m[3] * v[1] + m[6] * v[2], + m[1] * v[0] + m[4] * v[1] + m[7] * v[2], + m[2] * v[0] + m[5] * v[1] + m[8] * v[2], + ]; + } + + private static readonly SRGB_TO_REC2020 = [0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0113, 0.8956]; + private static readonly REC2020_TO_SRGB = [1.6605, -0.1246, -0.0182, -0.5876, 1.1329, -0.1006, -0.0728, -0.0083, 1.1187]; + private static readonly AGX_INSET = [0.856627153315983, 0.137318972929847, 0.11189821299995, 0.0951212405381588, 0.761241990602591, 0.0767994186031903, 0.0482516061458583, 0.101439036467562, 0.811302368396859]; + private static readonly AGX_OUTSET = [1.1271005818144368, -0.1413297634984383, -0.14132976349843826, -0.11060664309660323, 1.157823702216272, -0.11060664309660294, -0.016493938717834573, -0.016493938717834257, 1.2519364065950405]; + + private static _agx(c: number[]): [number, number, number] { + const minEv = -12.47393, maxEv = 4.026069; + let v = TonemapUtil._mul(TonemapUtil.SRGB_TO_REC2020, c); + v = TonemapUtil._mul(TonemapUtil.AGX_INSET, v); + v = v.map(x => { + x = Math.log2(Math.max(x, 1e-10)); + x = Math.min(Math.max((x - minEv) / (maxEv - minEv), 0), 1); + const x2 = x * x, x4 = x2 * x2; + return 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; + }) as any; + v = TonemapUtil._mul(TonemapUtil.AGX_OUTSET, v); + v = v.map(x => Math.pow(Math.max(x, 0), 2.2)) as any; + v = TonemapUtil._mul(TonemapUtil.REC2020_TO_SRGB, v); + return v.map(x => Math.min(Math.max(x, 0), 1)) as any; + } + + private static _neutral(c: number[]): [number, number, number] { + const startCompression = 0.8 - 0.04, desaturation = 0.15; + const x = Math.min(c[0], c[1], c[2]); + const offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + let r = c[0] - offset, g = c[1] - offset, b = c[2] - offset; + const peak = Math.max(r, g, b); + if (peak < startCompression) return [r, g, b]; + const d = 1 - startCompression; + const newPeak = 1 - (d * d) / (peak + d - startCompression); + const s = newPeak / peak; + r *= s; g *= s; b *= s; + const t = 1 - 1 / (desaturation * (peak - newPeak) + 1); + return [r + (newPeak - r) * t, g + (newPeak - g) * t, b + (newPeak - b) * t]; + } +} diff --git a/src/util/transformUtil/RotationControlComponents.ts b/src/util/transformUtil/RotationControlComponents.ts index 264d9176f..d5dbb8b9e 100644 --- a/src/util/transformUtil/RotationControlComponents.ts +++ b/src/util/transformUtil/RotationControlComponents.ts @@ -226,7 +226,8 @@ export class RotationControlComponents extends TransformControllerBaseComponent } intersect = collider.rayPick(ray); if (intersect) { - let distance = Vector3.distance(intersect.intersectPoint, collider.shape.center); + // Ring radius test is done in the handle's local space. + let distance = Vector3.distance(intersect.localPoint, collider.shape.center); if (distance > 20 + 0.8 || distance < 20 - 0.8) { continue; } diff --git a/test/components/GLTF_Extensions.test.ts b/test/components/GLTF_Extensions.test.ts new file mode 100644 index 000000000..e856c74b0 --- /dev/null +++ b/test/components/GLTF_Extensions.test.ts @@ -0,0 +1,148 @@ +import { test, expect, end, delay } from '../util' +import { CameraUtil, Engine3D, KHR_materials_specular, KHR_mesh_quantization, LitMaterial, MaterialVariants, MeshRenderer, Scene3D, Vector3, View3D } from '@orillusion/core'; +import { buildVariantsDemoGLB } from '@samples/utils/GLBBuilder'; + +// LitMaterial needs an engine (default textures), so create it before any test. +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); + +await test('KHR_mesh_quantization.dequantize: normalization rules, idempotent', async () => { + const a = { data: new Int8Array([-128, -127, 0, 127]) as any, normalize: true }; + KHR_mesh_quantization.dequantize(a); + expect(a.data instanceof Float32Array).tobe(true); + expect(Array.from(a.data as Float32Array)).toEqual([-1, -1, 0, 1]); // −128 clamps to −1 + expect(a.normalize).tobe(false); + const same = a.data; + KHR_mesh_quantization.dequantize(a); + expect(a.data === same).tobe(true); // already float → untouched + + const b = { data: new Uint8Array([0, 255]) as any, normalize: true }; + KHR_mesh_quantization.dequantize(b); + expect(Array.from(b.data as Float32Array)).toEqual([0, 1]); + const c = { data: new Int16Array([-32768, 32767, 16384]) as any, normalize: true }; + KHR_mesh_quantization.dequantize(c); + expect(c.data[0]).tobe(-1); expect(c.data[1]).tobe(1); expect(c.data[2]).toSubequal(0.5, 1e-4); + const d = { data: new Uint16Array([65535, 0]) as any, normalize: true }; + KHR_mesh_quantization.dequantize(d); + expect(Array.from(d.data as Float32Array)).toEqual([1, 0]); + const e = { data: new Int16Array([-300, 7, 1200]) as any, normalize: false }; // non-normalized ints keep their value + KHR_mesh_quantization.dequantize(e); + expect(Array.from(e.data as Float32Array)).toEqual([-300, 7, 1200]); + expect(KHR_mesh_quantization.isQuantizable('TEXCOORD_1') && KHR_mesh_quantization.isQuantizable('POSITION')).tobe(true); + expect(KHR_mesh_quantization.isQuantizable('JOINTS_0')).tobe(false); +}) + +await test('KHR_materials_specular.apply: factors → specularColor uniform (rgb tint, a strength)', async () => { + const m = new LitMaterial(); + KHR_materials_specular.apply({}, { extensions: { KHR_materials_specular: { specularFactor: 0.4, specularColorFactor: [0.9, 0.5, 0.1] } } }, m); + const c = m.shader.getUniformColor('specularColor'); + expect(c.r).toSubequal(0.9, 1e-6); expect(c.b).toSubequal(0.1, 1e-6); expect(c.a).toSubequal(0.4, 1e-6); + const d = new LitMaterial(); + KHR_materials_specular.apply({}, { extensions: { KHR_materials_specular: {} } }, d); // spec defaults + const dc = d.shader.getUniformColor('specularColor'); + expect(dc.r === 1 && dc.g === 1 && dc.b === 1 && dc.a === 1).tobe(true); + const before = new LitMaterial().shader.getUniformColor('specularColor').a; + const n = new LitMaterial(); + KHR_materials_specular.apply({}, {}, n); // no extension → untouched + expect(n.shader.getUniformColor('specularColor').a).tobe(before); +}) + +// ---- load a generated GLB that uses all of it ------------------------------ +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +view.camera.lookAt(new Vector3(0, 0, 12), new Vector3(0, 0, 0)); +engine.startRenderView(view); + +const info = buildVariantsDemoGLB(2, 16); +const root = await engine.res.loadGltf(URL.createObjectURL(info.blob)); +view.scene.addChild(root); +const renderers = root.getComponentsInChild(MeshRenderer); +const sphere = renderers.find(r => r.object3D.name.includes('Sphere') || r.geometry.getAttribute('position').data.length === info.sphereVertices * 3); +const ribbon = renderers.find(r => r !== sphere); + +await test('quantized sphere loads as float geometry with the right extents', async () => { + expect(renderers.length).tobe(2); + const pos = sphere.geometry.getAttribute('position').data, nor = sphere.geometry.getAttribute('normal').data, uv = sphere.geometry.getAttribute('uv').data; + expect(pos instanceof Float32Array && nor instanceof Float32Array && uv instanceof Float32Array).tobe(true); + expect(pos.length).tobe(info.sphereVertices * 3); + let maxAbs = 0, maxLenErr = 0, uvMin = 1, uvMax = 0; + for (let i = 0; i < pos.length; i += 3) { + maxAbs = Math.max(maxAbs, Math.abs(pos[i]), Math.abs(pos[i + 1]), Math.abs(pos[i + 2])); + maxLenErr = Math.max(maxLenErr, Math.abs(Math.hypot(pos[i], pos[i + 1], pos[i + 2]) - 1)); // unit sphere after ÷32767 + const nl = Math.hypot(nor[i], nor[i + 1], nor[i + 2]); + if (Math.abs(nl - 1) > 0.02) throw new Error('normal not ~unit after int8 dequantization: ' + nl); + } + for (let i = 0; i < uv.length; i++) { uvMin = Math.min(uvMin, uv[i]); uvMax = Math.max(uvMax, uv[i]); } + expect(maxAbs).toSubequal(1, 1e-4); + expect(maxLenErr < 1e-3).tobe(true); + expect(uvMin).tobe(0); expect(uvMax).toSubequal(1, 1e-6); + // Node scale ×2 brings it to world radius 2. + const b = sphere.object3D.bound; + expect(b.extents.x).toSubequal(2, 0.01); expect(b.extents.y).toSubequal(2, 0.01); +}) + +await test('default material carries KHR_materials_specular', async () => { + const c = (sphere.material as LitMaterial).shader.getUniformColor('specularColor'); + expect(c.g).toSubequal(0.5, 1e-6); expect(c.b).toSubequal(0.25, 1e-6); expect(c.a).toSubequal(0.5, 1e-6); + expect((sphere.material as LitMaterial).baseColor.r).toSubequal(0.6, 1e-6); +}) + +await test('non-indexed mesh: fallback indices cover every vertex (no Uint8 wrap)', async () => { + const idx = ribbon.geometry.getAttribute('indices').data; + const vertexCount = ribbon.geometry.getAttribute('position').data.length / 3; + expect(vertexCount).tobe(info.ribbonTriangles * 3); + expect(idx.length).tobe(vertexCount); + expect(idx.BYTES_PER_ELEMENT >= 2).tobe(true); + let max = 0; const seen = new Set(); + for (let i = 0; i < idx.length; i++) { max = Math.max(max, idx[i]); seen.add(idx[i]); } + expect(max).tobe(vertexCount - 1); + expect(seen.size).tobe(vertexCount); +}) + +await test('KHR_materials_variants: MaterialVariants on the root switches only mapped primitives', async () => { + const v = root.getComponent(MaterialVariants); + expect(v != null).tobe(true); + expect(v.variantNames).toEqual(['Crimson', 'Ocean', 'Velvet']); + expect(v.currentVariant).tobe(null); + expect(v.bindings.length).tobe(1); // the ribbon has no mappings + const original = sphere.material, ribbonMat = ribbon.material; + + expect(v.selectVariant('Crimson')).tobe(true); + expect(sphere.material !== original).tobe(true); + expect((sphere.material as LitMaterial).baseColor.r).toSubequal(0.8, 1e-6); + expect(v.currentVariant).tobe('Crimson'); expect(v.currentIndex).tobe(0); + expect(ribbon.material === ribbonMat).tobe(true); + + expect(v.selectVariant(1)).tobe(true); // by index + expect((sphere.material as LitMaterial).baseColor.b).toSubequal(0.8, 1e-6); + + expect(v.selectVariant('Velvet')).tobe(true); + const velvet = sphere.material as LitMaterial; + expect(velvet.sheenRoughness).toSubequal(0.45, 1e-6); // sheen extension applied to the variant material + expect((velvet.shader.getDefaultColorShader() as any).defineValue['USE_SHEEN']).tobe(true); + + expect(v.selectVariant('Nope')).tobe(false); // unknown → no change + expect(v.selectVariant(7)).tobe(false); + expect(sphere.material === velvet).tobe(true); + + expect(v.selectVariant(null)).tobe(true); + expect(sphere.material === original).tobe(true); + expect(v.currentVariant).tobe(null); +}) + +await test('renders every variant without GPU / shader errors', async () => { + const v = root.getComponent(MaterialVariants); + const errors: string[] = []; + const onErr = (e: any) => errors.push(String(e?.error?.message ?? e)); + engine.context3D.device.addEventListener('uncapturederror', onErr); + for (const name of [...v.variantNames, null]) { + v.selectVariant(name); + await delay(350); + } + engine.context3D.device.removeEventListener('uncapturederror', onErr); + if (errors.length) throw new Error('GPU errors: ' + errors.slice(0, 2).join(' | ')); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/LODGroup.test.ts b/test/components/LODGroup.test.ts new file mode 100644 index 000000000..07cc993db --- /dev/null +++ b/test/components/LODGroup.test.ts @@ -0,0 +1,179 @@ +import { test, expect, end, waitUntil } from '../util' +import { BoxGeometry, CameraUtil, Engine3D, LitMaterial, LODGroup, LODMode, MeshRenderer, Object3D, Scene3D, SphereGeometry, View3D } from '@orillusion/core'; + +const engine = await Engine3D.init(); + +let view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, 1, 0.1, 5000); +view.camera.object3D.z = 10; +view.camera.lookAt(view.camera.object3D.localPosition, new Object3D().localPosition); +engine.startRenderViews([view]); + +function makeGroup(radius = 1): { root: Object3D, lod: LODGroup, levels: Object3D[] } { + const root = new Object3D(); + const lod = root.addComponent(LODGroup); + const levels: Object3D[] = []; + const geos = [new SphereGeometry(radius, 16, 16), new SphereGeometry(radius, 6, 6), new BoxGeometry(radius * 2, radius * 2, radius * 2)]; + for (let i = 0; i < 3; i++) { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = geos[i]; + mr.material = new LitMaterial(); + root.addChild(o); + levels.push(o); + } + view.scene.addChild(root); + return { root, lod, levels }; +} + +function shownLevels(levels: Object3D[]): number[] { + const r: number[] = []; + levels.forEach((o, i) => { if (o.transform.enable) r.push(i); }); + return r; +} + +// Camera at z = 10, fov 60°, radius 1 → metric = r / (d · tan30°) = 0.1732 +await test('ScreenSize metric matches r / (d·tan(fov/2))', async () => { + const { lod, root } = makeGroup(1); + // Levels added out of order on purpose; they must be sorted finest-first. + lod.addLevel(root.entityChildren[2] as Object3D, 0.02); + lod.addLevel(root.entityChildren[0] as Object3D, 0.10); + lod.addLevel(root.entityChildren[1] as Object3D, 0.04); + expect(lod.levels.map(l => l.threshold)).toEqual([0.10, 0.04, 0.02]); + lod.radius = 1; + const m = lod.measure(view.camera); + expect(m).toSubequal(1 / (10 * Math.tan(Math.PI / 6)), 1e-4); + root.destroy(true); +}) + +await test('auto radius from level bounds', async () => { + const { lod, root, levels } = makeGroup(2); + levels.forEach((o, i) => lod.addLevel(o, [0.1, 0.04, 0.02][i])); + // Sphere radius 2 → AABB half-extent 2 → corner distance 2√3 + const m = lod.measure(view.camera); + expect(m).toSubequal(2 * Math.sqrt(3) / (10 * Math.tan(Math.PI / 6)), 1e-3); + root.destroy(true); +}) + +await test('exactly one level enabled, switches with camera distance, culls beyond last', async () => { + const { lod, root, levels } = makeGroup(1); + lod.radius = 1; + lod.hysteresis = 0; + levels.forEach((o, i) => lod.addLevel(o, [0.10, 0.04, 0.02][i])); + // Nothing shown until the first update runs. + expect(shownLevels(levels)).toEqual([]); + + await waitUntil(() => lod.currentLevel === 0, 5000); + expect(shownLevels(levels)).toEqual([0]); + + view.camera.object3D.z = 30; // metric 0.0577 → level 1 + await waitUntil(() => lod.currentLevel === 1, 5000); + expect(shownLevels(levels)).toEqual([1]); + + view.camera.object3D.z = 60; // metric 0.0289 → level 2 + await waitUntil(() => lod.currentLevel === 2, 5000); + expect(shownLevels(levels)).toEqual([2]); + + view.camera.object3D.z = 200; // metric 0.0087 → culled + await waitUntil(() => lod.currentLevel === LODGroup.CULLED, 5000); + expect(shownLevels(levels)).toEqual([]); + + lod.cullBeyondLast = false; // same distance → coarsest level instead of nothing + await waitUntil(() => lod.currentLevel === 2, 5000); + expect(shownLevels(levels)).toEqual([2]); + + view.camera.object3D.z = 10; // back to the front → level 0 again + await waitUntil(() => lod.currentLevel === 0, 5000); + expect(shownLevels(levels)).toEqual([0]); + root.destroy(true); +}) + +await test('hysteresis: promotion needs extra margin, demotion does not', async () => { + const { lod, root, levels } = makeGroup(1); + lod.radius = 1; + lod.hysteresis = 0.2; + levels.forEach((o, i) => lod.addLevel(o, [0.10, 0.04, 0.02][i])); + // Pure selection logic, no frames needed. + expect(lod.selectLevel(0.105, 1)).tobe(1); // just above 0.10, coming from coarser → stays + expect(lod.selectLevel(0.125, 1)).tobe(0); // above 0.10 × 1.2 → promoted + expect(lod.selectLevel(0.099, 0)).tobe(1); // below 0.10, coming from finer → dropped immediately + expect(lod.selectLevel(0.105, 0)).tobe(0); // still above → keeps level 0 + expect(lod.selectLevel(0.019, 2)).tobe(LODGroup.CULLED); + expect(lod.selectLevel(0.5, LODGroup.CULLED)).tobe(0); // from culled: no margin + root.destroy(true); +}) + +await test('Distance mode uses world distance / bias', async () => { + const { lod, root, levels } = makeGroup(1); + lod.mode = LODMode.Distance; + lod.hysteresis = 0; + levels.forEach((o, i) => lod.addLevel(o, [50, 20, 100][i])); // deliberately unsorted + expect(lod.levels.map(l => l.threshold)).toEqual([20, 50, 100]); + expect(lod.levels.map(l => levels.indexOf(l.objects[0]))).toEqual([1, 0, 2]); + view.camera.object3D.z = 10; + expect(lod.measure(view.camera)).toSubequal(10, 1e-6); + expect(lod.selectLevel(10)).tobe(0); + expect(lod.selectLevel(35)).tobe(1); + expect(lod.selectLevel(99)).tobe(2); + expect(lod.selectLevel(101)).tobe(LODGroup.CULLED); + lod.bias = 2; // bias 2 halves the effective distance + expect(lod.measure(view.camera)).toSubequal(5, 1e-6); + root.destroy(true); +}) + +await test('mode switch + setThresholds keeps object↔level mapping', async () => { + const { lod, root, levels } = makeGroup(1); + levels.forEach((o, i) => lod.addLevel(o, [0.10, 0.04, 0.02][i])); // hi, mid, low + lod.mode = LODMode.Distance; + lod.setThresholds([20, 50, 100]); + expect(lod.levels.map(l => l.threshold)).toEqual([20, 50, 100]); + expect(lod.levels.map(l => levels.indexOf(l.objects[0]))).toEqual([0, 1, 2]); + lod.mode = LODMode.ScreenSize; + lod.setThresholds([0.10, 0.04, 0.02]); + expect(lod.levels.map(l => levels.indexOf(l.objects[0]))).toEqual([0, 1, 2]); + root.destroy(true); +}) + +await test('forceLevel overrides the metric, null restores auto', async () => { + const { lod, root, levels } = makeGroup(1); + lod.radius = 1; + levels.forEach((o, i) => lod.addLevel(o, [0.10, 0.04, 0.02][i])); + view.camera.object3D.z = 10; + lod.forceLevel = 2; + await waitUntil(() => lod.currentLevel === 2, 5000); + expect(shownLevels(levels)).toEqual([2]); + lod.forceLevel = 99; // clamped to last level + expect(lod.selectLevel(1)).tobe(2); + lod.forceLevel = LODGroup.CULLED; + await waitUntil(() => lod.currentLevel === LODGroup.CULLED, 5000); + expect(shownLevels(levels)).toEqual([]); + lod.forceLevel = null; + await waitUntil(() => lod.currentLevel === 0, 5000); + expect(shownLevels(levels)).toEqual([0]); + root.destroy(true); +}) + +await test('onLevelChange fires once per switch; removeLevel re-enables objects', async () => { + const { lod, root, levels } = makeGroup(1); + lod.radius = 1; + lod.hysteresis = 0; + levels.forEach((o, i) => lod.addLevel(o, [0.10, 0.04, 0.02][i])); + const changes: number[][] = []; + lod.onLevelChange = (l, p) => changes.push([l, p]); + view.camera.object3D.z = 10; + await waitUntil(() => lod.currentLevel === 0, 5000); + view.camera.object3D.z = 30; + await waitUntil(() => lod.currentLevel === 1, 5000); + await new Promise(r => setTimeout(r, 200)); // a few more frames: no duplicate events + expect(changes).toEqual([[0, -1], [1, 0]]); + + lod.removeLevel(1); + expect(levels[1].transform.enable).tobe(true); + expect(lod.levels.length).tobe(2); + root.destroy(true); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/Material_Iridescence.test.ts b/test/components/Material_Iridescence.test.ts new file mode 100644 index 000000000..d10f9e112 --- /dev/null +++ b/test/components/Material_Iridescence.test.ts @@ -0,0 +1,131 @@ +import { test, expect, end, waitUntil, frames, readRowRGBA16F } from '../util' +import { BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, IridescenceUtil, KHR_materials_iridescence, LitMaterial, MeshRenderer, Object3D, Scene3D, Vector3, View3D } from '@orillusion/core'; + +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); +engine.setting.render.tonemap.mode = 'None'; +const define = (m: LitMaterial, name: string) => (m.shader.getDefaultColorShader() as any).defineValue[name]; + +await test('IridescenceUtil: limits and behaviour of the thin-film Fresnel', async () => { + const base: [number, number, number] = [0.5, 0.5, 0.5]; + // Zero thickness: the film degenerates (its IOR collapses onto the outside medium) → base Fresnel at normal incidence. + const none = IridescenceUtil.evalIridescence(1, 1.3, 1, 0, base); + for (const c of none) expect(c).toSubequal(0.5, 0.02); + // factor 0 → untouched F0 + expect(IridescenceUtil.filmF0(base, 0.8, 0, 1.3, 400)).toEqual([0.5, 0.5, 0.5]); + // A real film colours a grey base: channels diverge. + const film = IridescenceUtil.evalIridescence(1, 1.3, 1, 400, base); + expect(Math.max(...film) - Math.min(...film) > 0.05).tobe(true); + expect(film.every(c => isFinite(c) && c >= 0)).tobe(true); + // Hue depends on thickness and on view angle. + const thin = IridescenceUtil.evalIridescence(1, 1.3, 1, 250, base); + const grazing = IridescenceUtil.evalIridescence(1, 1.3, 0.4, 400, base); + const diff = (a: number[], b: number[]) => Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]); + expect(diff(film, thin) > 0.05).tobe(true); + expect(diff(film, grazing) > 0.05).tobe(true); + // Total internal reflection guard (film less dense than the outside at a grazing angle). + expect(IridescenceUtil.evalIridescence(1.5, 1.0, 0.1, 400, base)).toEqual([1, 1, 1]); +}) + +await test('LitMaterial iridescence API, clone, and KHR_materials_iridescence.apply', async () => { + const m = new LitMaterial(); + expect(m.iridescence).tobe(0); expect(m.iridescenceIOR).toSubequal(1.3, 1e-6); expect(m.iridescenceThickness).tobe(400); + expect(!!define(m, 'USE_IRIDESCENCE')).tobe(false); + m.iridescenceThickness = 550; m.iridescenceIOR = 1.8; + expect(!!define(m, 'USE_IRIDESCENCE')).tobe(false); // parameters alone do not enable it + m.iridescence = 0.7; + expect(define(m, 'USE_IRIDESCENCE')).tobe(true); + expect(m.iridescenceThickness).tobe(550); expect(m.iridescenceIOR).toSubequal(1.8, 1e-6); // survived the factor write + m.iridescence = 5; expect(m.iridescence).tobe(1); // clamped + m.iridescenceIOR = 0.2; expect(m.iridescenceIOR).tobe(1); + const c = m.clone() as LitMaterial; + expect(c.iridescence).tobe(1); expect(c.iridescenceThickness).tobe(550); expect(define(c, 'USE_IRIDESCENCE')).tobe(true); + m.iridescence = 0; + expect(define(m, 'USE_IRIDESCENCE')).tobe(false); + + const g = new LitMaterial(); + KHR_materials_iridescence.apply({}, { extensions: { KHR_materials_iridescence: { iridescenceFactor: 0.8, iridescenceIor: 1.6, iridescenceThicknessMaximum: 620 } } }, g); + expect(g.iridescence).toSubequal(0.8, 1e-6); expect(g.iridescenceIOR).toSubequal(1.6, 1e-6); expect(g.iridescenceThickness).tobe(620); + const d = new LitMaterial(); + KHR_materials_iridescence.apply({}, { extensions: { KHR_materials_iridescence: { iridescenceFactor: 1 } } }, d); // spec defaults + expect(d.iridescenceIOR).toSubequal(1.3, 1e-6); expect(d.iridescenceThickness).tobe(400); + const n = new LitMaterial(); + KHR_materials_iridescence.apply({}, {}, n); + expect(!!define(n, 'USE_IRIDESCENCE')).tobe(false); +}) + +// ---- GPU: a grey metal wall seen and lit head-on, so the specular colour tracks F0 ---- +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +view.camera.lookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0)); +const lightObj = new Object3D(); +lightObj.rotationY = 180; +lightObj.addComponent(DirectLight).intensity = 3; +view.scene.addChild(lightObj); +const wall = new Object3D(); +const mr = wall.addComponent(MeshRenderer); +mr.geometry = new BoxGeometry(200, 200, 1); +const mat = new LitMaterial(); +mat.baseColor = new Color(0.5, 0.5, 0.5, 1); +mat.metallic = 1; mat.roughness = 0.6; +mr.material = mat; +view.scene.addChild(wall); +engine.startRenderView(view); + +const tonemapPost = (): any => (engine.getRenderJob(view) as any)?.graph?.getPass('PostPass')?.postList?.get('TonemapPost'); +async function measure(factor: number, thickness: number, ior = 1.3): Promise { + mat.iridescenceIOR = ior; mat.iridescenceThickness = thickness; mat.iridescence = factor; + await frames(); + const t: GPUTexture = tonemapPost().renderTexture.getGPUTexture(); + return (await readRowRGBA16F(engine.context3D.device, t, t.width >> 1, t.height >> 1, 1))[0].slice(0, 3); +} +const order = (c: number[]) => [0, 1, 2].sort((a, b) => c[b] - c[a]).join(''); + +let base: number[]; +await test('shader compiles with and without USE_IRIDESCENCE; factor 0 is neutral grey', async () => { + await waitUntil(() => tonemapPost()?.renderTexture, 15000); + base = await measure(0, 400); + console.log('[Iridescence] base', base.map(v => v.toFixed(4)).join(', ')); + expect(base[0] > 0.02).tobe(true); + expect(Math.abs(base[0] - base[2]) / base[0] < 0.08).tobe(true); // grey metal under white light + const on = await measure(1, 400); + expect(on.every(v => isFinite(v))).tobe(true); +}) + +await test('GPU hue follows the CPU thin-film model across thicknesses', async () => { + let decisive = 0; + const seen = new Set(); + for (const thickness of [200, 300, 400, 500, 650, 800]) { + const gpu = await measure(1, thickness); + const cpu = IridescenceUtil.filmF0([0.5, 0.5, 0.5], 1, 1, 1.3, thickness); + const sorted = [...cpu].sort((a, b) => b - a); + // Only judge when the model clearly separates the strongest and weakest channel. + const clear = (sorted[0] - sorted[2]) / Math.max(sorted[0], 1e-6) > 0.2; + const gOrder = order(gpu), cOrder = order(cpu); + console.log(`[Iridescence] ${thickness} nm gpu=(${gpu.map(v => v.toFixed(3))}) cpuF0=(${cpu.map(v => v.toFixed(3))}) ${gOrder}/${cOrder}${clear ? '' : ' (not decisive)'}`); + if (!clear) continue; + decisive++; + // Strongest and weakest channel must agree. + if (gOrder[0] !== cOrder[0] || gOrder[2] !== cOrder[2]) throw new Error(`hue mismatch at ${thickness} nm: gpu ${gOrder} vs cpu ${cOrder}`); + seen.add(cOrder[0] + cOrder[2]); + } + expect(decisive >= 3).tobe(true); + expect(seen.size >= 2).tobe(true); // the sweep really went through different hues +}) + +await test('factor blends between base and film; film IOR changes the result', async () => { + const full = await measure(1, 400), half = await measure(0.5, 400); + for (let i = 0; i < 3; i++) { + const lo = Math.min(base[i], full[i]) - 0.01, hi = Math.max(base[i], full[i]) + 0.01; + if (half[i] < lo || half[i] > hi) throw new Error(`factor 0.5 not between base and full on channel ${i}: ${base[i]} ${half[i]} ${full[i]}`); + } + const dense = await measure(1, 400, 2.0); + const d = Math.abs(dense[0] - full[0]) + Math.abs(dense[1] - full[1]) + Math.abs(dense[2] - full[2]); + expect(d > 0.01).tobe(true); + const back = await measure(0, 400); + for (let i = 0; i < 3; i++) expect(back[i]).toSubequal(base[i], 0.005); // switching it off restores the base exactly +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/Material_Sheen.test.ts b/test/components/Material_Sheen.test.ts new file mode 100644 index 000000000..be5312583 --- /dev/null +++ b/test/components/Material_Sheen.test.ts @@ -0,0 +1,129 @@ +import { test, expect, end, waitUntil, frames } from '../util' +import { BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, KHR_materials_sheen, LitMaterial, MeshRenderer, Object3D, Scene3D, Vector3, View3D } from '@orillusion/core'; + +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); +engine.setting.render.tonemap.mode = 'None'; // read scene-linear values back unchanged + +const define = (m: LitMaterial, name: string) => (m.shader.getDefaultColorShader() as any).defineValue[name]; + +await test('LitMaterial sheen API: defaults, define toggling, roughness packing, clone', async () => { + const m = new LitMaterial(); + expect(m.sheenRoughness).tobe(0); + expect(m.sheenColor.r + m.sheenColor.g + m.sheenColor.b).tobe(0); + expect(!!define(m, 'USE_SHEEN')).tobe(false); + + m.sheenRoughness = 0.6; + expect(!!define(m, 'USE_SHEEN')).tobe(false); // roughness alone does not enable the lobe + m.sheenColor = new Color(0.9, 0.5, 0.2, 1); + expect(define(m, 'USE_SHEEN')).tobe(true); + expect(m.sheenColor.r).toSubequal(0.9, 1e-6); + expect(m.sheenRoughness).toSubequal(0.6, 1e-6); // survived the color write (packed in alpha) + m.sheenRoughness = 7; + expect(m.sheenRoughness).tobe(1); // clamped + m.sheenRoughness = 0.6; + + const c = m.clone() as LitMaterial; + expect(c.sheenColor.g).toSubequal(0.5, 1e-6); + expect(c.sheenRoughness).toSubequal(0.6, 1e-6); + expect(define(c, 'USE_SHEEN')).tobe(true); + + m.sheenColor = new Color(0, 0, 0); + expect(define(m, 'USE_SHEEN')).tobe(false); // black switches it off again +}) + +await test('KHR_materials_sheen.apply reads factors, ignores materials without the extension', async () => { + const a = new LitMaterial(); + KHR_materials_sheen.apply({}, { extensions: { KHR_materials_sheen: { sheenColorFactor: [0.2, 0.4, 0.6], sheenRoughnessFactor: 0.3 } } }, a); + expect(a.sheenColor.b).toSubequal(0.6, 1e-6); + expect(a.sheenRoughness).toSubequal(0.3, 1e-6); + expect(define(a, 'USE_SHEEN')).tobe(true); + const b = new LitMaterial(); + KHR_materials_sheen.apply({}, { extensions: { KHR_materials_clearcoat: {} } }, b); + KHR_materials_sheen.apply({}, {}, b); + expect(!!define(b, 'USE_SHEEN')).tobe(false); +}) + +// ---- GPU ------------------------------------------------------------------- +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +view.camera.lookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0)); +// Light hits the wall at 60° from its normal; the camera looks straight down the normal. +const lightObj = new Object3D(); +lightObj.rotationY = 180 - 60; +const light = lightObj.addComponent(DirectLight); +light.intensity = 3; +view.scene.addChild(lightObj); +const wall = new Object3D(); +const mr = wall.addComponent(MeshRenderer); +mr.geometry = new BoxGeometry(200, 200, 1); +const mat = new LitMaterial(); +mat.baseColor = new Color(0.2, 0.1, 0.05, 1); +mat.roughness = 0.9; mat.metallic = 0; +mr.material = mat; +view.scene.addChild(wall); +engine.startRenderView(view); + +function halfToFloat(h: number): number { + const s = (h & 0x8000) ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff; + if (e === 0) return s * Math.pow(2, -14) * (f / 1024); + if (e === 31) return f ? NaN : s * Infinity; + return s * Math.pow(2, e - 15) * (1 + f / 1024); +} +const tonemapPost = (): any => (engine.getRenderJob(view) as any)?.graph?.getPass('PostPass')?.postList?.get('TonemapPost'); +async function readCenter(): Promise<[number, number, number]> { + const tex: GPUTexture = tonemapPost().renderTexture.getGPUTexture(); + const device = engine.context3D.device; + const buf = device.createBuffer({ size: 256, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + const enc = device.createCommandEncoder(); + enc.copyTextureToBuffer({ texture: tex, origin: { x: tex.width >> 1, y: tex.height >> 1 } }, { buffer: buf, bytesPerRow: 256 }, { width: 1, height: 1 }); + device.queue.submit([enc.finish()]); + await buf.mapAsync(GPUMapMode.READ); + const u16 = new Uint16Array(buf.getMappedRange().slice(0, 8)); + buf.unmap(); buf.destroy(); + return [halfToFloat(u16[0]), halfToFloat(u16[1]), halfToFloat(u16[2])]; +} +async function measure(sheen: Color, roughness: number) { + mat.sheenRoughness = roughness; + mat.sheenColor = sheen; + await frames(); + return readCenter(); +} + +let base: [number, number, number]; +await test('shader compiles with and without USE_SHEEN and the wall is lit', async () => { + await waitUntil(() => tonemapPost()?.renderTexture, 15000); + base = await measure(new Color(0, 0, 0), 0.8); + console.log('[Sheen] base', base.map(v => v.toFixed(4)).join(', ')); + expect(base[0] > 0.01 && base[0] > base[1] && base[1] > base[2]).tobe(true); + const lit = await measure(new Color(1, 1, 1), 0.8); + console.log('[Sheen] white sheen r=0.8', lit.map(v => v.toFixed(4)).join(', ')); + expect(lit.every(v => isFinite(v))).tobe(true); +}) + +await test('output = base·(1 − 0.157·max(sheen)) + sheen·S (linear in sheen color)', async () => { + const full = await measure(new Color(1, 1, 1), 0.8); + const half = await measure(new Color(0.5, 0.5, 0.5), 0.8); + for (let i = 0; i < 3; i++) { + const S_full = full[i] - base[i] * (1 - 0.157); + const S_half = (half[i] - base[i] * (1 - 0.157 * 0.5)) / 0.5; + console.log(`[Sheen] ch${i} S(full)=${S_full.toFixed(4)} S(half)=${S_half.toFixed(4)}`); + expect(S_full > 0.005).tobe(true); // the lobe really adds light at 60° incidence + if (Math.abs(S_full - S_half) > 0.01 + 0.05 * Math.abs(S_full)) throw new Error(`not linear in sheen color: ${S_full} vs ${S_half}`); + } +}) + +await test('sheen tint colors the lobe; roughness changes its strength', async () => { + const red = await measure(new Color(1, 0, 0), 0.8); + const dR = red[0] - base[0] * (1 - 0.157), dB = red[2] - base[2] * (1 - 0.157); + expect(dR > 0.005).tobe(true); + expect(Math.abs(dB) < 0.003).tobe(true); // no blue added by a red sheen + const rough = await measure(new Color(1, 1, 1), 1.0); + const tight = await measure(new Color(1, 1, 1), 0.3); + console.log('[Sheen] r=1.0', rough[0].toFixed(4), 'r=0.3', tight[0].toFixed(4)); + expect(Math.abs(rough[0] - tight[0]) > 0.003).tobe(true); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/PostEffects_GTAO.test.ts b/test/components/PostEffects_GTAO.test.ts index 3b6ae9ddd..8726d6b51 100644 --- a/test/components/PostEffects_GTAO.test.ts +++ b/test/components/PostEffects_GTAO.test.ts @@ -20,6 +20,10 @@ await test('Post GTAOPost test', async () => { // when queued after Light_*/Component tests. Bump to 15 s to // cover worst-case driver compile latency. await waitUntil(() => gtao.gtaoTexture, 15000) + // The canvas ResizeObserver can fire after the texture was created at + // the pre-layout size; the post follows on the next frame. Wait for + // that instead of sampling mid-resize. + await waitUntil(() => gtao.gtaoTexture.width === engine.context3D.presentationSize[0], 15000) let dest = engine.context3D.presentationSize[0]; let src = gtao.gtaoTexture?.width; expect(src).tobe(dest) diff --git a/test/components/PostEffects_Lens.test.ts b/test/components/PostEffects_Lens.test.ts new file mode 100644 index 000000000..36c6db5ab --- /dev/null +++ b/test/components/PostEffects_Lens.test.ts @@ -0,0 +1,147 @@ +import { test, expect, end, waitUntil, frames, readRowRGBA16F } from '../util' +import { BoxGeometry, CameraUtil, Color, Engine3D, LensPost, LensUtil, MeshRenderer, Object3D, PostProcessingComponent, Scene3D, UnLitMaterial, Vector3, View3D } from '@orillusion/core'; + +await test('LensUtil: vignette and aberration math', async () => { + expect(LensUtil.vignette(0.5, 0.5, 1.7, 0.6, 0.4, 1)).toSubequal(1, 1e-9); // center untouched + expect(LensUtil.vignette(0.1, 0.9, 1.7, 0, 0.4, 1)).tobe(1); // intensity 0 = off + const corner = LensUtil.vignette(0, 0, 1, 0.5, 0.2, 0); // d=(−0.5,−0.5) → 1−0.5 = 0.5 ^ 1.01 + expect(corner).toSubequal(Math.pow(0.5, 1.01), 1e-9); + // Roundness 1 on a wide screen darkens the left/right edge more than roundness 0. + expect(LensUtil.vignette(0, 0.5, 2, 0.4, 0.4, 1) < LensUtil.vignette(0, 0.5, 2, 0.4, 0.4, 0)).tobe(true); + expect(LensUtil.vignette(0, 0, 1, 5, 0.4, 1)).tobe(0); // clamps at 0 + expect(LensUtil.chromaticOffset(0.5, 0.5, 0.3)).toEqual([0, 0]); // no fringing on the axis + const o = LensUtil.chromaticOffset(0.75, 0.5, 0.2); + expect(o[0]).toSubequal(0.25 * 0.0625 * 0.4 * 0.2, 1e-12); + expect(o[1]).tobe(0); +}) + +// ---- GPU ------------------------------------------------------------------- +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); +engine.setting.render.tonemap.mode = 'None'; +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +view.camera.lookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0)); + +const makeWall = (w: number, x: number, z: number, color: Color) => { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = new BoxGeometry(w, 200, 0.01); + const m = new UnLitMaterial(); m.baseColor = color; + mr.material = m; + o.x = x; o.z = z; + view.scene.addChild(o); + return o; +}; +// Full-screen mid-grey wall, plus a white wall in front covering uv.x > 0.75. +const halfW = 5 * Math.tan(Math.PI / 6) * engine.aspect; // world half-width of the view at z = 0 +makeWall(400, 0, -0.5, new Color(0.5, 0.5, 0.5, 1)); +const bright = makeWall(100, halfW * 0.5 + 50, 0, new Color(1, 1, 1, 1)); +engine.startRenderView(view); +const post = view.scene.addComponent(PostProcessingComponent); +const lens = post.addPost(LensPost); + +const tonemapRT = (): GPUTexture => (engine.getRenderJob(view) as any).graph.getPass('PostPass').postList.get('TonemapPost').renderTexture.getGPUTexture(); +const px = async (u: number, v: number, w = 1) => { + const t = tonemapRT(); + return readRowRGBA16F(engine.context3D.device, t, Math.min(t.width - w, Math.max(0, u * t.width)), Math.min(t.height - 1, v * t.height), w); +}; +const off = () => { lens.vignetteIntensity = 0; lens.chromaticAberration = 0; lens.grainIntensity = 0; lens.grainStatic = true; }; + +let grey = 0; +await test('LensPost attaches, all-zero settings are a passthrough', async () => { + await waitUntil(() => (engine.getRenderJob(view) as any)?.graph?.getPass('PostPass')?.postList?.get('TonemapPost')?.renderTexture && lens.renderTexture, 15000); + expect(engine.setting.render.postProcessing.lens.enable).tobe(true); + off(); + await frames(); + const c = (await px(0.3, 0.5))[0], corner = (await px(0.02, 0.04))[0]; + grey = c[0]; + console.log('[Lens] grey wall center', c.slice(0, 3).map(v => v.toFixed(4)).join(','), 'corner', corner.slice(0, 3).map(v => v.toFixed(4)).join(',')); + expect(grey > 0.05).tobe(true); + expect(corner[0]).toSubequal(grey, 0.004); +}) + +await test('vignette: GPU falloff matches LensUtil at several screen points, and tints toward vignetteColor', async () => { + off(); + lens.vignetteIntensity = 0.7; lens.vignetteSmoothness = 0.3; lens.vignetteRoundness = 1; + await frames(); + const t = tonemapRT(); + const aspect = t.width / t.height; + for (const [u, v] of [[0.3, 0.5], [0.1, 0.5], [0.3, 0.1], [0.05, 0.9], [0.5, 0.02]]) { + const gpu = (await px(u, v))[0][0]; + // Sample at the pixel centre the readback actually used. + const uu = (Math.floor(u * t.width) + 0.5) / t.width, vv = (Math.floor(v * t.height) + 0.5) / t.height; + const cpu = grey * LensUtil.vignette(uu, vv, aspect, 0.7, 0.3, 1); + console.log(`[Lens] vignette uv=(${u},${v}) gpu=${gpu.toFixed(4)} cpu=${cpu.toFixed(4)}`); + if (Math.abs(gpu - cpu) > 0.006) throw new Error(`vignette mismatch at ${u},${v}: gpu ${gpu} cpu ${cpu}`); + } + lens.vignetteColor = new Color(0.3, 0, 0, 1); + lens.vignetteIntensity = 5; // fully vignetted everywhere but the very centre + await frames(); + const tinted = (await px(0.05, 0.1))[0]; + expect(tinted[0]).toSubequal(0.3, 0.01); + expect(tinted[1] < 0.01 && tinted[2] < 0.01).tobe(true); + lens.vignetteColor = new Color(0, 0, 0, 1); +}) + +await test('chromatic aberration: R and B split at an off-axis edge, none on a flat region', async () => { + off(); + await frames(); + const t = tonemapRT(); + // Locate the grey→white edge on the middle row (expected near u = 0.75). + const row = await px(0.6, 0.5, Math.floor(t.width * 0.3)); + const edge = row.findIndex(p => p[0] > 0.75); + const edgeU = (Math.floor(0.6 * t.width) + edge) / t.width; + console.log('[Lens] edge at u =', edgeU.toFixed(4)); + expect(edgeU > 0.7 && edgeU < 0.8).tobe(true); + const before = row[edge - 3]; + expect(Math.abs(before[0] - before[2]) < 0.004).tobe(true); // neutral grey without the effect + + lens.chromaticAberration = 4; + await frames(); + const shiftPx = LensUtil.chromaticOffset(edgeU, 0.5, 4)[0] * t.width; + console.log('[Lens] expected red/blue shift', shiftPx.toFixed(2), 'px'); + expect(shiftPx > 4).tobe(true); + const x = Math.floor(0.6 * t.width) + edge - 3; // 3 px on the grey side of the edge + const p = (await readRowRGBA16F(engine.context3D.device, t, x, Math.floor(t.height * 0.5), 1))[0]; + console.log('[Lens] fringe pixel', p.slice(0, 3).map(v => v.toFixed(4)).join(',')); + expect(p[0] > 0.9).tobe(true); // red pulled in from the white side + expect(p[2] < grey + 0.01).tobe(true); // blue still grey + expect(Math.abs(p[1] - grey) < 0.01).tobe(true); // green untouched + const flat = (await px(0.2, 0.5))[0]; + expect(Math.abs(flat[0] - flat[2]) < 0.004).tobe(true); // uniform region: no fringe +}) + +await test('grain: adds per-pixel variance, static flag freezes it, off restores a flat image', async () => { + off(); + lens.grainIntensity = 0.5; + await frames(); + const a = await px(0.2, 0.3, 16); + const mean = a.reduce((s, p) => s + p[0], 0) / a.length; + const varA = a.reduce((s, p) => s + (p[0] - mean) ** 2, 0) / a.length; + console.log('[Lens] grain mean', mean.toFixed(4), 'std', Math.sqrt(varA).toFixed(4)); + expect(Math.sqrt(varA) > 0.02).tobe(true); + expect(Math.abs(mean - grey) < 0.12).tobe(true); // zero-mean noise + await frames(1); + const b = await px(0.2, 0.3, 16); + expect(a.map(p => p[0].toFixed(5)).join()).tobe(b.map(p => p[0].toFixed(5)).join()); // grainStatic → identical frames + lens.grainStatic = false; + await frames(); + const c = await px(0.2, 0.3, 16); + expect(a.map(p => p[0].toFixed(5)).join() !== c.map(p => p[0].toFixed(5)).join()).tobe(true); // animated + off(); + await frames(); + const flat = await px(0.2, 0.3, 16); + expect(flat.every(p => Math.abs(p[0] - grey) < 0.004)).tobe(true); +}) + +await test('removePost detaches and clears the enable flag', async () => { + post.removePost(LensPost); + await frames(); + expect(engine.setting.render.postProcessing.lens.enable).tobe(false); + expect((engine.getRenderJob(view) as any).graph.getPass('PostPass').postList.has('LensPost')).tobe(false); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/PostEffects_MotionBlur.test.ts b/test/components/PostEffects_MotionBlur.test.ts new file mode 100644 index 000000000..d84a50d34 --- /dev/null +++ b/test/components/PostEffects_MotionBlur.test.ts @@ -0,0 +1,141 @@ +import { test, expect, end, waitUntil, readRowRGBA16F } from '../util' +import { BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, LitMaterial, Matrix4, MeshRenderer, MotionBlurPost, MotionBlurUtil, Object3D, PostProcessingComponent, Scene3D, Time, Vector3, View3D } from '@orillusion/core'; + +// Matrix4 lives in the engine's WASM pool, so the engine must exist before any test builds one. +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); + +await test('MotionBlurUtil: shutter scale, projection, velocity', async () => { + expect(MotionBlurUtil.shutterScale(0.5, 33.3, false)).tobe(0.5); + expect(MotionBlurUtil.shutterScale(1, 1000 / 60, true)).toSubequal(1, 1e-9); + expect(MotionBlurUtil.shutterScale(1, 1000 / 30, true)).toSubequal(0.5, 1e-9); // slower frame → shorter shutter fraction + expect(MotionBlurUtil.shutterScale(1, 5000, true)).toSubequal((1000 / 60) / 100, 1e-9); // dt clamped to 100 ms + const I = new Matrix4().identity(); + const uv = MotionBlurUtil.projectToUV(new Vector3(0.5, 0.5, 0), I); + expect(uv[0]).toSubequal(0.75, 1e-9); expect(uv[1]).toSubequal(0.25, 1e-9); // +y is up → smaller v + expect(MotionBlurUtil.velocityPixels(new Vector3(0.2, 0, 0), I, I, 800, 600)).toEqual([0, 0]); +}) + +engine.setting.render.tonemap.mode = 'None'; +let camX = 0, step = 0; +// Triangle-wave dolly: constant speed, reversing every 12 frames. +let frame = 0; +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +const place = () => view.camera.lookAt(new Vector3(camX, 0, 5), new Vector3(camX, 0, 0)); +place(); + +const lightObj = new Object3D(); +lightObj.rotationY = 180; +lightObj.addComponent(DirectLight).intensity = 3; +view.scene.addChild(lightObj); +const wall = (w: number, x: number, z: number, c: Color) => { + const o = new Object3D(); + const mr = o.addComponent(MeshRenderer); + mr.geometry = new BoxGeometry(w, 200, 0.01); + const m = new LitMaterial(); m.baseColor = c; m.roughness = 1; m.metallic = 0; + mr.material = m; + o.x = x; o.z = z; + view.scene.addChild(o); +}; +wall(400, 0, -0.05, new Color(0.02, 0.02, 0.02, 1)); // dark backdrop +wall(100, 50, 0, new Color(1, 1, 1, 1)); // bright wall covering world x > 0 + +engine.startRenderView(view); +const post = view.scene.addComponent(PostProcessingComponent); +const blur = post.addPost(MotionBlurPost); +blur.frameRateIndependent = false; // deterministic: blur by the raw per-frame displacement +blur.samples = 16; + +// Drive the camera from a lateUpdate-ish hook: before each frame renders. +const drive = () => { + if (step !== 0) { + frame++; + const dir = Math.floor(frame / 12) % 2 === 0 ? 1 : -1; + camX += dir * step; + place(); + } + requestAnimationFrame(drive); +}; +requestAnimationFrame(drive); + +const tonemapRT = (): GPUTexture => (engine.getRenderJob(view) as any).graph.getPass('PostPass').postList.get('TonemapPost').renderTexture.getGPUTexture(); +/** Width (in pixels) of the dark→bright transition on the middle row: pixels strictly between the two plateaus. */ +async function transitionWidth(): Promise<{ width: number; dark: number; bright: number }> { + const t = tonemapRT(); + const row = await readRowRGBA16F(engine.context3D.device, t, 0, Math.floor(t.height / 2), t.width); + const v = row.map(p => p[1]); + const dark = Math.min(...v), bright = Math.max(...v); + const lo = dark + (bright - dark) * 0.08, hi = bright - (bright - dark) * 0.08; + return { width: v.filter(x => x > lo && x < hi).length, dark, bright }; +} +/** Wait for `n` more rendered frames. Software WebGPU in CI runs at ~2 fps, so wall-clock delays are not enough for a setting change to reach the image. */ +async function frames(n: number): Promise { + const target = Time.frame + n; + await waitUntil(() => Time.frame >= target, 30000, 10); +} +async function maxTransition(n = 5): Promise { + let m = 0; + for (let i = 0; i < n; i++) { m = Math.max(m, (await transitionWidth()).width); await frames(1); } + return m; +} + +await test('static camera: the image stays sharp with the post attached', async () => { + await waitUntil(() => (engine.getRenderJob(view) as any)?.graph?.getPass('PostPass')?.postList?.get('TonemapPost')?.renderTexture && blur.outTexture, 15000); + expect(engine.setting.render.postProcessing.motionBlur.enable).tobe(true); + blur.intensity = 1; + await frames(3); + const s = await transitionWidth(); + console.log('[MotionBlur] static: transition', s.width, 'px, dark', s.dark.toFixed(3), 'bright', s.bright.toFixed(3)); + expect(s.bright > s.dark + 0.2).tobe(true); // the edge is really there + expect(s.width <= 2).tobe(true); +}) + +let pxPerFrame = 0; +await test('moving camera: the edge is smeared by about the per-frame displacement', async () => { + const t = tonemapRT(); + step = 0.12; + // World → pixels at z = 0: width / (2 · 5 · tan30° · aspect) + pxPerFrame = step * t.width / (2 * 5 * Math.tan(Math.PI / 6) * (t.width / t.height)); + blur.intensity = 1; blur.maxBlurPixels = 200; + await frames(3); + const w = await maxTransition(); + console.log('[MotionBlur] moving: transition', w, 'px, expected ≈', pxPerFrame.toFixed(1)); + expect(pxPerFrame > 5).tobe(true); + expect(w >= pxPerFrame * 0.5 && w <= pxPerFrame * 1.6 + 2).tobe(true); +}) + +await test('intensity scales the smear; 0 turns it off while the camera keeps moving', async () => { + blur.intensity = 2; + await frames(3); + const twice = await maxTransition(); + blur.intensity = 0; + await frames(3); + const off = await maxTransition(); + console.log('[MotionBlur] intensity 2 →', twice, 'px; intensity 0 →', off, 'px'); + expect(twice > pxPerFrame * 1.2).tobe(true); + expect(off <= 2).tobe(true); +}) + +await test('maxBlurPixels clamps the smear', async () => { + blur.intensity = 2; blur.maxBlurPixels = 3; + await frames(3); + const clamped = await maxTransition(); + console.log('[MotionBlur] clamp 3 px →', clamped, 'px'); + expect(clamped <= 5).tobe(true); + blur.maxBlurPixels = 64; +}) + +await test('stopping the camera restores a sharp image; removePost clears the flag', async () => { + step = 0; + blur.intensity = 1; + await frames(3); + expect((await transitionWidth()).width <= 2).tobe(true); + post.removePost(MotionBlurPost); + await frames(1); + expect(engine.setting.render.postProcessing.motionBlur.enable).tobe(false); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/PostEffects_SSR.test.ts b/test/components/PostEffects_SSR.test.ts index d1a64be5a..de747615a 100644 --- a/test/components/PostEffects_SSR.test.ts +++ b/test/components/PostEffects_SSR.test.ts @@ -17,7 +17,9 @@ await test('Post SSR test', async () => { // finalTexture is created lazily inside SSRPost.render(); poll // instead of racing a fixed delay against the RAF tick. - await waitUntil(() => ssr.finalTexture) + await waitUntil(() => ssr.finalTexture, 15000) + // Same resize race as GTAO/TAA: wait until the post has followed the canvas. + await waitUntil(() => ssr.finalTexture.width === engine.context3D.presentationSize[0], 15000) let dest = engine.context3D.presentationSize[0]; let src = ssr.finalTexture?.width; expect(src).tobe(dest) diff --git a/test/components/PostEffects_TAA.test.ts b/test/components/PostEffects_TAA.test.ts index 60980f8a8..1db9c8af6 100644 --- a/test/components/PostEffects_TAA.test.ts +++ b/test/components/PostEffects_TAA.test.ts @@ -1,4 +1,4 @@ -import { test, expect, end, delay } from '../util' +import { test, expect, end, waitUntil } from '../util' import { Camera3D, CameraUtil, Engine3D, Object3D, PostProcessingComponent, Scene3D, TAAPost, View3D } from '@orillusion/core'; await test('Post TAAPost test', async () => { @@ -12,8 +12,12 @@ await test('Post TAAPost test', async () => { let postProcessing = view.scene.addComponent(PostProcessingComponent); let taa = postProcessing.addPost(TAAPost); - await delay(500) + // taaTexture is created lazily on the first rendered frame and the + // engine runs at 2 fps here, so a fixed 500 ms delay raced the very + // first tick (and the ResizeObserver-driven resize that follows it). + // Poll for the state we actually assert on instead. let dest = Math.floor(window.innerWidth * window.devicePixelRatio); + await waitUntil(() => taa.taaTexture?.width === dest, 15000) let src = taa.taaTexture?.width; expect(src).tobe(dest) Engine3D.pause() diff --git a/test/components/PostEffects_Tonemap.test.ts b/test/components/PostEffects_Tonemap.test.ts new file mode 100644 index 000000000..e6f9860a7 --- /dev/null +++ b/test/components/PostEffects_Tonemap.test.ts @@ -0,0 +1,137 @@ +import { test, expect, end, waitUntil, frames } from '../util' +import { BoxGeometry, CameraUtil, Color, Engine3D, MeshRenderer, Object3D, Scene3D, TonemapMode, TonemapUtil, UnLitMaterial, Vector3, View3D } from '@orillusion/core'; + +const near = (a: number, b: number, eps: number) => Math.abs(a - b) <= eps; + +await test('TonemapUtil: selector table and known curve values', async () => { + expect(TonemapUtil.MODES.map(m => TonemapUtil.modeIndex(m))).toEqual([0, 1, 2, 3, 4, 5]); + expect(TonemapUtil.modeIndex('bogus')).tobe(1); // unknown → ACES + expect(TonemapUtil.modeIndex(undefined)).tobe(1); + expect(TonemapUtil.apply('None', [2, 0.5, 0.1], 2)).toEqual([4, 1, 0.2]); + expect(TonemapUtil.apply('ACES', [1, 1, 1])[0]).toSubequal(2.54 / 3.16, 1e-6); + expect(TonemapUtil.apply('Reinhard', [4, 4, 4], 1, 4)[0]).toSubequal(1, 1e-6); // white point → 1 + expect(TonemapUtil.apply('Reinhard', [1, 1, 1], 1, 1e6)[0]).toSubequal(0.5, 1e-4); // plain x/(1+x) + expect(TonemapUtil.apply('Uncharted2', [5.6, 5.6, 5.6])[0]).toSubequal(1, 1e-6); // 2×5.6 = W + expect(TonemapUtil.apply('Neutral', [0.5, 0.5, 0.5])[0]).toSubequal(0.46, 1e-6); // below compression: −0.04 offset only + const n = TonemapUtil.apply('Neutral', [0.5, 0.3, 0.2]); + expect(n[0] - n[1]).toSubequal(0.2, 1e-6); // hue/chroma untouched under 0.76 +}) + +await test('TonemapUtil: every curve is monotonic on a gray ramp and maps 0 → ~0', async () => { + for (const mode of TonemapUtil.MODES) { + let prev = -1; + for (let i = 0; i <= 200; i++) { + const x = i * 0.08; // 0 … 16 + const y = TonemapUtil.apply(mode, [x, x, x])[0]; + if (!(y >= prev - 1e-6)) throw new Error(`${mode} not monotonic at ${x}: ${prev} → ${y}`); + prev = y; + } + expect(Math.abs(TonemapUtil.apply(mode, [0, 0, 0])[0]) < 0.02).tobe(true); + } + // Display-referred curves stay inside [0,1] even for absurd inputs. + for (const mode of ['ACES', 'AgX', 'Neutral'] as TonemapMode[]) { + const y = TonemapUtil.apply(mode, [1000, 1000, 1000]); + expect(y[0] <= 1.04 && y[0] > 0.9).tobe(true); + } + // AgX desaturates a very bright pure red toward white instead of clipping to (1,0,0). + const agx = TonemapUtil.apply('AgX', [50, 0, 0]); + expect(agx[1] > 0.3 && agx[2] > 0.3).tobe(true); +}) + +// ---- GPU: the WGSL curves must match the CPU mirror ------------------------ + +const engine = await Engine3D.init({ canvasConfig: { devicePixelRatio: 1 } }); +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +view.camera.perspective(60, engine.aspect, 0.1, 100); +view.camera.lookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0)); +// A wall that fills the whole view with one HDR color. +const wall = new Object3D(); +const mr = wall.addComponent(MeshRenderer); +mr.geometry = new BoxGeometry(200, 200, 1); +const mat = new UnLitMaterial(); +mat.baseColor = new Color(3.0, 1.0, 0.2, 1); +mr.material = mat; +view.scene.addChild(wall); +engine.startRenderView(view); + +function halfToFloat(h: number): number { + const s = (h & 0x8000) ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff; + if (e === 0) return s * Math.pow(2, -14) * (f / 1024); + if (e === 31) return f ? NaN : s * Infinity; + return s * Math.pow(2, e - 15) * (1 + f / 1024); +} + +function tonemapPost(): any { + const job: any = engine.getRenderJob(view); + return job?.graph?.getPass('PostPass')?.postList?.get('TonemapPost'); +} + +async function readCenter(): Promise<[number, number, number]> { + const post = tonemapPost(); + const tex: GPUTexture = post.renderTexture.getGPUTexture(); + const device = engine.context3D.device; + const buf = device.createBuffer({ size: 256, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + const enc = device.createCommandEncoder(); + enc.copyTextureToBuffer( + { texture: tex, origin: { x: tex.width >> 1, y: tex.height >> 1 } }, + { buffer: buf, bytesPerRow: 256 }, + { width: 1, height: 1 }); + device.queue.submit([enc.finish()]); + await buf.mapAsync(GPUMapMode.READ); + const u16 = new Uint16Array(buf.getMappedRange().slice(0, 8)); + buf.unmap(); buf.destroy(); + return [halfToFloat(u16[0]), halfToFloat(u16[1]), halfToFloat(u16[2])]; +} + +await test('TonemapPost is attached by default and renders an rgba16float target', async () => { + await waitUntil(() => tonemapPost()?.renderTexture, 15000); + const post = tonemapPost(); + expect(post != null).tobe(true); + expect(post.renderTexture.getGPUTexture().format).tobe('rgba16float'); +}) + +let hdr: [number, number, number] = [0, 0, 0]; +await test("'None' passes the HDR scene color through (values above 1 survive)", async () => { + const tm = engine.setting.render.tonemap; + tm.mode = 'None'; tm.exposure = 1; + await frames(); + hdr = await readCenter(); + console.log('[Tonemap] scene-linear input at center:', hdr.map(v => v.toFixed(4)).join(', ')); + expect(hdr[0] > 1.5).tobe(true); // really HDR, not clamped upstream + expect(hdr[0] > hdr[1] && hdr[1] > hdr[2]).tobe(true); +}) + +for (const mode of ['ACES', 'Reinhard', 'Uncharted2', 'AgX', 'Neutral'] as TonemapMode[]) { + await test(`GPU '${mode}' matches TonemapUtil.apply (exposure 1 and 0.5)`, async () => { + const tm = engine.setting.render.tonemap; + for (const exposure of [1, 0.5]) { + tm.mode = mode; tm.exposure = exposure; tm.whitePoint = 4; + await frames(); + const gpu = await readCenter(); + const cpu = TonemapUtil.apply(mode, hdr, exposure, 4); + console.log(`[Tonemap] ${mode} e=${exposure} gpu=(${gpu.map(v => v.toFixed(4))}) cpu=(${cpu.map(v => v.toFixed(4))})`); + for (let i = 0; i < 3; i++) { + if (!near(gpu[i], cpu[i], 0.01)) throw new Error(`${mode} e=${exposure} ch${i}: gpu ${gpu[i]} vs cpu ${cpu[i]}`); + } + } + }) +} + +await test('whitePoint drives Reinhard (higher white point → darker highlights)', async () => { + const tm = engine.setting.render.tonemap; + tm.mode = 'Reinhard'; tm.exposure = 1; tm.whitePoint = 2; + await frames(); + const a = await readCenter(); + const cpu = TonemapUtil.apply('Reinhard', hdr, 1, 2); + expect(near(a[0], cpu[0], 0.01)).tobe(true); + tm.whitePoint = 16; + await frames(); + const b = await readCenter(); + expect(b[0] < a[0]).tobe(true); // higher white point → darker highlights + tm.mode = 'ACES'; tm.whitePoint = 4; +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/components/Texture.test.ts b/test/components/Texture.test.ts index 9adcd90cb..2b6fc4883 100644 --- a/test/components/Texture.test.ts +++ b/test/components/Texture.test.ts @@ -48,4 +48,21 @@ await test('textureCube create SolidColorSky', async () => { }) +await test('loadTexture from a base64 data URI (decoded via Blob, no .decode dependency)', async () => { + const make = (w: number, h: number) => { + const c = document.createElement('canvas'); c.width = w; c.height = h; + const g = c.getContext('2d'); g.fillStyle = '#ff8000'; g.fillRect(0, 0, w, h); + return c.toDataURL('image/png'); + }; + const withTimeout = (p: Promise) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('base64 texture load hung')), 8000))]); + const big = await withTimeout(engine.res.loadTexture(make(64, 48))); + expect(big.width).tobe(64); expect(big.height).tobe(48); + expect(!!big.getGPUTexture()).tobe(true); + const tiny = await withTimeout(engine.res.loadTexture(make(2, 2))); + expect(tiny.width).tobe(32); expect(tiny.height).tobe(32); // tiny images are upsized to the 32 px minimum + const uri = make(40, 40); + const a = await withTimeout(engine.res.loadTexture(uri)), b = await withTimeout(engine.res.loadTexture(uri)); + expect(a === b).tobe(true); // pooled by URL +}) + setTimeout(end, 500) diff --git a/test/components/WaterRenderer.test.ts b/test/components/WaterRenderer.test.ts new file mode 100644 index 000000000..46107d353 --- /dev/null +++ b/test/components/WaterRenderer.test.ts @@ -0,0 +1,401 @@ +import { test, end, expect, delay, waitUntil, frames } from '../util' +import { Engine3D, Scene3D, View3D, Camera3D, Object3D, WaterRenderer, WaterMaterial, Vector2, Vector3, DirectLight, GeometryBase, VertexAttributeName, WaterSpectrum } from '@orillusion/core' + +/** Height (g) and Jacobian-related stats of an rgba16float texture's channel, read back from the GPU. */ +async function channelStats(engine: Engine3D, texture: any, channel: number) { + const device = engine.context3D.device as GPUDevice + const g = texture.getGPUTexture() as GPUTexture + const bpr = Math.ceil(g.width * 8 / 256) * 256 + const buf = device.createBuffer({ size: bpr * g.height, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }) + const enc = device.createCommandEncoder() + enc.copyTextureToBuffer({ texture: g }, { buffer: buf, bytesPerRow: bpr }, [g.width, g.height, 1]) + device.queue.submit([enc.finish()]) + await buf.mapAsync(GPUMapMode.READ) + const u16 = new Uint16Array(buf.getMappedRange().slice(0)) + buf.unmap() + buf.destroy() + const half = (h: number) => { + const e = (h >> 10) & 31, m = h & 1023 + const v = e === 0 ? m / 1024 * 2 ** -14 : (1 + m / 1024) * 2 ** (e - 15) + return h >> 15 ? -v : v + } + let sum = 0, sq = 0, n = 0 + for (let y = 0; y < g.height; y++) { + for (let x = 0; x < g.width; x++) { + const v = half(u16[(y * bpr) / 2 + x * 4 + channel]) + sum += v + sq += v * v + n++ + } + } + const mean = sum / n + return { mean, rms: Math.sqrt(sq / n - mean * mean) } +} + +/** Flat disc in the xz plane: a center vertex and rings of segments. */ +function discGeometry(radius: number, rings = 16, segments = 48) { + const count = 1 + rings * segments + const pos = new Float32Array(count * 3) + const nor = new Float32Array(count * 3) + const uv = new Float32Array(count * 2) + nor[1] = 1 + for (let r = 1; r <= rings; r++) { + for (let s = 0; s < segments; s++) { + const i = 1 + (r - 1) * segments + s + const a = s / segments * Math.PI * 2 + pos[i * 3] = Math.cos(a) * radius * r / rings + pos[i * 3 + 2] = Math.sin(a) * radius * r / rings + nor[i * 3 + 1] = 1 + } + } + const idx: number[] = [] + for (let s = 0; s < segments; s++) idx.push(0, 1 + (s + 1) % segments, 1 + s) + for (let r = 1; r < rings; r++) { + for (let s = 0; s < segments; s++) { + const a = 1 + (r - 1) * segments + s + const b = 1 + (r - 1) * segments + (s + 1) % segments + idx.push(a, b, a + segments, b, b + segments, a + segments) + } + } + const g = new GeometryBase() + g.setIndices(new Uint16Array(idx)) + g.setAttribute(VertexAttributeName.position, pos) + g.setAttribute(VertexAttributeName.normal, nor) + g.setAttribute(VertexAttributeName.uv, uv) + g.setAttribute(VertexAttributeName.TEXCOORD_1, uv) + g.addSubGeometry({ indexStart: 0, indexCount: idx.length, vertexStart: 0, vertexCount: 0, firstStart: 0, index: 0, topology: 0 }) + return g +} + +async function createView(render: any = {}) { + const engine = await Engine3D.init({ setting: { render } }) + const scene = new Scene3D() + const cameraObj = new Object3D() + const camera = cameraObj.addComponent(Camera3D) + camera.perspective(60, engine.aspect, 0.1, 200) + cameraObj.y = 5 + cameraObj.z = -12 + cameraObj.rotationX = 20 + scene.addChild(cameraObj) + const view = new View3D() + view.scene = scene + view.camera = camera + engine.startRenderView(view) + return { engine, scene, view, cameraObj } +} + +await test('WaterRenderer renders and animates without errors', async () => { + const { engine, scene } = await createView() + const obj = new Object3D() + obj.y = 1 + const water = obj.addComponent(WaterRenderer) + water.width = 8 + water.length = 6 + water.resolution = 64 + scene.addChild(obj) + expect(water.waterMaterial instanceof WaterMaterial).toEqual(true) + expect(water.waterMaterial.transmissionFactor).toEqual(1) + await frames(1) + expect(water.time > 0).toEqual(true) + water.timeScale = 0 + const t = water.time + await frames(1) + expect(water.time).toEqual(t) + engine.dispose() +}) + +await test('setting.render.water adds SceneLinearDepthPass between the pyramid and transmission', async () => { + const off = await createView() + expect(off.view.renderGraph!.getPass('SceneLinearDepthPass') == null).toEqual(true) + off.engine.dispose() + + const { engine, scene, view } = await createView({ water: true }) + const order = (view.renderGraph as any)._compiled as string[] + const at = (name: string) => order.indexOf(name) + expect(at('SceneLinearDepthPass') > at('SceneColorPyramidPass')).toEqual(true) + expect(at('SceneLinearDepthPass') < at('TransmissionOpaquePass')).toEqual(true) + expect(at('CausticsPass') > at('SkyPass')).toEqual(true) + expect(at('CausticsPass') < at('SceneColorPyramidPass')).toEqual(true) + expect(at('WaterSimulationPass') < at('CausticsPass')).toEqual(true) + expect(at('WaterSimulationPass') < at('TransmissionOpaquePass')).toEqual(true) + expect(at('UnderwaterPass') > at('SortedTransparentPass')).toEqual(true) + expect(at('UnderwaterPass') < at('PostPass')).toEqual(true) + const obj = new Object3D() + obj.addComponent(WaterRenderer) + scene.addChild(obj) + await delay(300) + engine.dispose() +}) + +await test('WaterRenderer.getHeight follows the Gerstner surface', async () => { + const { engine, scene } = await createView() + const obj = new Object3D() + obj.y = 2 + const water = obj.addComponent(WaterRenderer) + scene.addChild(obj) + await delay(50) + + // Flat water: the surface is the owner's height. + water.waves = [] + expect(Math.abs(water.getHeight(1.3, -0.7) - 2) < 1e-6).toEqual(true) + + // One wave: height stays within its amplitude, and moves with time. + water.waves = [{ direction: new Vector2(1, 0), wavelength: 4, steepness: 0.3 }] + const amplitude = 0.3 / (2 * Math.PI / 4) + water.timeScale = 0 + water.time = 0 + let min = Infinity, max = -Infinity + for (let x = -4; x <= 4; x += 0.1) { + const h = water.getHeight(x, 0) - 2 + min = Math.min(min, h) + max = Math.max(max, h) + } + expect(max <= amplitude + 1e-4 && min >= -amplitude - 1e-4).toEqual(true) + expect(max - min > amplitude).toEqual(true) + const h0 = water.getHeight(0.5, 0) + water.time = 0.7 + expect(Math.abs(water.getHeight(0.5, 0) - h0) > 1e-3).toEqual(true) + engine.dispose() +}) + +await test('WaterRenderer.isUnderwater checks the footprint and the surface', async () => { + const { engine, scene } = await createView() + const obj = new Object3D() + obj.x = 10 + obj.y = 1 + const water = obj.addComponent(WaterRenderer) + water.width = 4 + water.length = 2 + water.waves = [] + scene.addChild(obj) + await delay(50) + + expect(water.containsXZ(11.9, 0.9)).toEqual(true) + expect(water.containsXZ(12.1, 0)).toEqual(false) + expect(water.containsXZ(10, -1.1)).toEqual(false) + expect(water.isUnderwater(new Vector3(10, 0.9, 0))).toEqual(true) + expect(water.isUnderwater(new Vector3(10, 1.1, 0))).toEqual(false) + // Below the surface height but outside the footprint. + expect(water.isUnderwater(new Vector3(0, 0, 0))).toEqual(false) + expect(water.containsXZ(12.4, 0, 0.5)).toEqual(true) + + // Rotated a quarter turn and scaled: half extents are 4 * 2 / 2 along z and 2 * 3 / 2 along x. + obj.rotationY = 90 + obj.scaleX = 2 + obj.scaleZ = 3 + expect(water.containsXZ(10, 3.9)).toEqual(true) + expect(water.containsXZ(10, 4.1)).toEqual(false) + expect(water.containsXZ(12.9, 0)).toEqual(true) + expect(water.containsXZ(13.1, 0)).toEqual(false) + expect(water.containsXZ(13.4, 0, 0.5)).toEqual(true) + engine.dispose() +}) + +for (const extra of [{}, { msaa: 4 }, { useLogDepth: true }, { zPrePass: false }, { zPrePass: false, msaa: 4 }]) await test(`UnderwaterPass renders with the camera at and below the surface ${JSON.stringify(extra)}`, async () => { + const { engine, scene, cameraObj } = await createView({ water: true, ...extra }) + const obj = new Object3D() + const water = obj.addComponent(WaterRenderer) + water.width = 30 + water.length = 30 + scene.addChild(obj) + // A sun, so the caustics pass draws too. + const sun = new Object3D() + sun.rotationX = 50 + sun.addComponent(DirectLight) + scene.addChild(sun) + // A second, rotated surface overlapping the first. + const obj2 = new Object3D() + obj2.y = -0.5 + obj2.rotationY = 30 + const water2 = obj2.addComponent(WaterRenderer) + water2.width = 10 + water2.length = 40 + scene.addChild(obj2) + cameraObj.rotationX = 0 + for (const y of [0, -1]) { + cameraObj.y = y + await delay(150) + } + water.caustics = false + water2.caustics = false + await delay(100) + expect(water.isUnderwater(new Vector3(0, -1, -12))).toEqual(true) + engine.dispose() +}) + +await test('WaterRenderer.surfaceGeometry follows a custom outline', async () => { + const { engine, scene } = await createView() + const obj = new Object3D() + obj.x = 10 + obj.y = 1 + const water = obj.addComponent(WaterRenderer) + water.waves = [] + scene.addChild(obj) + await delay(50) + + water.surfaceGeometry = discGeometry(3) + expect(water.geometry === water.surfaceGeometry).toEqual(true) + // Inside the disc; inside its bounding square but outside the disc. + expect(water.containsXZ(12.5, 0)).toEqual(true) + expect(water.containsXZ(12.5, 2.5)).toEqual(false) + expect(water.containsXZ(13.2, 0)).toEqual(false) + expect(water.containsXZ(13.2, 0, 0.5)).toEqual(true) + expect(water.isUnderwater(new Vector3(10, 0.5, 1))).toEqual(true) + expect(water.isUnderwater(new Vector3(12.5, 0.5, 2.5))).toEqual(false) + // Rectangle settings no longer rebuild the mesh. + water.width = 30 + expect(water.geometry === water.surfaceGeometry).toEqual(true) + + // Scaled along x and rotated a quarter turn: radius 6 along world z, still 3 along world x. + obj.scaleX = 2 + obj.rotationY = 90 + expect(water.containsXZ(10, 5.5)).toEqual(true) + expect(water.containsXZ(12.5, 0)).toEqual(true) + expect(water.containsXZ(13.2, 0)).toEqual(false) + + water.surfaceGeometry = null + expect(water.footprint == null).toEqual(true) + expect(water.containsXZ(12.5, 2.5)).toEqual(true) + engine.dispose() +}) + +for (const extra of [{}, { zPrePass: false, msaa: 4 }]) await test(`custom surface renders underwater and with caustics ${JSON.stringify(extra)}`, async () => { + const { engine, scene, cameraObj } = await createView({ water: true, ...extra }) + const sun = new Object3D() + sun.rotationX = 50 + sun.addComponent(DirectLight) + scene.addChild(sun) + const obj = new Object3D() + obj.z = -10 + const water = obj.addComponent(WaterRenderer) + water.surfaceGeometry = discGeometry(6, 24, 96) + scene.addChild(obj) + const floor = new Object3D() + floor.y = -2 + floor.addComponent(WaterRenderer).waves = [] + scene.addChild(floor) + cameraObj.rotationX = 0 + for (const y of [1, -1]) { + cameraObj.y = y + await delay(150) + } + expect(water.footprint!.triangleCount > 0).toEqual(true) + engine.dispose() +}) + +await test('addRipple starts the ripple simulation; points off the water are ignored', async () => { + const { engine, scene } = await createView({ water: true }) + const obj = new Object3D() + const water = obj.addComponent(WaterRenderer) + water.width = 8 + water.length = 6 + scene.addChild(obj) + await delay(100) + expect(water.hasRipples).toEqual(false) + water.addRipple(20, 0) + await delay(100) + expect(water.hasRipples).toEqual(false) + water.addRipple(1, 1, 0.1, 0.3) + expect(await waitUntil(() => water.hasRipples)).toEqual(true) + // A new footprint clears them; the next ripple starts a fresh simulation. + water.width = 10 + expect(water.hasRipples).toEqual(false) + engine.dispose() +}) + +for (const extra of [{}, { useLogDepth: true }, { zPrePass: false, msaa: 4 }]) await test(`ripples render on rectangle and custom surfaces ${JSON.stringify(extra)}`, async () => { + const { engine, scene, cameraObj } = await createView({ water: true, ...extra }) + const sun = new Object3D() + sun.rotationX = 50 + sun.addComponent(DirectLight) + scene.addChild(sun) + const rect = new Object3D() + const water = rect.addComponent(WaterRenderer) + water.width = 30 + water.length = 30 + scene.addChild(rect) + const pond = new Object3D() + pond.y = 0.5 + pond.z = 10 + const pondWater = pond.addComponent(WaterRenderer) + pondWater.surfaceGeometry = discGeometry(4, 16, 64) + scene.addChild(pond) + for (let i = 0; i < 5; i++) { + water.addRipple(i - 2, 0, 0.1, 0.3) + pondWater.addRipple(0, 10 + i * 0.5, 0.1, 0.3) + cameraObj.y = i % 2 ? -1 : 3 + await delay(80) + } + await frames(1) + expect(water.hasRipples && pondWater.hasRipples).toEqual(true) + engine.dispose() +}) + +await test('WaterSpectrum: FFT cascades have the expected height statistics and follow the wind', async () => { + const { engine, scene } = await createView({ water: true }) + const obj = new Object3D() + const water = obj.addComponent(WaterRenderer) + water.waves = [] + const spectrum = new WaterSpectrum() + water.spectrum = spectrum + scene.addChild(obj) + expect(await waitUntil(() => water.fft, 30000) != null).toEqual(true) + await frames(1) + // Paused while reading back, so each read waits only for the frames already submitted. + engine.pause() + + // 10 m/s over 100 km: significant height about 1.6 m, most of it in the first cascade. + const height = await channelStats(engine, water.fft!.displacement[0], 1) + expect(Math.abs(height.mean) < 0.05).toEqual(true) + expect(height.rms > 0.25 && height.rms < 0.9).toEqual(true) + const fine = await channelStats(engine, water.fft!.displacement[2], 1) + expect(fine.rms < height.rms * 0.1).toEqual(true) + // The foam map's Jacobian averages about 1: the waves move water around, not away. + const jacobian = await channelStats(engine, water.fft!.foam, 1) + expect(Math.abs(jacobian.mean - 1) < 0.1).toEqual(true) + + // Half the wind rebuilds the spectrum with about half the height (fetch-limited seas grow with the wind). + spectrum.windSpeed = 5 + engine.resume() + await frames(1) + engine.pause() + const calm = await channelStats(engine, water.fft!.displacement[0], 1) + expect(calm.rms < height.rms * 0.7).toEqual(true) + + // getHeight picks up the FFT waves once a query has been read back. + water.getHeight(3, 4) + engine.resume() + await frames(1) + engine.pause() + const h = await waitUntil(() => water.getHeight(3, 4), 30000) + expect(h !== 0 && Math.abs(h) < 3).toEqual(true) + + water.spectrum = null + expect(water.fft == null).toEqual(true) + engine.dispose() +}) + +for (const extra of [{}, { useLogDepth: true }, { zPrePass: false, msaa: 4 }]) await test(`FFT ocean renders above and under the surface ${JSON.stringify(extra)}`, async () => { + const { engine, scene, cameraObj } = await createView({ water: true, ...extra }) + const sun = new Object3D() + sun.rotationX = 30 + sun.addComponent(DirectLight) + scene.addChild(sun) + const obj = new Object3D() + const water = obj.addComponent(WaterRenderer) + water.width = 200 + water.length = 200 + water.resolution = 256 + water.spectrum = new WaterSpectrum() + scene.addChild(obj) + cameraObj.rotationX = 0 + for (const y of [8, -3]) { + cameraObj.y = y + await delay(200) + } + await frames(1) + expect(water.hasSimulation).toEqual(true) + engine.dispose() +}) + +setTimeout(end, 500) diff --git a/test/graph/FluidPass.test.ts b/test/graph/FluidPass.test.ts new file mode 100644 index 000000000..093975335 --- /dev/null +++ b/test/graph/FluidPass.test.ts @@ -0,0 +1,160 @@ +import { test, end, expect, delay } from '../util' +import { Engine3D, Scene3D, View3D, Camera3D, Object3D, FluidRenderer, FluidPass, FluidDebug, FluidDepthFilter, FluidThicknessMode } from '@orillusion/core' + +async function createView(render: any, canvas?: HTMLCanvasElement) { + const engine = await Engine3D.init({ setting: { render }, ...(canvas ? { canvasConfig: { canvas, devicePixelRatio: 1 } } : {}) }) + const scene = new Scene3D() + const cameraObj = new Object3D() + const camera = cameraObj.addComponent(Camera3D) + camera.perspective(60, engine.aspect, 0.1, 100) + cameraObj.z = -5 + scene.addChild(cameraObj) + const view = new View3D() + view.scene = scene + view.camera = camera + engine.startRenderView(view) + return { engine, scene, view } +} + +function compiledOrder(view: View3D): string[] { + return (view.renderGraph as any)._compiled as string[] +} + +await test('FluidPass is absent unless setting.render.fluid is on', async () => { + const { engine, view } = await createView({}) + expect(view.renderGraph!.getPass('FluidPass') == null).toEqual(true) + engine.dispose() +}) + +await test('FluidPass runs after the opaque half and before transparents', async () => { + const { engine, view } = await createView({ fluid: true, decals: true }) + expect(view.renderGraph!.getPass('FluidPass') instanceof FluidPass).toEqual(true) + const order = compiledOrder(view) + const at = (name: string) => order.indexOf(name) + expect(at('FluidPass') > at('TransmissionOpaquePass')).toEqual(true) + expect(at('FluidPass') > at('DecalShadowVolumePass')).toEqual(true) + expect(at('FluidPass') < at('SortedTransparentPass')).toEqual(true) + engine.dispose() +}) + +await test('FluidRenderer renders CPU particles without errors', async () => { + const { engine, scene } = await createView({ fluid: true }) + const obj = new Object3D() + const fluid = obj.addComponent(FluidRenderer) + const data = new Float32Array(64 * 4) + for (let i = 0; i < 64; i++) data.set([(i % 4) * 0.2, Math.floor(i / 16) * 0.2, (Math.floor(i / 4) % 4) * 0.2, 1], i * 4) + fluid.setDataBuffer(data) + scene.addChild(obj) + expect(fluid.particleCount).toEqual(64) + await delay(250) + data[0] = 1 + fluid.setDataBuffer(data, 32) + expect(fluid.particleCount).toEqual(32) + await delay(100) + // Reduced-size maps, divided blur targets and every debug view. + fluid.depthMapSize = 256 + fluid.thicknessMapSize = 128 + fluid.blurDepthSizeDivisor = 2 + fluid.blurThicknessSizeDivisor = 2 + fluid.debug = true + for (const mode of [FluidDebug.DepthTexture, FluidDebug.ThicknessTexture, FluidDebug.ThicknessBlurredTexture, FluidDebug.Normals]) { + fluid.debugFeature = mode + await delay(50) + } + engine.dispose() +}) + +await test('FluidPass composites with fixed thickness, no environment, stencil depth and log depth', async () => { + for (const render of [{ fluid: true, useStencil: true, zPrePass: false }, { fluid: true, useLogDepth: true }]) { + const { engine, scene } = await createView(render) + const obj = new Object3D() + const fluid = obj.addComponent(FluidRenderer) + const data = new Float32Array(27 * 4) + for (let i = 0; i < 27; i++) data.set([(i % 3) * 0.1, Math.floor(i / 9) * 0.1, (Math.floor(i / 3) % 3) * 0.1, 1], i * 4) + fluid.setDataBuffer(data) + scene.addChild(obj) + await delay(150) + fluid.useFixedThickness = true + fluid.minimumThickness = 0.5 + fluid.environmentMap = null + await delay(150) + engine.dispose() + } +}) + +await test('FluidPass renders anisotropic ellipsoids with the narrow-range filter', async () => { + const { engine, scene } = await createView({ fluid: true }) + const obj = new Object3D() + const fluid = obj.addComponent(FluidRenderer) + // A thin 12 x 12 x 2 slab: interior particles become flat ellipsoids, corner ones stay near spheres. + const n = 12 * 12 * 2 + const data = new Float32Array(n * 4) + for (let i = 0; i < n; i++) data.set([(i % 12) * 0.05, Math.floor(i / 144) * 0.05, (Math.floor(i / 12) % 12) * 0.05, 1], i * 4) + fluid.setDataBuffer(data) + fluid.depthFilter = FluidDepthFilter.NarrowRange + fluid.useAnisotropy = true + fluid.edgeSoftness = 5 + scene.addChild(obj) + await delay(200) + // More particles than the first allocation regrows the neighbor-search buffers. + const more = new Float32Array(n * 8) + more.set(data) + for (let i = n; i < 2 * n; i++) more.set([data[(i - n) * 4], 0.1 + data[(i - n) * 4 + 1], data[(i - n) * 4 + 2], 1], i * 4) + fluid.setDataBuffer(more) + fluid.debug = true + fluid.debugFeature = FluidDebug.Normals + await delay(200) + // Geometric thickness: back-depth stage on the ellipsoids, then far - near. + fluid.debug = false + fluid.thicknessMode = FluidThicknessMode.Geometric + await delay(150) + fluid.thicknessMode = '0' as any + expect(fluid.thicknessMode === FluidThicknessMode.Accumulated).toEqual(true) + fluid.useAnisotropy = false + fluid.thicknessMode = FluidThicknessMode.Geometric + await delay(150) + fluid.depthFilter = '0' as any + expect(fluid.depthFilter === FluidDepthFilter.Bilateral).toEqual(true) + await delay(100) + engine.dispose() +}) + +await test('FluidPass runs in two engines at once', async () => { + const instances = [] + for (let k = 0; k < 2; k++) { + const canvas = document.createElement('canvas') + canvas.width = 160 + canvas.height = 120 + document.body.appendChild(canvas) + const inst = await createView({ fluid: true }, canvas) + const obj = new Object3D() + const fluid = obj.addComponent(FluidRenderer) + fluid.setDataBuffer(new Float32Array([0, 0, 0, 1, 0.1, 0, 0, 1, 0, 0.1, 0, 1])) + inst.scene.addChild(obj) + instances.push({ ...inst, canvas }) + } + await delay(250) + for (const { engine, canvas } of instances) { + engine.dispose() + canvas.remove() + } +}) + +await test('FluidRenderer data layout', async () => { + const fluid = new FluidRenderer() + fluid.setDataBuffer(new Float32Array(30), undefined, { stride: 12 }) + expect(fluid.particleCount).toEqual(10) + fluid.setDataBuffer(new Float32Array(32), undefined, { stride: 32, positionOffset: 16 }) + expect(fluid.particleCount).toEqual(4) + let threw = false + try { fluid.setDataBuffer(new Float32Array(8), undefined, { stride: 16, positionOffset: 8 }) } catch { threw = true } + expect(threw).toEqual(true) +}) + +await test('FluidRenderer.debugFeature accepts GUI string values', async () => { + const fluid = new FluidRenderer() + fluid.debugFeature = '4' as any + expect(fluid.debugFeature === FluidDebug.Normals).toEqual(true) +}) + +setTimeout(end, 500) diff --git a/test/math/Box2.test.ts b/test/math/Box2.test.ts new file mode 100644 index 000000000..d30747bef --- /dev/null +++ b/test/math/Box2.test.ts @@ -0,0 +1,50 @@ +import { test, expect, end } from '../util' +import { Box2, Vector2 } from '@orillusion/core'; + +const v = (x: number, y: number) => new Vector2(x, y); + +await test('Box2: empty by default, grows from points', async () => { + const b = new Box2(); + expect(b.isEmpty()).tobe(true); + expect(b.getSize().x).tobe(0); + b.setFromPoints([v(1, 5), v(-2, 3), v(4, -1)]); + expect(b.isEmpty()).tobe(false); + expect([b.min.x, b.min.y, b.max.x, b.max.y]).toEqual([-2, -1, 4, 5]); + expect(b.getCenter().x).tobe(1); expect(b.getCenter().y).tobe(2); + expect(b.getSize().x).tobe(6); expect(b.getSize().y).tobe(6); + expect(new Box2(v(2, 2), v(2, 2)).isEmpty()).tobe(false); // a single point is not empty +}) + +await test('Box2: contains / intersects / distance / clamp / parameter', async () => { + const b = new Box2(v(0, 0), v(10, 4)); + expect(b.containsPoint(v(10, 4))).tobe(true); // inclusive edges + expect(b.containsPoint(v(10.01, 4))).tobe(false); + expect(b.containsBox(new Box2(v(1, 1), v(9, 3)))).tobe(true); + expect(b.containsBox(new Box2(v(1, 1), v(11, 3)))).tobe(false); + expect(b.intersectsBox(new Box2(v(10, 4), v(12, 6)))).tobe(true); // touching counts + expect(b.intersectsBox(new Box2(v(10.1, 0), v(12, 6)))).tobe(false); + expect(b.distanceToPoint(v(5, 2))).tobe(0); + expect(b.distanceToPoint(v(13, 8))).toSubequal(5, 1e-12); // 3-4-5 + const c = b.clampPoint(v(-3, 9)); + expect(c.x).tobe(0); expect(c.y).tobe(4); + const p = b.getParameter(v(2.5, 1)); + expect(p.x).tobe(0.25); expect(p.y).tobe(0.25); +}) + +await test('Box2: set operations and transforms', async () => { + const a = new Box2(v(0, 0), v(4, 4)), b = new Box2(v(2, 1), v(6, 3)); + const i = a.clone().intersect(b); + expect([i.min.x, i.min.y, i.max.x, i.max.y]).toEqual([2, 1, 4, 3]); + const u = a.clone().union(b); + expect([u.min.x, u.min.y, u.max.x, u.max.y]).toEqual([0, 0, 6, 4]); + expect(a.clone().intersect(new Box2(v(10, 10), v(11, 11))).isEmpty()).tobe(true); + const t = a.clone().translate(v(1, -1)).expandByScalar(1); + expect([t.min.x, t.min.y, t.max.x, t.max.y]).toEqual([0, -2, 6, 4]); + expect(a.clone().expandByVector(v(1, 2)).max.y).tobe(6); + const c = new Box2().setFromCenterAndSize(v(5, 5), v(2, 4)); + expect([c.min.x, c.min.y, c.max.x, c.max.y]).toEqual([4, 3, 6, 7]); + expect(new Box2().copy(c).equals(c)).tobe(true); + expect(c.clone().min !== c.min).tobe(true); // deep clone +}) + +setTimeout(end, 500) diff --git a/test/math/CatmullRomCurve3.test.ts b/test/math/CatmullRomCurve3.test.ts new file mode 100644 index 000000000..c97bd1a7a --- /dev/null +++ b/test/math/CatmullRomCurve3.test.ts @@ -0,0 +1,84 @@ +import { test, expect, end } from '../util' +import { CatmullRomCurve3, CatmullRomType, Vector3 } from '@orillusion/core'; + +const pts = () => [new Vector3(0, 0, 0), new Vector3(10, 4, 0), new Vector3(12, 0, 8), new Vector3(30, -3, 9), new Vector3(31, 6, -5)]; +const dist = (a: Vector3, b: Vector3) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); + +await test('passes through every control point (all three parameterizations, open and closed)', async () => { + for (const type of ['centripetal', 'chordal', 'catmullrom'] as CatmullRomType[]) { + const p = pts(); + const open = new CatmullRomCurve3(p, false, type); + for (let i = 0; i < p.length; i++) { + const q = open.getPoint(i / (p.length - 1)); + if (dist(q, p[i]) > 1e-9) throw new Error(`${type} open misses control point ${i}`); + } + const closed = new CatmullRomCurve3(p, true, type); + for (let i = 0; i < p.length; i++) { + const q = closed.getPoint(i / p.length); + if (dist(q, p[i]) > 1e-9) throw new Error(`${type} closed misses control point ${i}`); + } + expect(dist(closed.getPoint(1), p[0]) < 1e-9).tobe(true); // loop closes + } +}) + +await test('collinear evenly spaced points give a straight line of the right length', async () => { + const c = new CatmullRomCurve3([new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(2, 0, 0), new Vector3(3, 0, 0)]); + expect(c.getLength()).toSubequal(3, 1e-6); + const mid = c.getPointAt(0.5); + expect(mid.x).toSubequal(1.5, 1e-6); expect(Math.abs(mid.y) + Math.abs(mid.z) < 1e-9).tobe(true); + const t = c.getTangentAt(0.3); + expect(t.x).toSubequal(1, 1e-6); expect(Math.hypot(t.x, t.y, t.z)).toSubequal(1, 1e-9); +}) + +await test('getSpacedPoints is uniform in arc length; getPoints is not', async () => { + const c = new CatmullRomCurve3(pts()); + c.arcLengthDivisions = 2000; + const spread = (list: Vector3[]) => { + const d: number[] = []; + for (let i = 1; i < list.length; i++) d.push(dist(list[i], list[i - 1])); + return (Math.max(...d) - Math.min(...d)) / (d.reduce((a, b) => a + b, 0) / d.length); + }; + const spaced = spread(c.getSpacedPoints(40)), param = spread(c.getPoints(40)); + console.log(`[CatmullRom] chord spread: spaced ${spaced.toFixed(4)}, parametric ${param.toFixed(4)}`); + expect(spaced < 0.05).tobe(true); + expect(param > 0.5).tobe(true); // control points are unevenly spaced on purpose + expect(c.getSpacedPoints(40).length).tobe(41); + // u ↔ t mapping is monotonic and pinned at the ends. + expect(c.getUtoTmapping(0)).tobe(0); expect(c.getUtoTmapping(1)).toSubequal(1, 1e-12); + let prev = -1; + for (let i = 0; i <= 50; i++) { const t = c.getUtoTmapping(i / 50); if (t < prev) throw new Error('mapping not monotonic'); prev = t; } +}) + +await test('length: closed > open, cache follows in-place edits, tangents are unit length', async () => { + const p = pts(); + const open = new CatmullRomCurve3(p), closed = new CatmullRomCurve3(p, true); + const lo = open.getLength(); + expect(closed.getLength() > lo).tobe(true); + expect(lo > dist(p[0], p[4])).tobe(true); // longer than the straight chord + expect(open.getLengths() === open.getLengths()).tobe(true); // cached + p[2].y += 25; // mutate a control point in place + expect(open.getLength() > lo + 5).tobe(true); // table rebuilt without an explicit call + for (let i = 0; i <= 10; i++) { + const t = open.getTangent(i / 10); + expect(Math.hypot(t.x, t.y, t.z)).toSubequal(1, 1e-6); + } +}) + +await test('tension (uniform type), degenerate inputs, clone', async () => { + const p = [new Vector3(0, 0, 0), new Vector3(5, 5, 0), new Vector3(10, 0, 0)]; + const loose = new CatmullRomCurve3(p, false, 'catmullrom', 0.5), tight = new CatmullRomCurve3(p, false, 'catmullrom', 0); + // Tension 0 = zero tangents: the quarter point sits on the chord p0→p1 (0.5 on the cubic ease), not bulging past it. + const q = tight.getPoint(0.25); + expect(q.x).toSubequal(2.5, 1e-9); expect(q.y).toSubequal(2.5, 1e-9); + expect(loose.getLength() > tight.getLength()).tobe(true); + expect(new CatmullRomCurve3([]).getPoint(0.5).x).tobe(0); + const one = new CatmullRomCurve3([new Vector3(7, 8, 9)]).getPoint(0.3); + expect(one.x === 7 && one.y === 8 && one.z === 9).tobe(true); + // Repeated control points must not produce NaN. + const dup = new CatmullRomCurve3([new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0)]); + for (let i = 0; i <= 10; i++) { const d = dup.getPoint(i / 10); if (!isFinite(d.x + d.y + d.z)) throw new Error('NaN on repeated points'); } + const c = loose.clone(); + expect(c.points[1] !== loose.points[1] && c.points[1].y === 5 && c.curveType === 'catmullrom').tobe(true); +}) + +setTimeout(end, 500) diff --git a/test/math/Plane.test.ts b/test/math/Plane.test.ts index 9913cf552..2ae28ac9f 100644 --- a/test/math/Plane.test.ts +++ b/test/math/Plane.test.ts @@ -27,4 +27,17 @@ await test('Plane intersectsRay', async () => { expect(intersection.z).toSubequal(0); }) +await test('Plane intersectsRay parallel', async () => { + let plane = new Plane(Vector3.ZERO, Vector3.UP); + + // horizontal rays never reach the plane, whichever side they start on + let above = new Ray(new Vector3(0, 5, 0), new Vector3(1, 0, 0)); + let below = new Ray(new Vector3(0, -5, 0), new Vector3(1, 0, 0)); + let inside = new Ray(new Vector3(0, 0, 0), new Vector3(1, 0, 0)); + + expect(plane.intersectsRay(above, new Vector3())).toEqual(false); + expect(plane.intersectsRay(below, new Vector3())).toEqual(false); + expect(plane.intersectsRay(inside, new Vector3())).toEqual(false); +}) + setTimeout(end, 500) diff --git a/test/math/Spherical.test.ts b/test/math/Spherical.test.ts new file mode 100644 index 000000000..c1b22dc39 --- /dev/null +++ b/test/math/Spherical.test.ts @@ -0,0 +1,49 @@ +import { test, expect, end } from '../util' +import { Cylindrical, OrbitController, Spherical, Vector3 } from '@orillusion/core'; + +await test('Spherical: cartesian round trip and axis conventions', async () => { + const s = new Spherical(); + s.setFromVector3(new Vector3(0, 5, 0)); + expect(s.radius).toSubequal(5, 1e-12); expect(s.phi).toSubequal(0, 1e-12); // +Y is the pole + s.setCoords(0, 0, 3); + expect(s.phi).toSubequal(Math.PI / 2, 1e-12); expect(s.theta).toSubequal(0, 1e-12); // +Z is theta 0 + s.setCoords(2, 0, 0); + expect(s.theta).toSubequal(Math.PI / 2, 1e-12); // +X is theta 90° + for (const v of [new Vector3(1, 2, 3), new Vector3(-4, 0.5, 2), new Vector3(0.1, -7, -0.3)]) { + const out = new Spherical().setFromVector3(v).toVector3(); + expect(out.x).toSubequal(v.x, 1e-9); expect(out.y).toSubequal(v.y, 1e-9); expect(out.z).toSubequal(v.z, 1e-9); + } + expect(new Spherical().setCoords(0, 0, 0).radius).tobe(0); +}) + +await test('Spherical: makeSafe, copy/clone, getCoords scratch, three.js alias', async () => { + const s = new Spherical(2, 0, 1).makeSafe(); + expect(s.phi > 0).tobe(true); + s.phi = Math.PI; s.makeSafe(); + expect(s.phi < Math.PI).tobe(true); + const c = s.clone(); + expect(c !== s && c.radius === s.radius && c.phi === s.phi && c.theta === s.theta).tobe(true); + expect(new Spherical().copy(s).theta).tobe(1); + expect(s.getCoords() === s.coords).tobe(true); // legacy scratch-vector contract + const a = new Spherical().setFromCartesianCoords(1, 1, 1), b = new Spherical().setCoords(1, 1, 1); + expect(a.radius === b.radius && a.phi === b.phi && a.theta === b.theta).tobe(true); +}) + +await test('OrbitController exposes the public Spherical class', async () => { + // The controller used to carry a private copy of this class. + expect(typeof OrbitController).tobe('function'); + expect(Object.getOwnPropertyDescriptor(OrbitController.prototype, 'spherical') != null).tobe(true); +}) + +await test('Cylindrical: round trip and conventions', async () => { + const c = new Cylindrical().setFromVector3(new Vector3(3, 7, 0)); + expect(c.radius).toSubequal(3, 1e-12); expect(c.theta).toSubequal(Math.PI / 2, 1e-12); expect(c.y).tobe(7); + for (const v of [new Vector3(1, 2, 3), new Vector3(-4, -0.5, 2), new Vector3(0, 9, -3)]) { + const out = new Cylindrical().setFromVector3(v).toVector3(); + expect(out.x).toSubequal(v.x, 1e-9); expect(out.y).toSubequal(v.y, 1e-9); expect(out.z).toSubequal(v.z, 1e-9); + } + const k = new Cylindrical(2, 1, 5).clone(); + expect(new Cylindrical().copy(k).y).tobe(5); +}) + +setTimeout(end, 500) diff --git a/test/math/Vector2.test.ts b/test/math/Vector2.test.ts index c8a3d707b..a5e2fdfde 100644 --- a/test/math/Vector2.test.ts +++ b/test/math/Vector2.test.ts @@ -120,6 +120,18 @@ await test('Vector2 lerp / lerpVectors', async () => { expect(v2.x).toEqual(5); }) +await test('Vector2 static lerp keeps endpoint order', async () => { + const from = new Vector2(2, 3); + const to = new Vector2(10, 15); + for (const [t, x, y] of [[0, 2, 3], [0.25, 4, 6], [1, 10, 15]]) { + const result = Vector2.lerp(from, to, t); + expect(result.x).toEqual(x); + expect(result.y).toEqual(y); + } + expect(from.x).toEqual(2); + expect(to.x).toEqual(10); +}) + await test('Vector2 rotateAround', async () => { let v = new Vector2(1, 0); v.rotateAround(new Vector2(0, 0), Math.PI / 2); diff --git a/test/system/MeshBVH.test.ts b/test/system/MeshBVH.test.ts new file mode 100644 index 000000000..4d3b3263f --- /dev/null +++ b/test/system/MeshBVH.test.ts @@ -0,0 +1,299 @@ +import { test, expect, end } from '../util' +import { BoundingBox, BoundingSphere, BoxGeometry, Engine3D, GeometryBase, GeometryVertexType, Matrix4, MeshBVH, MeshColliderShape, Quaternion, Ray, SphereGeometry, Vector3, VertexAttributeName } from '@orillusion/core'; + +await Engine3D.init(); + +// Deterministic PRNG so failures reproduce. +let seed = 12345; +const rnd = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; +const randomDir = () => new Vector3(rnd() - 0.5, rnd() - 0.5, rnd() - 0.5).normalize(); + +/** Quads facing +z at the given z values, one sub-geometry each. */ +function quadStack(zs: number[], half = 1): GeometryBase { + const geo = new GeometryBase(); + const pos: number[] = [], idx: number[] = []; + zs.forEach((z, i) => { + const b = i * 4; + pos.push(-half, -half, z, half, -half, z, half, half, z, -half, half, z); + idx.push(b, b + 1, b + 2, b, b + 2, b + 3); + }); + geo.setAttribute(VertexAttributeName.position, new Float32Array(pos)); + geo.setIndices(new Uint32Array(idx)); + zs.forEach((_, i) => geo.addSubGeometry({ indexStart: i * 6, indexCount: 6, vertexStart: 0, vertexCount: 0, firstStart: 0, index: i, topology: 0 })); + return geo; +} + +await test('build stats: every triangle indexed, tree is balanced-ish', async () => { + const geo = new SphereGeometry(1, 64, 64); + const bvh = MeshBVH.get(geo); + expect(bvh.triCount).tobe(geo.getAttribute('indices').data.length / 3); + expect(bvh.nodeCount > bvh.triCount / 8).tobe(true); // more nodes than leaves-at-capacity + expect(bvh.depth < 40).tobe(true); // log2(8192)=13, midpoint split can be deeper but not pathological + expect(MeshBVH.get(geo) === bvh).tobe(true); // cached + MeshBVH.invalidate(geo); + expect(MeshBVH.has(geo)).tobe(false); +}) + +await test('500 random rays: BVH closest hit == brute force', async () => { + const geo = new SphereGeometry(2, 96, 96); + const bvh = MeshBVH.get(geo); + let hits = 0, misses = 0; + for (let i = 0; i < 500; i++) { + const o = randomDir().multiplyScalar(6); + const aim = new Vector3(rnd() * 5 - 2.5, rnd() * 5 - 2.5, rnd() * 5 - 2.5); // some rays miss the r=2 sphere + const d = new Vector3(aim.x - o.x, aim.y - o.y, aim.z - o.z).normalize(); + const a = bvh.raycast(o, d); + const at = a ? a.t : -1; + const b = bvh.raycastBruteForce(o, d); + const bt = b ? b.t : -1; + // A shared edge can legitimately report either triangle, so compare t. + expect(at).toSubequal(bt, 1e-5); + if (a) hits++; else misses++; + // Any-hit agrees with closest-hit. + expect(bvh.intersectsRay(o, d)).tobe(a != null); + } + expect(hits > 200 && misses > 50).tobe(true); +}) + +await test('closest hit is the front face; culling, near/far and inside-out rays', async () => { + const geo = new SphereGeometry(1, 32, 32); + const bvh = MeshBVH.get(geo); + const o = new Vector3(0, 0, 5), d = new Vector3(0, 0, -1); + const h = bvh.raycast(o, d); + expect(h != null).tobe(true); + expect(h.t).toSubequal(4, 2e-2); // r=1 tessellated: slightly inside the true sphere + expect(h.point.z).toSubequal(1, 2e-2); + expect(h.faceNormal.z > 0.9).tobe(true); // outward facing + expect(h.frontFace).tobe(true); + // Back-face culling keeps the front face; front-face culling skips it and finds the inside of the far side. + expect(bvh.raycast(o, d, { cull: 'back' }).t).toSubequal(4, 2e-2); + expect(bvh.raycast(o, d, { cull: true }).t).toSubequal(4, 2e-2); + const far = bvh.raycast(o, d, { cull: 'front' }); + expect(far.t).toSubequal(6, 2e-2); + expect(far.frontFace).tobe(false); + // From inside: nearest surface is a back face → culled away, visible otherwise. + const inside = new Vector3(0, 0, 0); + expect(bvh.raycast(inside, d, { cull: 'back' })).tobe(null); + expect(bvh.raycast(inside, d).t).toSubequal(1, 2e-2); + // far below the surface → miss; near past the first surface → the far side. + expect(bvh.raycast(o, d, { far: 3.5 })).tobe(null); + expect(bvh.raycast(o, d, { near: 5 }).t).toSubequal(6, 2e-2); + expect(bvh.intersectsRay(o, d, { far: 3.5 })).tobe(false); + // Away from the mesh → miss. + expect(bvh.raycast(o, new Vector3(0, 0, 1))).tobe(null); + // Results are fresh objects unless a target is passed. + const h2 = bvh.raycast(o, d); + expect(h2 !== h).tobe(true); + const tgt = bvh.raycast(new Vector3(0, 0, -5), new Vector3(0, 0, 1), undefined, h2); + expect(tgt === h2).tobe(true); + expect(h.point.z).toSubequal(1, 2e-2); +}) + +await test('raycastAll returns every crossing sorted; tree-less queries match the tree', async () => { + const geo = new SphereGeometry(1, 32, 32); + const o = new Vector3(0.1, 0.05, 5), d = new Vector3(0, 0, -1); + // No tree yet: the static queries must not build one. + const noTree = MeshBVH.raycastGeometry(geo, o, d); + const noTreeAll = MeshBVH.raycastGeometryAll(geo, o, d); + expect(MeshBVH.has(geo)).tobe(false); + const bvh = MeshBVH.get(geo); + const all = bvh.raycastAll(o, d); + expect(all.length).tobe(2); + expect(all[0].t < all[1].t).tobe(true); + expect(all[0].frontFace).tobe(true); + expect(all[1].frontFace).tobe(false); + expect(all[0].t).toSubequal(bvh.raycast(o, d).t, 1e-9); + expect(noTree.t).toSubequal(all[0].t, 1e-9); + expect(noTreeAll.length).tobe(2); + expect(noTreeAll[1].t).toSubequal(all[1].t, 1e-9); + expect(bvh.raycastAll(o, d, { cull: 'back' }).length).tobe(1); + expect(bvh.raycastAll(o, d, { far: 5 }).length).tobe(1); + // Appends to `out` without disturbing earlier entries. + const out = [all[1]]; + bvh.raycastAll(o, d, undefined, out); + expect(out.length).tobe(3); + expect(out[0] === all[1]).tobe(true); + // A ray along the shared diagonal of a quad crosses it once, not once per triangle. + const quad = new GeometryBase(); + quad.setAttribute(VertexAttributeName.position, new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0])); + quad.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3])); + const diag = new Vector3(0.25, 0.25, 4); + expect(MeshBVH.get(quad).raycastAll(diag, d).length).tobe(1); + expect(MeshBVH.raycastGeometryAll(quad, diag, d).length).tobe(1); +}) + +await test('non-indexed geometry builds and hits', async () => { + // Two triangles forming the quad z=0, [-1,1]², no index buffer. + const geo = new GeometryBase(); + geo.setAttribute(VertexAttributeName.position, new Float32Array([ + -1, -1, 0, 1, -1, 0, 1, 1, 0, + -1, -1, 0, 1, 1, 0, -1, 1, 0, + ])); + const bvh = MeshBVH.get(geo); + expect(bvh.triCount).tobe(2); + const h = bvh.raycast(new Vector3(-0.5, 0.5, 3), new Vector3(0, 0, -1)); + expect(h.t).toSubequal(3, 1e-6); + expect(h.triIndex).tobe(1); + expect(bvh.getTriangle(1)[2]).tobe(5); + expect(MeshBVH.raycastGeometry(geo, new Vector3(0.5, -0.5, 3), new Vector3(0, 0, -1)).triIndex).tobe(0); + // Indexed cube. + const box = MeshBVH.get(new BoxGeometry(2, 2, 2)); + expect(box.triCount).tobe(12); + const hb = box.raycast(new Vector3(0.3, 0.2, 10), new Vector3(0, 0, -1)); + expect(hb.t).toSubequal(9, 1e-5); + expect(hb.faceNormal.z).toSubequal(1, 1e-6); +}) + +await test('compose_bin (interleaved prefab) geometry: positions and attributes read from the packed buffer', async () => { + // [pos3, normal3, uv2] per vertex, quad at z = 2. + const v = (x: number, y: number, u: number, w: number) => [x, y, 2, 0, 0, 1, u, w]; + const data = new Float32Array([...v(-1, -1, 0, 0), ...v(1, -1, 1, 0), ...v(1, 1, 1, 1), ...v(-1, 1, 0, 1)]); + const geo = new GeometryBase(); + geo.vertexDim = 8; + geo.geometryType = GeometryVertexType.compose_bin; + geo.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3])); + geo.setAttribute(VertexAttributeName.all, data); + geo.vertexBuffer.setComposeBinLayout([ + { name: 'position', format: 'float32x3', offset: 0, shaderLocation: 0, stride: 3 }, + { name: 'normal', format: 'float32x3', offset: 12, shaderLocation: 1, stride: 3 }, + { name: 'uv', format: 'float32x2', offset: 24, shaderLocation: 2, stride: 2 }, + ] as any); + const uv = MeshBVH.getAttributeView(geo, VertexAttributeName.uv); + expect(uv.stride).tobe(8); + expect(uv.offset).tobe(6); + expect(MeshBVH.getAttributeView(geo, VertexAttributeName.TEXCOORD_1)).tobe(null); + const h = MeshBVH.get(geo).raycast(new Vector3(0.5, 0.25, 10), new Vector3(0, 0, -1)); + expect(h.t).toSubequal(8, 1e-6); + expect(h.point.x).toSubequal(0.5, 1e-6); +}) + +await test('sub-geometries: hits report their sub-geometry, only LOD 0 is indexed', async () => { + const geo = quadStack([0, -2, 5]); + // Third quad (z=5) becomes LOD 1 of sub-geometry 0, so it is never drawn at LOD 0. + geo.subGeometries.length = 2; + geo.subGeometries[0].lodLevels.push({ indexStart: 12, indexCount: 6, vertexStart: 0, vertexCount: 0, firstStart: 0, index: 0, topology: 0 }); + const bvh = MeshBVH.get(geo); + expect(bvh.triCount).tobe(4); + const o = new Vector3(0.2, 0.3, 10), d = new Vector3(0, 0, -1); + const all = bvh.raycastAll(o, d); + expect(all.length).tobe(2); // z=5 quad skipped + expect(all[0].subGeometryIndex).tobe(0); + expect(all[1].subGeometryIndex).tobe(1); + expect(bvh.getSubGeometryIndex(all[1].triIndex)).tobe(1); + expect(MeshBVH.raycastGeometryAll(geo, o, d).length).tobe(2); +}) + +await test('cache follows GeometryBase.version: upload refits, replaced arrays rebuild', async () => { + const geo = quadStack([0]); + const bvh = MeshBVH.get(geo); + const o = new Vector3(0, 0, 10), d = new Vector3(0, 0, -1); + expect(bvh.raycast(o, d).t).toSubequal(10, 1e-6); + // Move the quad to z=3 in place and re-upload (what dynamic meshes do). + const posAttr = geo.getAttribute(VertexAttributeName.position); + const p = posAttr.data as Float32Array; + for (let i = 2; i < p.length; i += 3) p[i] = 3; + const v0 = geo.version; + geo.vertexBuffer.upload(VertexAttributeName.position, posAttr); + expect(geo.version > v0).tobe(true); + const again = MeshBVH.get(geo); + expect(again === bvh).tobe(true); // refit, not rebuilt + expect(again.raycast(o, d).t).toSubequal(7, 1e-6); + // Moving it in place *without* an upload (here: sideways, out of the old + // bounds) is invisible until refit(). + for (let i = 0; i < p.length; i += 3) p[i] += 5; + const side = new Vector3(5.2, 0, 10); + expect(MeshBVH.get(geo).raycast(side, d)).tobe(null); + bvh.refit(); + expect(bvh.raycast(side, d).t).toSubequal(7, 1e-6); + // Replacing the position array rebuilds. + geo.setAttribute(VertexAttributeName.position, new Float32Array([-1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1])); + const rebuilt = MeshBVH.get(geo); + expect(rebuilt !== bvh).tobe(true); + expect(rebuilt.raycast(o, d).t).toSubequal(9, 1e-6); +}) + +await test('very deep trees do not overflow the traversal stack', async () => { + // Planes x = 3^k: each midpoint split peels off only the largest plane, + // so with one triangle per leaf the tree is n-1 levels deep (> 128). + const n = 135; + const pos: number[] = []; + for (let k = 0; k < n; k++) { const x = Math.pow(3, k - 55); pos.push(x, 0, 0, x, 1, 0, x, 0, 1); } + const geo = new GeometryBase(); + geo.setAttribute(VertexAttributeName.position, new Float32Array(pos)); + const bvh = MeshBVH.get(geo, 1); + expect(bvh.depth > 128).tobe(true); + // A ray along +x crosses every plane, including the deepest leaves. + const o = new Vector3(-1, 0.2, 0.2), d = new Vector3(1, 0, 0); + expect(bvh.raycastAll(o, d).length).tobe(n); + expect(bvh.raycast(o, d).t).toSubequal(bvh.raycastBruteForce(o, d).t, 1e-9); + // Coming from the far end, the closest plane is the shallowest one. + const back = bvh.raycast(new Vector3(1e38, 0.2, 0.2), new Vector3(-1, 0, 0)); + expect(back.triIndex).tobe(n - 1); +}) + +await test('MeshColliderShape.rayPick: world-space distance/point/normal under scale + translation', async () => { + const shape = new MeshColliderShape(); + shape.mesh = new SphereGeometry(1, 48, 48); + const world = new Matrix4(); + world.compose(new Vector3(5, 0, 0), new Quaternion(), new Vector3(2, 2, 2)); // radius 2 at x=5 + const ray = new Ray(); + ray.origin.set(5, 0, 10); + ray.direction.set(0, 0, -1); + const hit = shape.rayPick(ray, world); + expect(hit != null).tobe(true); + expect(hit.distance).toSubequal(8, 5e-2); + expect(hit.intersectPoint.x).toSubequal(5, 1e-3); + expect(hit.intersectPoint.z).toSubequal(2, 5e-2); + expect(hit.normal.z).toSubequal(1, 1e-2); + // Nearest hit, not first-in-index-order: a ray from the other side hits the far pole. + ray.origin.set(5, 0, -10); ray.direction.set(0, 0, 1); + const back = shape.rayPick(ray, world); + expect(back.intersectPoint.z).toSubequal(-2, 5e-2); + expect(back.normal.z).toSubequal(-1, 1e-2); + // Miss. + ray.origin.set(50, 0, 10); + expect(shape.rayPick(ray, world)).tobe(null); +}) + +await test('BoundingBox.intersectsRay and BoundingSphere.updateBound no longer throw', async () => { + const box = new BoundingBox(new Vector3(0, 0, 0), new Vector3(2, 2, 2)); + const ray = new Ray(); + ray.origin.set(0, 0, 5); ray.direction.set(0, 0, -1); + const p = new Vector3(); + expect(box.intersectsRay(ray, p)).tobe(true); + expect(p.z).toSubequal(1, 1e-6); + ray.origin.set(5, 5, 5); + expect(box.intersectsRay(ray, p)).tobe(false); + + const s = new BoundingSphere(new Vector3(1, 2, 3), 4); + s.updateBound(); + expect(s.min.x).toSubequal(-3, 1e-6); + expect(s.max.y).toSubequal(6, 1e-6); + expect(s.size.z).toSubequal(8, 1e-6); + expect(s.extents.x).toSubequal(4, 1e-6); + s.setFromCenterAndSize(new Vector3(0, 0, 0), 1); + expect(s.max.x).toSubequal(1, 1e-6); +}) + +await test('BVH is at least 5× faster than brute force on a 320k-tri mesh', async () => { + const geo = new SphereGeometry(10, 400, 400); + const t0 = performance.now(); + const bvh = MeshBVH.get(geo); + const buildMs = performance.now() - t0; + console.log(`[MeshBVH] build ${bvh.triCount} tris: ${buildMs.toFixed(1)} ms, ${bvh.nodeCount} nodes, depth ${bvh.depth}`); + const N = 300; + const os: Vector3[] = [], ds: Vector3[] = []; + for (let i = 0; i < N; i++) { const o = randomDir().multiplyScalar(30); os.push(o); ds.push(new Vector3(-o.x, -o.y, -o.z).normalize()); } + let t = performance.now(); + for (let i = 0; i < N; i++) bvh.raycast(os[i], ds[i]); + const bvhMs = performance.now() - t; + t = performance.now(); + for (let i = 0; i < N; i++) bvh.raycastBruteForce(os[i], ds[i]); + const bruteMs = performance.now() - t; + console.log(`[MeshBVH] ${N} rays: BVH ${bvhMs.toFixed(2)} ms, brute ${bruteMs.toFixed(2)} ms, ×${(bruteMs / bvhMs).toFixed(0)}`); + expect(bruteMs / bvhMs > 5).tobe(true); + expect(buildMs < 5000).tobe(true); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/system/RayPick.test.ts b/test/system/RayPick.test.ts new file mode 100644 index 000000000..2f532cf4d --- /dev/null +++ b/test/system/RayPick.test.ts @@ -0,0 +1,211 @@ +import { test, expect, end, waitUntil } from '../util' +import { BoxColliderShape, BoxGeometry, CameraUtil, ColliderComponent, ComponentCollect, Engine3D, LitMaterial, Matrix4, MeshColliderShape, MeshRenderer, Object3D, Quaternion, Ray, RotationControlComponents, Scene3D, SphereColliderShape, SphereGeometry, Vector3, View3D } from '@orillusion/core'; + +const engine = await Engine3D.init(); + +const makeRay = (o: Vector3, d: Vector3) => { const r = new Ray(); r.origin.copy(o); r.direction = d; return r; }; +const compose = (pos: Vector3, scale: Vector3, rotY = 0) => { + const m = new Matrix4(); + const q = new Quaternion(); + q.setFromEuler(0, rotY, 0); + m.compose(pos, q, scale); + return m; +}; + +await test('BoxColliderShape: world-space point/distance/normal, local point kept', async () => { + const box = new BoxColliderShape(); + box.setFromCenterAndSize(new Vector3(), new Vector3(1, 1, 1)); + // Unit box scaled ×10 at the origin: world faces at ±5. + const world = compose(new Vector3(0, 0, 0), new Vector3(10, 10, 10)); + const hit = box.rayPick(makeRay(new Vector3(1, 2, 20), new Vector3(0, 0, -1)), world); + expect(hit != null).tobe(true); + expect(hit.distance).toSubequal(15, 1e-4); // was 1.5 (local units) + expect(hit.intersectPoint.z).toSubequal(5, 1e-4); + expect(hit.intersectPoint.x).toSubequal(1, 1e-4); + expect(hit.localPoint.z).toSubequal(0.5, 1e-4); + expect(hit.normal.z).toSubequal(1, 1e-6); + // Side face under rotation: normal follows the transform. + const rotated = compose(new Vector3(0, 0, 0), new Vector3(2, 2, 2), 90); + const side = box.rayPick(makeRay(new Vector3(10, 0, 0), new Vector3(-1, 0, 0)), rotated); + expect(side.distance).toSubequal(9, 1e-4); + expect(side.normal.x).toSubequal(1, 1e-5); + // Miss. + expect(box.rayPick(makeRay(new Vector3(30, 0, 20), new Vector3(0, 0, -1)), world)).tobe(null); +}) + +await test('SphereColliderShape: world-space hit, uses its own hit point, inside origin hits exit', async () => { + const sphere = new SphereColliderShape(1); + const world = compose(new Vector3(0, 0, 0), new Vector3(3, 3, 3)); + const hit = sphere.rayPick(makeRay(new Vector3(0, 0, 10), new Vector3(0, 0, -1)), world); + expect(hit.distance).toSubequal(7, 1e-4); + expect(hit.intersectPoint.z).toSubequal(3, 1e-4); + expect(hit.localPoint.z).toSubequal(1, 1e-4); + expect(hit.normal.z).toSubequal(1, 1e-6); + // Ray from the centre exits on the far side. + const inside = sphere.rayPick(makeRay(new Vector3(0, 0, 0), new Vector3(1, 0, 0)), world); + expect(inside.distance).toSubequal(3, 1e-4); + expect(sphere.rayPick(makeRay(new Vector3(0, 10, 10), new Vector3(0, 0, -1)), world)).tobe(null); +}) + +await test('mixed shapes: distances are comparable (nearest object wins)', async () => { + // A big box behind a small mesh sphere: the box's old local distance + // (1.5) would have beaten the sphere's world distance (~4). + const box = new BoxColliderShape(); + box.setFromCenterAndSize(new Vector3(), new Vector3(1, 1, 1)); + const boxWorld = compose(new Vector3(0, 0, 0), new Vector3(10, 10, 10)); + const mesh = new MeshColliderShape(); + mesh.mesh = new SphereGeometry(1, 24, 24); + const meshWorld = compose(new Vector3(0, 0, 15), new Vector3(1, 1, 1)); + const ray = makeRay(new Vector3(0, 0, 20), new Vector3(0, 0, -1)); + const a = box.rayPick(ray, boxWorld), b = mesh.rayPick(ray, meshWorld); + expect(b.distance < a.distance).tobe(true); + expect(b.distance).toSubequal(4, 2e-2); +}) + +await test('MeshColliderShape: normal stays perpendicular under non-uniform scale', async () => { + const shape = new MeshColliderShape(); + shape.mesh = new SphereGeometry(1, 96, 96); + // Ellipsoid with semi-axes (4, 1, 1). Hit it at 45° in the XY plane of the + // *local* sphere: local point p = (1,1,0)/√2 → world (4/√2, 1/√2, 0). + const world = compose(new Vector3(), new Vector3(4, 1, 1)); + const target = new Vector3(4 / Math.SQRT2, 1 / Math.SQRT2, 0); + const o = new Vector3(target.x, target.y + 10, 0); + const hit = shape.rayPick(makeRay(o, new Vector3(0, -1, 0)), world); + expect(hit != null).tobe(true); + // Ellipsoid gradient at (x,y,z): (x/16, y/1, z/1) → normalize. + const g = new Vector3(hit.intersectPoint.x / 16, hit.intersectPoint.y, hit.intersectPoint.z).normalize(); + expect(hit.normal.dotProduct(g)).toSubequal(1, 5e-3); + // Transforming with M instead would point at (4,1,0) — far off. + const wrong = new Vector3(4, 1, 0).normalize(); + expect(hit.normal.dotProduct(wrong) < 0.9).tobe(true); + // Results are fresh objects: a second pick does not overwrite the first. + const again = shape.rayPick(makeRay(new Vector3(0, 0, 10), new Vector3(0, 0, -1)), world); + expect(again.intersectPoint !== hit.intersectPoint).tobe(true); + expect(hit.intersectPoint.x).toSubequal(target.x, 5e-2); +}) + +await test('Camera3D.screenPointToRay round-trips worldToScreenPoint on an offset canvas', async () => { + const view = new View3D(); + view.scene = new Scene3D(); + view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); + const canvas = engine.context3D.canvas as HTMLCanvasElement; + view.camera.perspective(60, canvas.clientWidth / canvas.clientHeight, 0.1, 1000); + view.camera.lookAt(new Vector3(0, 5, 20), new Vector3(0, 0, 0)); + engine.startRenderView(view); + await new Promise(r => setTimeout(r, 100)); + + const prev = { position: canvas.style.position, left: canvas.style.left, top: canvas.style.top }; + canvas.style.position = 'absolute'; + canvas.style.left = '120px'; + canvas.style.top = '60px'; + try { + expect(canvas.offsetLeft).tobe(120); + const pts = [new Vector3(0, 0, 0), new Vector3(3, 1, -2), new Vector3(-4, 2, 1)]; + for (const p of pts) { + const s = view.camera.worldToScreenPoint(p, new Vector3()); + const ray = view.camera.screenPointToRay(s.x, s.y); + // Distance from p to the ray line. + const v = new Vector3(p.x - ray.origin.x, p.y - ray.origin.y, p.z - ray.origin.z); + const t = v.dotProduct(ray.direction); + const closest = new Vector3(ray.origin.x + ray.direction.x * t, ray.origin.y + ray.direction.y * t, ray.origin.z + ray.direction.z * t); + expect(Vector3.distance(closest, p)).toSubequal(0, 1e-2); + } + } finally { + canvas.style.position = prev.position; + canvas.style.left = prev.left; + canvas.style.top = prev.top; + } +}) + +await test('PickFire (bound mode): nearest collider wins, full hit data, all hits, filters', async () => { + const view = new View3D(); + view.scene = new Scene3D(); + view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); + const canvas = engine.context3D.canvas as HTMLCanvasElement; + view.camera.perspective(60, canvas.clientWidth / canvas.clientHeight, 0.1, 1000); + view.camera.lookAt(new Vector3(0, 0, 30), new Vector3(0, 0, 0)); + + const add = (name: string, pos: Vector3, scale: number, meshShape: boolean) => { + const obj = new Object3D(); + obj.name = name; + obj.localPosition = pos; + obj.localScale = new Vector3(scale, scale, scale); + const mr = obj.addComponent(MeshRenderer); + mr.geometry = meshShape ? new SphereGeometry(1, 32, 32) : new BoxGeometry(1, 1, 1); + mr.material = new LitMaterial(); + const col = obj.addComponent(ColliderComponent); + if (meshShape) col.shape = new MeshColliderShape(); // no .mesh: taken from the MeshRenderer + else (col.shape as BoxColliderShape).setFromCenterAndSize(new Vector3(), new Vector3(1, 1, 1)); + view.scene.addChild(obj); + return obj; + }; + // A big scaled box behind a small sphere: in local units the box looks closer. + const box = add('box', new Vector3(0, 0, -5), 10, false); + const ball = add('ball', new Vector3(0, 0, 3), 1, true); + engine.startRenderView(view); + // Colliders register for picking when the render loop starts them. + const ready = await waitUntil(() => ComponentCollect.componentsEnablePickerList.get(view)?.size === 2, 20000); + expect(!!ready).tobe(true); + + const pf: any = view.pickFire; + const s = view.camera.worldToScreenPoint(new Vector3(0.2, 0.3, 3), new Vector3()); + engine.inputSystem.mouseX = s.x; + engine.inputSystem.mouseY = s.y; + const pick = () => { pf.pick(view.camera); return pf.findNearestObj(pf._interestList, view.camera); }; + + const target = pick(); + expect(target.object3D === ball).tobe(true); + const data = pf.getPickInfo(); + expect(data.hits.length).tobe(2); + expect(data.hits[1].collider.object3D === box).tobe(true); + expect(data.distance < data.hits[1].distance).tobe(true); + expect(data.faceIndex >= 0).tobe(true); + expect(data.uv != null && data.barycentric != null && data.localPos != null).tobe(true); + expect(data.frontFace).tobe(true); + expect(data.worldNormal.z > 0.5).tobe(true); + // The next pick must not mutate the data handed out above. + const z = data.worldPos.z; + engine.inputSystem.mouseX = s.x + 40; + pick(); + expect(data.worldPos.z).tobe(z); + engine.inputSystem.mouseX = s.x; + + pf.filter = (c: ColliderComponent) => c.object3D !== ball; + expect(pick().object3D === box).tobe(true); + pf.filter = null; + ball.getComponent(ColliderComponent).visibleLayer = 1 << 2; + pf.layerMask = ~(1 << 2); + expect(pick().object3D === box).tobe(true); + pf.layerMask = 0xFFFFFFFF; + expect(pick().object3D === ball).tobe(true); +}) + +await test('RotationControlComponents: each ring is picked by its own axis under a scaled gizmo', async () => { + const view = new View3D(); + view.scene = new Scene3D(); + view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); + const canvas = engine.context3D.canvas as HTMLCanvasElement; + view.camera.perspective(60, canvas.clientWidth / canvas.clientHeight, 0.1, 1000); + view.camera.lookAt(new Vector3(9, 7, 11), new Vector3(0, 0, 0)); + const holder = new Object3D(); + view.scene.addChild(holder); + const gizmo: any = holder.addComponent(RotationControlComponents); + engine.startRenderView(view); + // Constant-screen-size scaling, as onUpdate does (the ring radius is 20 local units). + const s = 0.16; + gizmo.mContainer.scaleX = gizmo.mContainer.scaleY = gizmo.mContainer.scaleZ = s; + for (let axis = 0; axis < 3; axis++) { + const ringObj = gizmo.mAxis[axis] as Object3D; + const c = Math.SQRT1_2 * 20; + const world = Matrix4.transformPoint(ringObj.transform.worldMatrix, new Vector3(c, 0, c), new Vector3()); + const sp = view.camera.worldToScreenPoint(world, new Vector3()); + engine.inputSystem.mouseX = sp.x; + engine.inputSystem.mouseY = sp.y; + const res = gizmo.pickAxis(); + expect(res != null).tobe(true); + expect(res.axis).tobe(axis); + } +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/system/Raycaster.test.ts b/test/system/Raycaster.test.ts new file mode 100644 index 000000000..78c233c36 --- /dev/null +++ b/test/system/Raycaster.test.ts @@ -0,0 +1,224 @@ +import { test, expect, end } from '../util' +import { + CameraUtil, Engine3D, GeometryBase, InstanceDrawComponent, LitMaterial, MeshBVH, MeshRenderer, Object3D, PlaneGeometry, + Raycaster, Scene3D, SphereGeometry, Vector3, VertexAttributeName, View3D, +} from '@orillusion/core'; + +const engine = await Engine3D.init(); + +/** + * Quads facing +z at the given z values (one sub-geometry each), with + * normals and a uv that maps [-1,1]² → [0,1]². + */ +function quads(zs: number[]): GeometryBase { + const geo = new GeometryBase(); + const pos: number[] = [], nrm: number[] = [], uv: number[] = [], idx: number[] = []; + zs.forEach((z, i) => { + const b = i * 4; + pos.push(-1, -1, z, 1, -1, z, 1, 1, z, -1, 1, z); + nrm.push(0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1); + uv.push(0, 0, 1, 0, 1, 1, 0, 1); + idx.push(b, b + 1, b + 2, b, b + 2, b + 3); + }); + geo.setAttribute(VertexAttributeName.position, new Float32Array(pos)); + geo.setAttribute(VertexAttributeName.normal, new Float32Array(nrm)); + geo.setAttribute(VertexAttributeName.uv, new Float32Array(uv)); + geo.setIndices(new Uint32Array(idx)); + zs.forEach((_, i) => geo.addSubGeometry({ indexStart: i * 6, indexCount: 6, vertexStart: 0, vertexCount: 0, firstStart: 0, index: i, topology: 0 })); + return geo; +} + +function mesh(geometry: GeometryBase, pos = new Vector3(), scale = new Vector3(1, 1, 1), name = ''): Object3D { + const obj = new Object3D(); + obj.name = name; + obj.localPosition = pos; + obj.localScale = scale; + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geometry; + mr.material = new LitMaterial(); + return obj; +} + +const down = (x = 0, y = 0, z = 10) => new Raycaster(new Vector3(x, y, z), new Vector3(0, 0, -1)); + +await test('hit data: point, distance, normals, faceIndex, barycentric, uv', async () => { + const obj = mesh(quads([0]), new Vector3(0, 0, -2), new Vector3(2, 2, 2), 'quad'); + const hits = down(1, -1).intersectObject(obj); + expect(hits.length).tobe(1); + const h = hits[0]; + expect(h.object3D === obj).tobe(true); + expect(h.renderer === obj.getComponent(MeshRenderer)).tobe(true); + expect(h.distance).toSubequal(12, 1e-5); + expect(h.point.x).toSubequal(1, 1e-5); + expect(h.point.z).toSubequal(-2, 1e-5); + expect(h.localPoint.x).toSubequal(0.5, 1e-5); + expect(h.localPoint.y).toSubequal(-0.5, 1e-5); + expect(h.uv.x).toSubequal(0.75, 1e-5); + expect(h.uv.y).toSubequal(0.25, 1e-5); + expect(h.uv1).tobe(null); + expect(h.faceIndex).tobe(0); // lower-right triangle (0,1,2) + expect(h.barycentric.x + h.barycentric.y + h.barycentric.z).toSubequal(1, 1e-6); + expect(h.normal.z).toSubequal(1, 1e-6); + expect(h.faceNormal.z).toSubequal(1, 1e-6); + expect(h.frontFace).tobe(true); + expect(h.subGeometryIndex).tobe(0); + // PlaneGeometry (y-up) centre → uv (0.5, 0.5). + const plane = mesh(new PlaneGeometry(4, 4)); + const ph = new Raycaster(new Vector3(0.001, 5, 0.001), new Vector3(0, -1, 0)).intersectObject(plane)[0]; + expect(ph.uv.x).toSubequal(0.5, 1e-3); + expect(ph.uv.y).toSubequal(0.5, 1e-3); +}) + +await test('recursive traversal, sorting, near/far, layerMask and filter', async () => { + const root = mesh(quads([0]), new Vector3(0, 0, 0), undefined, 'root'); + const a = mesh(quads([0]), new Vector3(0, 0, 3), undefined, 'a'); + const b = mesh(quads([0]), new Vector3(0, 0, -3), undefined, 'b'); + root.addChild(a); + a.addChild(b); // b at z = 0 in world (nested) + const names = (hs: any[]) => hs.map(h => h.object3D.name).join(','); + const rc = down(); + const hits = rc.intersectObject(root); + expect(names(hits)).tobe('a,root,b'); // sorted; a(z=3) then root and b (both z=0) + expect(hits[0].distance).toSubequal(7, 1e-5); + expect(names(rc.intersectObject(root, false))).tobe('root'); + rc.far = 9; + expect(names(rc.intersectObject(root))).tobe('a'); + rc.far = Infinity; rc.near = 8; + expect(names(rc.intersectObject(root)).startsWith('root')).tobe(true); + rc.near = 0; + a.getComponent(MeshRenderer).visibleLayer = 1 << 3; + rc.layerMask = ~(1 << 3); + expect(names(rc.intersectObject(root)).includes('a')).tobe(false); + rc.layerMask = 0xFFFFFFFF; + rc.filter = r => r.object3D.name !== 'root'; + expect(names(rc.intersectObject(root))).tobe('a,b'); + rc.filter = null; + // intersectObjects over several roots; intersectFirst finds the same closest hit. + const other = mesh(quads([0]), new Vector3(0, 0, 5), undefined, 'other'); + expect(names(rc.intersectObjects([root, other]))).tobe('other,a,root,b'); + expect(rc.intersectFirst([root, other]).object3D === other).tobe(true); + expect(rc.intersectFirst(root).object3D === a).tobe(true); + expect(down(5, 5).intersectFirst(root)).tobe(null); +}) + +await test('sides: material cull mode, explicit side, mirrored transforms', async () => { + const sphere = mesh(new SphereGeometry(1, 32, 32)); + const mat = sphere.getComponent(MeshRenderer).material; + const fromInside = new Raycaster(new Vector3(0, 0, 0), new Vector3(1, 0, 0)); + // LitMaterial culls back faces: the inside of the sphere is invisible. + expect(fromInside.intersectObject(sphere).length).tobe(0); + fromInside.side = 'double'; + expect(fromInside.intersectObject(sphere).length).tobe(1); + fromInside.side = 'back'; + expect(fromInside.intersectObject(sphere)[0].frontFace).tobe(false); + fromInside.side = 'material'; + mat.cullMode = 'none'; + expect(fromInside.intersectObject(sphere).length).tobe(1); + mat.cullMode = 'back'; + // All hits vs first hit only. + const outside = down(0.1, 0.1); + expect(outside.intersectObject(sphere).length).tobe(1); // far side is a back face + outside.side = 'double'; + expect(outside.intersectObject(sphere).length).tobe(2); + outside.firstHitOnly = true; + expect(outside.intersectObject(sphere).length).tobe(1); + // A mirroring transform reverses the winding the rasterizer sees (the + // engine does not flip frontFace per object), so with back-face culling a + // mirrored sphere shows its inner far side; 'material' picks what is drawn. + const mirrored = mesh(new SphereGeometry(1, 32, 32), new Vector3(), new Vector3(-1, 1, 1)); + const mh = down(0.1, 0.1).intersectObject(mirrored); + expect(mh.length).tobe(1); + expect(mh[0].frontFace).tobe(true); + expect(mh[0].point.z).toSubequal(-1, 2e-2); + const md = down(0.1, 0.1); + md.side = 'double'; + const both = md.intersectObject(mirrored); + expect(both.length).tobe(2); + expect(both[0].frontFace).tobe(false); // near side is a back face once mirrored +}) + +await test('per-sub-mesh materials: non-triangle and culled sub-meshes are skipped', async () => { + const obj = mesh(quads([2, 0])); + const mr = obj.getComponent(MeshRenderer); + const lines = new LitMaterial(); + lines.topology = 'line-list'; + mr.materials = [lines, new LitMaterial()]; + const hits = down().intersectObject(obj); + expect(hits.length).tobe(1); + expect(hits[0].subGeometryIndex).tobe(1); + // Closest-hit mode must also skip to the next valid hit, not report none. + const rc = down(); + rc.firstHitOnly = true; + expect(rc.intersectObject(obj)[0].subGeometryIndex).tobe(1); + expect(rc.intersectFirst(obj).subGeometryIndex).tobe(1); +}) + +await test('BVH usage: auto uses an existing tree, never/auto do not build one', async () => { + const geo = new SphereGeometry(1, 24, 24); + const obj = mesh(geo); + const rc = down(0.2, 0.1); + rc.side = 'double'; + rc.useBVH = 'never'; + const brute = rc.intersectObject(obj); + expect(MeshBVH.has(geo)).tobe(false); + rc.useBVH = 'auto'; + const auto = rc.intersectObject(obj); + expect(MeshBVH.has(geo)).tobe(false); + rc.useBVH = 'always'; + const tree = rc.intersectObject(obj); + expect(MeshBVH.has(geo)).tobe(true); + expect(brute.length).tobe(2); + for (let i = 0; i < 2; i++) { + expect(auto[i].distance).toSubequal(brute[i].distance, 1e-9); + expect(tree[i].distance).toSubequal(brute[i].distance, 1e-9); + expect(tree[i].faceIndex).tobe(brute[i].faceIndex); + } +}) + +await test('non-uniform scale: world distance and perpendicular normals', async () => { + const obj = mesh(new SphereGeometry(1, 96, 96), new Vector3(0, 0, 0), new Vector3(4, 1, 1)); + const target = new Vector3(4 / Math.SQRT2, 1 / Math.SQRT2, 0); + const h = new Raycaster(new Vector3(target.x, 10, 0), new Vector3(0, -1, 0)).intersectFirst(obj); + expect(h.distance).toSubequal(10 - target.y, 2e-2); + const g = new Vector3(h.point.x / 16, h.point.y, h.point.z).normalize(); + expect(h.normal.dotProduct(g)).toSubequal(1, 5e-3); +}) + +await test('instanced batches stay pickable; disabled renderers do not', async () => { + const root = new Object3D(); + const child = mesh(quads([0])); + root.addChild(child); + child.getComponent(MeshRenderer).enable = false; + expect(down().intersectObject(root).length).tobe(0); + root.addComponent(InstanceDrawComponent); + expect(down().intersectObject(root).length).tobe(1); + expect(down().intersectObject(child).length).tobe(1); // ancestor batch is found from a child root too +}) + +await test('setFromCamera / setFromCameraNDC aim through the same pixel', async () => { + const view = new View3D(); + view.scene = new Scene3D(); + view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); + const canvas = engine.context3D.canvas as HTMLCanvasElement; + view.camera.perspective(60, canvas.clientWidth / canvas.clientHeight, 0.1, 1000); + view.camera.lookAt(new Vector3(3, 4, 12), new Vector3(0, 0, 0)); + const target = mesh(new SphereGeometry(1, 32, 32), new Vector3(0, 0, 0), undefined, 'target'); + view.scene.addChild(target); + engine.startRenderView(view); + await new Promise(r => setTimeout(r, 100)); + + const s = view.camera.worldToScreenPoint(new Vector3(0, 0, 0), new Vector3()); + const a = new Raycaster().setFromCamera(view.camera, s.x, s.y); + const ndcX = s.x / canvas.clientWidth * 2 - 1, ndcY = 1 - s.y / canvas.clientHeight * 2; + const b = new Raycaster().setFromCameraNDC(view.camera, ndcX, ndcY); + expect(a.ray.direction.dotProduct(b.ray.direction)).toSubequal(1, 1e-6); + const ha = a.intersectFirst(view.scene), hb = b.intersectFirst(view.scene); + expect(ha.object3D.name).tobe('target'); + expect(Vector3.distance(ha.point, hb.point)).toSubequal(0, 1e-3); + // The ray through the sphere centre hits the surface facing the camera. + const toCam = new Vector3(3, 4, 12).normalize(); + expect(ha.normal.dotProduct(toCam)).toSubequal(1, 2e-2); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/system/SkinnedRaycast.test.ts b/test/system/SkinnedRaycast.test.ts new file mode 100644 index 000000000..b37b9e96a --- /dev/null +++ b/test/system/SkinnedRaycast.test.ts @@ -0,0 +1,314 @@ +import { test, expect, end, delay, waitUntil } from '../util' +import { + AnimatorComponent, CameraUtil, ColliderComponent, DirectLight, Engine3D, GeometryBase, LitMaterial, Matrix4, MeshColliderShape, MeshDeformer, + MeshRenderer, Object3D, PrefabAvatarData, PrefabBoneData, Quaternion, Ray, Raycaster, Scene3D, SkinnedMeshRenderer2, Vector3, VertexAttributeName, View3D, +} from '@orillusion/core'; + +// Pixel picking reads the rendered G-buffer back: the GPU's own answer to +// "what surface is under this pixel", which the CPU raycast must reproduce. +const engine = await Engine3D.init({ setting: { pick: { enable: true, mode: 'pixel' } } }); + +const view = new View3D(); +view.scene = new Scene3D(); +view.camera = CameraUtil.createCamera3DObject(view.scene, 'camera'); +const canvas = engine.context3D.canvas as HTMLCanvasElement; +view.camera.perspective(45, canvas.clientWidth / canvas.clientHeight, 0.1, 100); +const light = new Object3D(); +light.rotationX = 45; +light.addComponent(DirectLight).intensity = 3; +view.scene.addChild(light); +engine.startRenderView(view); + +/** GPU pick at a canvas pixel: waits until the read-back result is for this pixel. */ +async function gpuPick(x: number, y: number): Promise<{ id: number, pos: Vector3 } | null> { + const pc: any = (view.pickFire as any)._pickCompute; + const buf = pc._outBuffer; + const pr = (engine.context3D as any).pixelRatio || 1; + engine.inputSystem.mouseX = x; + engine.inputSystem.mouseY = y; + for (let attempt = 0; attempt < 6; attempt++) { + await delay(100); + pc.compute(view); + const ok = await waitUntil(() => { + const a = buf.outFloat32Array; + return a && Math.abs(a[2] - x * pr) < 0.5 && Math.abs(a[3] - y * pr) < 0.5; + }, 3000); + if (ok) return { id: pc.getPickMeshID(), pos: pc.getPickWorldPosition() }; + } + return null; +} + +/** + * Pixels on the deformed surface: projected triangle centroids (never on a + * silhouette edge) that the CPU ray hits on `root`, spread over the mesh. + */ +function surfacePixels(root: Object3D, renderers: MeshRenderer[], count: number): { x: number, y: number }[] { + const rc = new Raycaster(); + const out: { x: number, y: number }[] = []; + const all: Vector3[] = []; + for (const r of renderers) { + const d = MeshDeformer.deform(r); + const p = d.geometry.getAttribute(VertexAttributeName.position).data as Float32Array; + const idx = d.geometry.getAttribute(VertexAttributeName.indices).data as ArrayLike; + const m = d.worldSpace ? null : r.transform.worldMatrix; + for (let t = 0; t + 2 < idx.length; t += 3) { + const c = new Vector3(); + for (let k = 0; k < 3; k++) { + const i = idx[t + k] * 3; + c.x += p[i] / 3; c.y += p[i + 1] / 3; c.z += p[i + 2] / 3; + } + all.push(m ? m.transformPoint(c) : c); + } + } + const step = Math.max(1, Math.floor(all.length / count)); + for (let i = step >> 1; i < all.length && out.length < count; i += step) { + const s = view.camera.worldToScreenPoint(all[i], new Vector3()); + const x = Math.round(s.x) + 0.5, y = Math.round(s.y) + 0.5; + if (x < 1 || y < 1 || x > canvas.clientWidth - 1 || y > canvas.clientHeight - 1) continue; + if (rc.setFromCamera(view.camera, x, y).intersectFirst(root)) out.push({ x, y }); + } + return out; +} + +/** Compare CPU hits (as drawn and bind pose) with the GPU surface at `pixels`. */ +async function compare(root: Object3D, renderers: MeshRenderer[], pixels: { x: number, y: number }[], tol: number) { + const rc = new Raycaster(); + const ids = renderers.map(r => r.transform.worldMatrix.index); + let samples = 0, cpuOk = 0, bindOk = 0; + const rows: string[] = []; + for (const { x, y } of pixels) { + const g = await gpuPick(x, y); + if (!g || !ids.includes(g.id)) continue; // GPU sees something else (or nothing) there + samples++; + rc.setFromCamera(view.camera, x, y); + rc.deformation = 'cpu'; + const c = rc.intersectFirst(root); + rc.deformation = 'bindPose'; + const b = rc.intersectFirst(root); + const dc = c ? Vector3.distance(c.point, g.pos) : Infinity, db = b ? Vector3.distance(b.point, g.pos) : Infinity; + if (dc < tol) cpuOk++; + if (db < tol) bindOk++; + rows.push(`(${x},${y}) cpu ${dc.toFixed(3)} bind ${db.toFixed(3)}`); + } + console.log(rows.join('\n')); + return { samples, cpuOk, bindOk }; +} + +/** Indexed grid of (nx × ny) quads on the XY plane over [x0, x0 + w] × [y0, y0 + h], facing +z. */ +function gridGeometry(nx: number, ny: number, x0: number, y0: number, w: number, h: number): GeometryBase { + const vx = nx + 1, vy = ny + 1; + const pos = new Float32Array(vx * vy * 3), nrm = new Float32Array(vx * vy * 3), uv = new Float32Array(vx * vy * 2); + for (let j = 0; j < vy; j++) { + for (let i = 0; i < vx; i++) { + const v = j * vx + i; + pos.set([x0 + w * i / nx, y0 + h * j / ny, 0], v * 3); + nrm.set([0, 0, 1], v * 3); + uv.set([i / nx, j / ny], v * 2); + } + } + const idx = new Uint16Array(nx * ny * 6); + for (let j = 0, k = 0; j < ny; j++) { + for (let i = 0; i < nx; i++, k += 6) { + const a = j * vx + i, b = a + 1, c = a + vx + 1, d = a + vx; + idx.set([a, b, c, a, c, d], k); + } + } + const geo = new GeometryBase(); + geo.setAttribute(VertexAttributeName.position, pos); + geo.setAttribute(VertexAttributeName.normal, nrm); + geo.setAttribute(VertexAttributeName.uv, uv); + geo.setAttribute(VertexAttributeName.TEXCOORD_1, uv); + geo.setIndices(idx); + geo.addSubGeometry({ indexStart: 0, indexCount: idx.length, vertexStart: 0, vertexCount: vx * vy, firstStart: 0, index: 0, topology: 0 }); + return geo; +} + +function bone(name: string, id: number, parent: PrefabBoneData | null, t: Vector3): PrefabBoneData { + const b = new PrefabBoneData(); + b.boneName = name; + b.bonePath = parent ? parent.bonePath + '/' + name : name; + b.parentBoneName = parent ? parent.boneName : ''; + b.boneID = id; + b.parentBoneID = parent ? parent.boneID : -1; + b.instanceID = b.parentInstanceID = ''; + b.t = t; + b.q = new Quaternion(); + b.s = new Vector3(1, 1, 1); + return b; +} + +/** + * Two-bone rig: b0 at the origin, b1 two units up. The skinned strip spans + * y ∈ [0, 4]; vertices below y = 1.5 follow b0, above y = 2.5 follow b1, + * and blend linearly in between. + */ +function skinnedStrip(): { rig: Object3D, animator: AnimatorComponent, renderer: SkinnedMeshRenderer2 } { + const avatar = new PrefabAvatarData(); + avatar.name = 'test-two-bone-rig'; + const b0 = bone('b0', 0, null, new Vector3(0, 0, 0)); + const b1 = bone('b1', 1, b0, new Vector3(0, 2, 0)); + avatar.boneData = [b0, b1]; + avatar.boneMap = new Map([[b0.boneName, b0], [b1.boneName, b1]]); + avatar.count = 2; + engine.res.addObj(avatar.name, avatar); + + const geo = gridGeometry(4, 16, -0.5, 0, 1, 4); + const pos = geo.getAttribute(VertexAttributeName.position).data as Float32Array; + const n = pos.length / 3; + const joints = new Float32Array(n * 4), weights = new Float32Array(n * 4); + for (let v = 0; v < n; v++) { + const t = Math.min(1, Math.max(0, pos[v * 3 + 1] - 1.5)); + joints.set([0, 1, 0, 0], v * 4); + weights.set([1 - t, t, 0, 0], v * 4); + } + geo.setAttribute(VertexAttributeName.joints0, joints); + geo.setAttribute(VertexAttributeName.weights0, weights); + geo.skinNames = ['b0', 'b1']; + const invB1 = new Matrix4(); + invB1.rawData[13] = -2; // inverse of b1's bind world matrix (translate y + 2) + geo.bindPose = [new Matrix4(), invB1]; + + const rig = new Object3D(); + view.scene.addChild(rig); + const animNode = new Object3D(); + rig.addChild(animNode); + const animator = animNode.addComponent(AnimatorComponent); + animator.avatar = avatar.name; // the root joint is parented under `rig` + + const meshNode = new Object3D(); + rig.addChild(meshNode); + const renderer = meshNode.addComponent(SkinnedMeshRenderer2); + renderer.geometry = geo; + const mat = new LitMaterial(); + mat.cullMode = 'none'; + renderer.material = mat; + renderer.skeletonAnimation = animator; + return { rig, animator, renderer }; +} + +await test('skinned two-bone strip: CPU-skinned hits land on the GPU-rendered surface', async () => { + const { rig, animator, renderer } = skinnedStrip(); + // Tilt the whole strip towards the camera and bend the upper half sideways, + // so no part of the drawn surface coincides with the bind pose. + animator.getJointObject('b0').rotationX = -25; + animator.getJointObject('b1').rotationZ = 60; + view.camera.lookAt(new Vector3(1, 2, 9), new Vector3(-0.5, 2, 0)); + await delay(1000); + + expect(MeshDeformer.isDeformed(renderer)).tobe(true); + const pixels = surfacePixels(rig, [renderer], 8); + const { samples, cpuOk, bindOk } = await compare(rig, [renderer], pixels, 0.05); + console.log(`[skin] samples ${samples}, cpu ok ${cpuOk}, bind pose ok ${bindOk}`); + expect(samples >= 6).tobe(true); + expect(cpuOk >= samples - 1).tobe(true); + expect(bindOk <= samples / 2).tobe(true); // the bind pose is visibly elsewhere + + // Unchanged pose → cached result, no recomputation. + const v0 = MeshDeformer.deform(renderer).geometry.version; + expect(MeshDeformer.deform(renderer).geometry.version).tobe(v0); + // Once a frame applies a new pose, the next query recomputes. + animator.getJointObject('b1').rotationZ = 30; + const moved = await waitUntil(() => MeshDeformer.deform(renderer).geometry.version > v0, 3000); + expect(!!moved).tobe(true); + view.scene.removeChild(rig); +}) + +await test('morph targets (bump grid): CPU-morphed hits land on the GPU-rendered surface', async () => { + const geo = gridGeometry(12, 12, -2, -2, 4, 4); + const pos = geo.getAttribute(VertexAttributeName.position).data as Float32Array; + const n = pos.length / 3; + const bump = new Float32Array(n * 3), vIndex = new Float32Array(n); + for (let v = 0; v < n; v++) { + const x = pos[v * 3], y = pos[v * 3 + 1]; + bump[v * 3 + 2] = 1.5 * Math.exp(-(x * x + y * y)); // relative z offset, a bump in the middle + vIndex[v] = v; + } + geo.setAttribute(VertexAttributeName.vIndex, vIndex); + geo.setAttribute('a_morphPositions_0', bump); + geo.morphTargetDictionary = { bump: 0 }; + geo.morphTargetsRelative = true; + + const obj = new Object3D(); + obj.rotationY = 20; // morphs are mesh-local: exercise the world transform too + const renderer = obj.addComponent(MeshRenderer); + renderer.geometry = geo; + const mat = new LitMaterial(); + mat.cullMode = 'none'; + renderer.material = mat; + renderer.setMorphInfluence('bump', 0.8); + view.scene.addChild(obj); + view.camera.lookAt(new Vector3(2.5, 2.5, 6), new Vector3(0, 0, 0)); + await delay(1000); + + expect(MeshDeformer.isDeformed(renderer)).tobe(true); + const pixels = surfacePixels(obj, [renderer], 8); + const { samples, cpuOk, bindOk } = await compare(obj, [renderer], pixels, 0.05); + console.log(`[morph] samples ${samples}, cpu ok ${cpuOk}, bind pose ok ${bindOk}`); + expect(samples >= 6).tobe(true); + expect(cpuOk >= samples - 1).tobe(true); + view.scene.removeChild(obj); +}) + +/** Quad z=0 over [-1,1]² with one morph target. */ +function morphQuad(relative: boolean, target: number[]): Object3D { + const geo = new GeometryBase(); + geo.setAttribute(VertexAttributeName.position, new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0])); + geo.setAttribute(VertexAttributeName.normal, new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1])); + geo.setAttribute(VertexAttributeName.uv, new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])); + geo.setAttribute(VertexAttributeName.vIndex, new Float32Array([0, 1, 2, 3])); + geo.setAttribute('a_morphPositions_0', new Float32Array(target)); + geo.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3])); + geo.addSubGeometry({ indexStart: 0, indexCount: 6, vertexStart: 0, vertexCount: 4, firstStart: 0, index: 0, topology: 0 }); + geo.morphTargetDictionary = { up: 0 }; + geo.morphTargetsRelative = relative; + const obj = new Object3D(); + const mr = obj.addComponent(MeshRenderer); + mr.geometry = geo; + mr.material = new LitMaterial(); + return obj; +} + +await test('morph math: relative and absolute targets, bind-pose / skip modes, cache', async () => { + const down = () => new Raycaster(new Vector3(0.3, 0.2, 10), new Vector3(0, 0, -1)); + // Relative: delta +2 in z at weight 0.5 → z = 1. + const rel = morphQuad(true, [0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 2]); + const mr = rel.getComponent(MeshRenderer); + expect(MeshDeformer.isDeformed(mr)).tobe(false); // all weights 0 → nothing to deform + expect(down().intersectFirst(rel).point.z).toSubequal(0, 1e-6); + mr.setMorphInfluence('up', 0.5); + expect(MeshDeformer.isDeformed(mr)).tobe(true); + const h = down().intersectFirst(rel); + expect(h.point.z).toSubequal(1, 1e-6); + expect(h.uv.x).toSubequal(0.65, 1e-6); + expect(h.localPoint.z).toSubequal(1, 1e-6); + const bind = down(); bind.deformation = 'bindPose'; + expect(bind.intersectFirst(rel).point.z).toSubequal(0, 1e-6); + const skip = down(); skip.deformation = 'skip'; + expect(skip.intersectFirst(rel)).tobe(null); + // Cached until the weights change. + const g = MeshDeformer.deform(mr).geometry, v = g.version; + expect(MeshDeformer.deform(mr).geometry.version).tobe(v); + mr.setMorphInfluence('up', 1); + expect(MeshDeformer.deform(mr).geometry.version > v).tobe(true); + expect(down().intersectFirst(rel).point.z).toSubequal(2, 1e-6); + // Absolute: base weight 1 - 0.25, target at z = 4 → z = 1. + const abs = morphQuad(false, [-1, -1, 4, 1, -1, 4, 1, 1, 4, -1, 1, 4]); + abs.getComponent(MeshRenderer).setMorphInfluence('up', 0.25); + expect(down().intersectFirst(abs).point.z).toSubequal(1, 1e-6); +}) + +await test('mesh colliders pick deformed meshes as drawn', async () => { + const obj = morphQuad(true, [0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 2]); + obj.getComponent(MeshRenderer).setMorphInfluence('up', 0.5); + const collider = obj.addComponent(ColliderComponent); + const shape = new MeshColliderShape(); + collider.shape = shape; + const ray = new Ray(new Vector3(0.3, 0.2, 10), new Vector3(0, 0, -1)); + expect(collider.rayPick(ray).intersectPoint.z).toSubequal(1, 1e-6); + expect(shape.renderer === obj.getComponent(MeshRenderer)).tobe(true); + shape.deformation = 'bindPose'; + expect(collider.rayPick(ray).intersectPoint.z).toSubequal(0, 1e-6); +}) + +Engine3D.pause(); +setTimeout(end, 500) diff --git a/test/util.ts b/test/util.ts index f95fe2b7d..9db908bfd 100644 --- a/test/util.ts +++ b/test/util.ts @@ -1,3 +1,5 @@ +import { Time } from '@orillusion/core' + let target = sessionStorage.target.split('/').pop() let result: { [key: string]: any } = {} let totalS = 0, totalF = 0 @@ -137,4 +139,39 @@ function isMatch(object: any, attrs: { [key: string]: any }) { return true; } -export { test, expect, end, delay, waitUntil } \ No newline at end of file +function halfToFloat(h: number): number { + const s = (h & 0x8000) ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff; + if (e === 0) return s * Math.pow(2, -14) * (f / 1024); + if (e === 31) return f ? NaN : s * Infinity; + return s * Math.pow(2, e - 15) * (1 + f / 1024); +} + +/** + * Read a `w`×1 row of an rgba16float texture back as [r,g,b,a] float + * tuples. For GPU-vs-CPU checks on post-effect targets. + */ +async function readRowRGBA16F(device: GPUDevice, texture: GPUTexture, x: number, y: number, w: number = 1): Promise { + const bytesPerRow = Math.ceil((w * 8) / 256) * 256; + const buf = device.createBuffer({ size: bytesPerRow, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + const enc = device.createCommandEncoder(); + enc.copyTextureToBuffer({ texture, origin: { x: Math.floor(x), y: Math.floor(y) } }, { buffer: buf, bytesPerRow }, { width: w, height: 1 }); + device.queue.submit([enc.finish()]); + await buf.mapAsync(GPUMapMode.READ); + const u16 = new Uint16Array(buf.getMappedRange().slice(0, w * 8)); + buf.unmap(); buf.destroy(); + const out: number[][] = []; + for (let i = 0; i < w; i++) out.push([halfToFloat(u16[i * 4]), halfToFloat(u16[i * 4 + 1]), halfToFloat(u16[i * 4 + 2]), halfToFloat(u16[i * 4 + 3])]); + return out; +} + +/** + * Wait until `count` whole frames that began after this call have rendered. + * CI runs WebGPU on SwiftShader at ~2 fps or slower, so a wall-clock delay after + * changing a setting may not cover a single frame and a readback sees the old image. + */ +async function frames(count: number = 2) { + const until = Time.frame + count + 1 + await waitUntil(() => Time.frame >= until, 30000, 10) +} + +export { test, expect, end, delay, waitUntil, frames, readRowRGBA16F } \ No newline at end of file