Compare commits
2
Commits
53115d9ea2
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62a5f5ad11 | ||
|
|
66992b3024 |
@@ -6,6 +6,15 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
set(SPEEDTREE_SOURCES
|
||||
src/spt_parser.cpp
|
||||
src/spt_reader.cpp
|
||||
src/branch_spline.cpp
|
||||
src/wind.cpp
|
||||
src/legacy_wind.cpp
|
||||
src/billboard.cpp
|
||||
src/frond.cpp
|
||||
src/leaf.cpp
|
||||
src/lod.cpp
|
||||
src/branch_generator.cpp
|
||||
src/tree_generator.cpp
|
||||
src/forest.cpp
|
||||
)
|
||||
@@ -31,7 +40,18 @@ target_include_directories(speedtree PUBLIC
|
||||
option(SPEEDTREE_BUILD_TESTS "Build SpeedTree SDK tests" ON)
|
||||
if(SPEEDTREE_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_executable(generation_baseline tools/generation_baseline.cpp)
|
||||
target_link_libraries(generation_baseline PRIVATE speedtree)
|
||||
add_executable(speedtree_test tests/speedtree_test.cpp)
|
||||
target_link_libraries(speedtree_test PRIVATE speedtree)
|
||||
add_test(NAME speedtree_test COMMAND speedtree_test)
|
||||
add_executable(spt_format_test tests/spt_format_test.cpp)
|
||||
target_link_libraries(spt_format_test PRIVATE speedtree)
|
||||
add_test(NAME spt_format_test COMMAND spt_format_test)
|
||||
add_executable(branch_wind_test tests/branch_wind_test.cpp)
|
||||
target_link_libraries(branch_wind_test PRIVATE speedtree)
|
||||
add_test(NAME branch_wind_test COMMAND branch_wind_test)
|
||||
add_executable(legacy_runtime_test tests/legacy_runtime_test.cpp)
|
||||
target_link_libraries(legacy_runtime_test PRIVATE speedtree)
|
||||
add_test(NAME legacy_runtime_test COMMAND legacy_runtime_test)
|
||||
endif()
|
||||
|
||||
+50
-3
@@ -1,10 +1,49 @@
|
||||
# SpeedTree Cross-Platform Foliage SDK
|
||||
|
||||
A pure C++20, graphics-API-agnostic implementation of SpeedTree foliage rendering and wind dynamics for cross-platform game engines.
|
||||
A C++20, graphics-API-agnostic SDK for legacy SPT metadata and procedural foliage.
|
||||
Tree assets now generate limb hierarchies from their authored Bezier curves and
|
||||
seed. Wind uses indexed weighted matrices and pivot-based leaf rocking, with
|
||||
reference GLSL for generic matrix deformation and fallback rocking. Authored leaf
|
||||
card dimensions, pivots, camera orientation and grouped rocking now use a CPU path;
|
||||
that authored-card path is not yet implemented in the standalone reference GLSL.
|
||||
AVA2's active Metal/SPIR-V scene pipeline now implements it alongside native wind,
|
||||
with a CPU fallback. Independent branch/leaf/frond LODs are cached per model;
|
||||
their decimation rules remain SDK approximations. Authored branch density and
|
||||
indexed attachment sampling are restored, while full original random distribution
|
||||
is incomplete. The generator now restores branch-entry draw ordering, normalized
|
||||
child spline positions, original longitudinal segment counts, and a separate
|
||||
terminal authored-leaf path. Branch frames now inherit source basis rotations,
|
||||
apply perturbations/default Z-up gravity, and use authored axial exponents.
|
||||
Special leaf pools respect authored thresholds, ancestor depth and probability.
|
||||
Geometry uses 32-bit indices throughout;
|
||||
GetGenerationStats exposes per-level node counts, terminal leaf calls and explicit
|
||||
allocation-limit reasons. WasGenerationTruncated reports these limits. Forest updates use the original AVA2 four-matrix controller and legacy leaf
|
||||
rocking phase. The standalone wind fallback and branch scheduling remain
|
||||
approximations of the original SpeedTreeRT runtime.
|
||||
|
||||
The SPT reader now follows the token grammar recovered from the AVA2 runtime:
|
||||
tree size/variance (`2006`/`2007`), near/far LOD (`2003`/`2001`), atlas UV quads,
|
||||
texture names, collision objects and wind metadata. It reads explicit little-endian
|
||||
values, checks lengths/counts and exposes unsupported extensions through
|
||||
`metadata_complete`, `unsupported_token`, and `error`. Invalid files return false;
|
||||
model factories return null instead of silently fabricating a tree.
|
||||
Billboard support includes camera-facing vertical quads, optional horizontal
|
||||
quads, 360-degree atlas transitions and alpha-test distance switching in AVA2.
|
||||
Fronds now use authored blade/profile modes, branch levels, texture sizing and
|
||||
profile splines, with CPU wind and AVA2 draw integration. Geometry dimensions and
|
||||
limb placement still come from our approximate generated meshes.
|
||||
See [reverse engineering coverage](REVERSE-ENGINEERING.md).
|
||||
|
||||
For reproducible snapshots, build with `SPEEDTREE_BUILD_TESTS=ON`, then run
|
||||
`generation_baseline SPT_DIRECTORY > baseline.jsonl`. It sorts the corpus paths
|
||||
and records authored seed, hierarchy counts, bounds, per-LOD topology and hashes.
|
||||
Run `python3 tools/compare_generation_baselines.py before.jsonl after.jsonl` to
|
||||
compare snapshots of the same directory. The snapshots measure this replacement;
|
||||
they do not establish equivalence to the Windows DLL.
|
||||
|
||||
## 🌟 核心特性与渲染真实度突破(Realism & Shading)
|
||||
|
||||
为了达到与商业版 SpeedTree 同样真实、飘逸自然的渲染质感,本 SDK 实现了以下四大核心技术管线:
|
||||
以下渲染与风力效果是本 SDK 的程序化近似方案;尚未经过原 DLL 的动态等价验证:
|
||||
|
||||
### 1. 三级分层风场动力学 (3-Tier Hierarchical Wind Dynamics)
|
||||
- **Level 1 树干弯曲 (Trunk Bending)**: 基于树高的二次曲线响应,具备长度保持(Length-Preserving)算法,模拟主干在阵风下的柔韧弯曲。
|
||||
@@ -35,7 +74,15 @@ sdk/speedtree/
|
||||
│ ├── speedtree.h # 核心模型、顶点布局、SPT 信息、森林实例管理
|
||||
│ └── foliage_shaders.h # 现代 GPU 植被顶点/片元着色器源码(含 3 级风力与次表面透光)
|
||||
├── src/
|
||||
│ ├── spt_parser.cpp # 官方 .spt 二进制解析(Token 2000/2001/10000/10002/12000 等)
|
||||
│ ├── spt_parser.cpp # .prt 属性文本解析与路径处理
|
||||
│ ├── spt_reader.cpp # 有边界检查的原版 SPT 元数据语法(含未支持扩展诊断)
|
||||
│ ├── branch_spline.cpp # BezierSpline 与每模型独立的旧版随机序列
|
||||
│ ├── branch_generator.cpp # 曲线驱动的分枝网格与叶片
|
||||
│ ├── lod.cpp # 独立网格缩减、叶片子集与 LOD 尺寸调整
|
||||
│ ├── leaf.cpp # 原版叶片支点、镜像与朝向旋转
|
||||
│ ├── frond.cpp # 带片/弧面 frond 网格、纹理尺寸与 UV
|
||||
│ ├── billboard.cpp # 原版视角纹理选择、水平与垂直远景贴片
|
||||
│ ├── wind.cpp # 加权风力矩阵、叶片支点和法线变形
|
||||
│ ├── tree_generator.cpp # 树木骨架圆柱网格、树冠卡片、风力权重生成与 CPU 变形求值
|
||||
│ └── forest.cpp # 森林多实例生命周期、视锥剔除基础、风向风力统一控制
|
||||
└── tests/
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
# AVA2 legacy SpeedTreeRT compatibility
|
||||
|
||||
This implementation uses the static analysis of the AVA2 PE32 x86 DLL with
|
||||
SHA-256 `ddba9b9b427d541ebc0bf1221fffc5d56a85d7b8ee0dfe6370a83a133da6967b`.
|
||||
The full analysis is in the sibling client under
|
||||
`ava2-client/build/verification/speedtree-decompile/`; no generated pseudocode or
|
||||
game assets are copied into this SDK. The original DLL and reference files are unchanged.
|
||||
|
||||
## Implemented corrections
|
||||
|
||||
| Source address | Recovered behavior | SDK change |
|
||||
|---|---|---|
|
||||
| `100230a0`, `10022f80`, `10023060` | General tree fields: 2001 far LOD, 2002 one byte, 2003 near LOD, 2005 seed, 2006 size, 2007 variance | Correct field widths/semantics; removed byte-by-byte token guessing |
|
||||
| `10022950`, `10007ae0`, `10007ad0`, `10007b00` | Token 1000, counted `__IdvSpt_02_` string, nested sections; little-endian 4-byte values and counted strings | Sequential cursor, signature checks, bounds/count checks and explicit endian conversion |
|
||||
| `10006a70`, `10023640`, `10015a60`, `100257e0` | Branch spline strings, counted branch/leaf records and general wind fields | Traverse metadata without treating payload bytes as tokens |
|
||||
| `1001ebb0`, `10021840` | 10002 leaf, 10003 billboard, 10004 frond; eight floats per UV quad; counted composite texture name | Correct atlas groups, arbitrary ordering and zero counts; preserve all authored UV corners |
|
||||
| `10018380`, `10023ec0`, `1001ea20`, `100085b0`, `100243c0`, `10024760`, `100187e0`, `100211f0` | Lighting, engine LOD, wind level, frond, branch texture control, flare, shadow and user-data field widths | Safely traverse these sections to retain subsequent metadata |
|
||||
| `1001f2d0` | Sphere/cylinder/box position and dimensions | Expose collision objects in original coordinates; no automatic runtime collision integration |
|
||||
| `10022fc0`, `10023060` | Near/far clamped LOD response | `SpeedTreeSptInfo::EvaluateLod(distance)`; caller supplies distance, no x86 approximate-sqrt emulation |
|
||||
| `1001b8a0`, original `SpeedTreeWrapper::LoadTree` | Property size applied before Compute | Positive factory size overrides SPT size; zero/default uses authored size |
|
||||
|
||||
The factory default size is now zero (use SPT size). A positive argument is an
|
||||
explicit override. Missing/corrupt SPT input returns null; callers wanting a
|
||||
placeholder must use `CreateProcedural`. Failed SDK property registration leaves
|
||||
the previous registration unchanged. Existing forest instance creation still
|
||||
has its documented procedural fallback for an unknown CRC.
|
||||
|
||||
Texture names are derived from counted fields, including non-ASCII author paths,
|
||||
instead of guessing `CompositeMap` prefixes from arbitrary file bytes. The SDK
|
||||
retains its TGA-to-DDS conversion convention for converted client assets; this is
|
||||
a resource adaptation policy, not an assertion that the DLL itself performs that conversion.
|
||||
Raw UV quads are preserved with no implicit V inversion; the legacy rectangle
|
||||
API now returns their bounds. Generated foliage uses the raw quads when available.
|
||||
|
||||
## Validation (2026-10-11)
|
||||
|
||||
- Debug SDK tests: procedural geometry/forest behavior and SPT format regressions.
|
||||
- AddressSanitizer + UndefinedBehaviorSanitizer: both SDK tests and all 606 SPT
|
||||
files under the original AVA2 pack_maker passed without reported memory/UB errors.
|
||||
- Corpus: 606 basic metadata parses succeeded; 323 consumed the complete file.
|
||||
The other 283 stop at token 21000, report `metadata_complete=false` and preserve
|
||||
only the already parsed metadata. The analyzed DLL's extension dispatcher also
|
||||
does not handle 21000. This is not a claim of full compatibility with that extension.
|
||||
- Regressions cover wrong size/LOD tokens, one-byte fields, every truncated base
|
||||
prefix, corrupt magic, oversized counts, truncated/non-finite UV payloads,
|
||||
zero/reordered atlas groups, more than 64 atlas entries, embedded token bytes
|
||||
inside strings, unsupported extensions, rotated UV quads and explicit size overrides.
|
||||
- The sibling client's `ava2.speedtree_forest` integration test is built against
|
||||
this external SDK, with a corrected valid synthetic SPT fixture.
|
||||
|
||||
Reproduce without committing client resources or build products:
|
||||
|
||||
```sh
|
||||
cmake -S speedtree -B build/speedtree-check -DCMAKE_BUILD_TYPE=Debug
|
||||
cmake --build build/speedtree-check -j 8
|
||||
ctest --test-dir build/speedtree-check --output-on-failure
|
||||
build/speedtree-check/spt_format_test '/path/to/AVA2/1. Client DEV/pack_maker'
|
||||
```
|
||||
|
||||
## 2026-10-11 Branch generation and wind follow-up
|
||||
|
||||
SPT branch levels now retain their nine BezierSpline fields and segment settings.
|
||||
The generator uses the recovered length (`6004`), radius (`6005`), radius profile
|
||||
(`6006`), growth (`6003`) and declination (`6007`) curves to build connected limb
|
||||
hierarchies. Tree assets with branch levels no longer select their shape from
|
||||
filename-based pine/oak rules. Radius/growth vary along each limb; normals use
|
||||
longitudinal/circumferential tangents including taper and curvature. Geometry is
|
||||
bounded to four authored levels, 128 limbs, 24 radial segments and 32 length rings.
|
||||
Grass/shrub fallback and explicit procedural models retain their simpler geometry.
|
||||
|
||||
The random stream follows the Park-Miller multiplier/modulus (`10027a50`), the
|
||||
128-entry shuffle (`10027f50`, `10027bb0`) and DLL scaling constant at
|
||||
`0x1015c510` (`2^-31`); `0x1015c514` confirms a shuffle index multiplier of 128.
|
||||
Each model owns its stream, so geometry does not depend on global RNG state or
|
||||
model creation order. Authored seed affects orientation and size variance;
|
||||
positive property size uses the supplied property variance, now forwarded by
|
||||
both SDK and AVA2 forest adapters. Seed zero maps deterministically to one here;
|
||||
the original time-dependent seed-zero behavior is not reproduced.
|
||||
|
||||
Spline parsing follows `10025f00` / `10026520`: min/max/variance plus nodes with
|
||||
position, normalized tangent and handle length. Signed variance is preserved
|
||||
(three real SPTs have negative spline variance). Evaluation now reproduces the recovered 500-entry parameter sampling and
|
||||
x-resampling table, followed by the original 499-scaled lookup. Bitwise equality
|
||||
with x87 execution has not been verified. Branch attachment locations, counts,
|
||||
orientation frames, leaf placement and generation call order remain SDK policies.
|
||||
|
||||
Wind now uses the recovered indexed, weighted affine transform from `10011e10`:
|
||||
`p' = p + w * (M * p - p)`. Optional column-major local-space matrices are supplied
|
||||
through `WindParameters::matrices`; absent matrices use synthesized rotations.
|
||||
The fallback is still approximate; forest instances now supply the original
|
||||
AVA2 source-level four-matrix controller described below.
|
||||
Leaf cards rock around their pivot using one shared phase/weight per card,
|
||||
strength zero is neutral, and inverse-transpose normals follow deformation.
|
||||
World wind direction is converted into the instance's local frame before
|
||||
deformation, rather than rotating the wind along with the instance yaw.
|
||||
|
||||
The reference GLSL uses the same weighted transform, generated-wind frequencies,
|
||||
gust settings, leaf pivot and normal rules. Its interface now includes vertex
|
||||
attribute location 6 (`wind_matrix_index`) and a std140 WindBlock at binding 3:
|
||||
four column-major mat4 values plus vec4 settings `(matrixCount, gustFrequency,
|
||||
gustStrength, 0)` and a second vec4 `(legacyLeafEnabled, leafPhase, rockingRange,
|
||||
rockingFrequency)`. Set legacyLeafEnabled to zero for procedural rocking; a zero
|
||||
rockingRange disables legacy rocking. Default settings are `(0, 0.8, 0.5, 0)`; custom matrices support
|
||||
up to four groups in this reference shader. Diffuse sampler binding is now 4,
|
||||
avoiding a descriptor conflict with the vertex FrameBlock at binding 0. Uploaders
|
||||
must use the new vertex stride/offset and block layout. CPU supports additional
|
||||
matrix groups; CPU/GLSL correspondence assumes the same supplied groups and a
|
||||
yaw plus uniform positive instance scale. AVA2 currently uses CPU-transformed
|
||||
draw data and does not upload this optional GLSL interface.
|
||||
|
||||
Validation: branch/wind regressions cover spline endpoints/midpoint, signed
|
||||
variance, invalid curve counts, repeated/different seeds, filename-independent
|
||||
authored shape, radius curves, property size/variance, zero wind, weighted affine
|
||||
positions, inverse-transpose normals, anchor weights, world wind under yaw,
|
||||
coherent leaf cards, and world transform order. All 606 original SPTs generate
|
||||
finite, bounded, indexed geometry and finite wind positions under ASan/UBSan.
|
||||
Both reference shader stages compile to SPIR-V with glslc. This is static shader
|
||||
validation; GPU execution and Windows DLL output comparison have not been done.
|
||||
|
||||
## 2026-10-11 Original runtime primitives and forest integration
|
||||
|
||||
- `10026aa0`, `10026870`, `10025e00`: cached 500-entry Bezier parameter sampling,
|
||||
x-resampling at i/500, exact last-node endpoint, and 499-scaled runtime queries
|
||||
using DLL constant 0x1015c4b8. A linear curve queried at 0.5 returns approximately
|
||||
0.499, preserving the original sampling convention instead of direct inversion.
|
||||
- `SpeedTreeLib/SpeedTreeForest.cpp::SetupWindMatrices`: four frequency pairs,
|
||||
35-degree strength-dependent throw, strength*20 frequencies, compound X/Y
|
||||
rotations and phase rescaling when strength changes. Static/global phase state
|
||||
is replaced by per-controller state. Matrices are converted from source Z-up
|
||||
to SDK Y-up by an explicit basis permutation.
|
||||
- `10025480`, `100254d0`, `10025510`: legacy leaf rocking range/frequency metadata
|
||||
and strength-change phase offset. SDK and AVA2 forest updates pass the matrices
|
||||
and phase into CPU deformation; GLSL exposes the same legacy waveform settings.
|
||||
Leaf per-group phase still comes from generated cards, not the unrecovered
|
||||
original orientation/rocking group table.
|
||||
- `1001d630`, `100207a0`: discrete LOD bucket selection, boundary clamping and two
|
||||
alpha-test thresholds during overlap/exponent transitions. These helpers are
|
||||
exposed through SelectDiscreteLod and SelectLodTransition. They do not create
|
||||
original per-LOD geometry. The later billboard milestone below connects them to the client.
|
||||
- Parsed branch scalar/flag fields and LOD configuration are retained for future
|
||||
topology/LOD recovery rather than discarded.
|
||||
|
||||
Active client build and five targeted tests pass; four SDK tests and all 606
|
||||
SPT metadata/generation/deformation checks pass under ASan/UBSan. Both GLSL stages
|
||||
compile to SPIR-V. Source matrices, phase continuity, zero-strength identity,
|
||||
controller isolation, sampled-curve quirks and LOD alpha thresholds have dedicated
|
||||
regressions. Evidence is under the sibling client's
|
||||
build/verification/speedtree-original-runtime/.
|
||||
|
||||
The user selected static recovery because no Windows execution environment is
|
||||
available. No original DLL execution, visual comparison or full-equivalence
|
||||
claim is made. This does not mark the entire original SpeedTree implementation
|
||||
complete; the remaining items below are actual missing behavior.
|
||||
|
||||
## 2026-10-11 Billboard generation and client distance switching
|
||||
|
||||
- `1001ebb0`, `10021840`: retain horizontal (`10006`/`20003`) and 360-degree
|
||||
(`10007`/`20004`) flags, including supplemental overrides. Token `20005` is
|
||||
preserved as eight raw floats without guessing its purpose.
|
||||
- `10020390`: SelectBillboardViews reproduces the half-step angle remapping,
|
||||
reversed atlas indices, cyclic endpoint wrap and composition of view-angle and
|
||||
distance alpha-test thresholds. Invalid/missing atlas entries are bounded;
|
||||
fully rejected draws are omitted. Threshold base remains the AVA2 value 84.
|
||||
- `100212c0`, `10020560`: BuildBillboardMeshes supplies vertical camera-facing
|
||||
quads and optional horizontal quads at the bounds' midpoint, using the last
|
||||
atlas quad for horizontal UVs and preserving all four original UV pairs.
|
||||
Bounds are cached from our generated geometry. Vertical width uses the greater
|
||||
horizontal extent and the quad is centered on those bounds; these are SDK
|
||||
adaptations until original geometry/dimension computation is recovered.
|
||||
- AVA2 passes its camera into model draw construction, converts it through inverse
|
||||
instance yaw/scale, and selects the final leaf-to-billboard transition. Near
|
||||
trees retain generated geometry; far trees submit billboard quads. If LOD
|
||||
distances or billboard UVs are missing, generated geometry remains available.
|
||||
Branches and leaves currently share the final silhouette transition, with
|
||||
branch alpha testing enabled while fading. Original per-component LOD meshes
|
||||
and branch disappearance scheduling remain outstanding.
|
||||
- Billboard vertices carry zero wind weights and are not leaf-rocking cards.
|
||||
Their geometry remains stable as time/strength changes.
|
||||
|
||||
Validation: active client application builds and all five targeted tests pass.
|
||||
Four SDK tests pass under ASan/UBSan. The 606-file corpus generates/deforms
|
||||
successfully under the sanitizers; 462 files produce valid billboard meshes.
|
||||
Regressions cover flags/overrides, raw supplemental UVs, horizontal planarity,
|
||||
atlas corners, angle wrap, threshold composition, near/transition/far draw
|
||||
selection, instance yaw/scale and wind-independent billboard positions.
|
||||
No DLL execution or rendered image comparison was performed.
|
||||
|
||||
## 2026-10-11 Frond geometry and extension 21000 payload
|
||||
|
||||
Recovered frond metadata from `100085b0`, cross-checked with serializer
|
||||
`10008ac0` and constructor `100082c0`: start branch level (13002), blade/profile
|
||||
mode (13003), blade count (13004), profile spline (13005), profile sample count
|
||||
(13006), enabled flag (13007), texture list (13008), LOD fields (13009..13013),
|
||||
segment override (14007) and reduction mode (14008). Each texture retains its
|
||||
filename, aspect ratio (14003), size scale (14004) and angle range (14005/14006).
|
||||
LOD/reduction configuration is retained but does not yet generate reduced meshes.
|
||||
|
||||
`10002450` switches enabled branches at/after the authored frond level away from
|
||||
branch tubes. The SDK now applies that same level switch to its approximate
|
||||
hierarchy, generates fronds along the branch centerlines, and avoids duplicate
|
||||
leaf cards on terminal frond limbs. Authored fronds override the old filename
|
||||
heuristic that previously rendered grass/bush-named SPTs as generic planes.
|
||||
|
||||
- `10009040`: texture half-width uses centerline length * 0.5 * aspect * size
|
||||
scale; angle sampling retains the authored interval and alternates sign.
|
||||
- `10009740`: blade mode emits multiple paired-vertex strips around the limb,
|
||||
with length-normalized V coordinates.
|
||||
- `1000b6d0`, `1000a820`: profile mode emits 2*profile_samples-1 symmetric
|
||||
cross-section vertices, with the spline offset relative to its center value.
|
||||
- Atlas UVs use all four corners through bilinear interpolation; individual
|
||||
textures are used when no composite atlas is supplied. Fronds receive branch
|
||||
wind matrix weights, zero leaf-rocking weights, alpha testing and double-sided
|
||||
client draws. Radius and cached billboard bounds include frond vertices.
|
||||
|
||||
Limits/adaptations: the underlying limb scheduling and frames remain approximate;
|
||||
texture choice uses deterministic SDK scheduling rather than original random
|
||||
call order; blade/profile counts are capped for bounded work; the original
|
||||
blade-edge averaging, profile-frame smoothing, normal/tangent construction and
|
||||
per-level frond reduction have not been reproduced exactly. Generation has a
|
||||
65535-vertex budget per material. Default missing profile data produces a flat
|
||||
profile instead of reconstructing the DLL constructor's default curve.
|
||||
|
||||
Corpus investigation: every one of the 283 extension-21000 occurrences contains
|
||||
21000 + float followed by 21001 + float, followed by unsupported token 22000.
|
||||
The reader now preserves the pair in extension_21000 with has_extension_21000.
|
||||
Their meaning is unresolved, and no matching parser handler was found in the
|
||||
current DLL decompilation. This is an observed corpus grammar, not a recovered
|
||||
DLL algorithm. No guessed rendering effect is applied. The subsequent extension
|
||||
remains explicitly unsupported; completeness stays 323/606, with zero rejected
|
||||
files. Truncated/non-finite/missing-marker payloads are rejected.
|
||||
|
||||
Verified: ava2_client builds; five targeted active tests pass; four SDK tests and
|
||||
606-file metadata/generation/deformation checks pass under ASan/UBSan. All 337
|
||||
SPTs with enabled fronds produce frond geometry, and 462 produce billboard meshes.
|
||||
Tests cover both frond modes, dimensions, disabled state, source filename
|
||||
heuristics, zero wind, vertex/index limits, finite deformation and client draws.
|
||||
Evidence is in ../ava2-client/build/verification/speedtree-fronds/.
|
||||
|
||||
## 2026-10-12 Authored leaf cards and static map collision
|
||||
|
||||
Leaf parsing now retains each definition's flag, color, scalar, filename, pivot
|
||||
(4004), placement vector (4005) and dimensions (4006), rather than discarding its
|
||||
vectors. Defaults and storage offsets were checked in 10015a60/10014930.
|
||||
The obsolete 4007 scalar remains intentionally ignored as in the DLL reader.
|
||||
|
||||
10014b60 generates four corners from the authored width/height and pivot. Even
|
||||
variants use 1-pivot.x; odd variants use pivot.x. BuildLeafCorners preserves this
|
||||
asymmetric mirrored-pivot rule. Authored branch leaf clusters now emit a single
|
||||
card with these offsets, scaled by generated_height/authored_size, instead of
|
||||
two generic centered planes. Original curve-driven placement and exact variant
|
||||
selection are still not reconstructed.
|
||||
|
||||
OrientLeafOffset implements the recovered composition Rz(azimuth) * Ry(pitch) *
|
||||
Rx(rocking), explicitly converting source Z-up and SDK Y-up. CPU evaluation and
|
||||
AVA2 draw construction pass camera coordinates through inverse instance yaw;
|
||||
rotation and rocking preserve each card's pivot. Conservative pivot-sphere
|
||||
bounds prevent camera rotation from escaping the cached static-card bounds.
|
||||
|
||||
10015900 initializes group phases in [0,10000]; 10014b60 multiplies each phase by
|
||||
variant+1 before 10025510 evaluates the native leaf waveform. The SDK now uses
|
||||
three deterministic default groups with that multiplier and the native waveform.
|
||||
It does not reproduce the original global RNG call sequence or arbitrary group
|
||||
count setters. Camera facing uses the tree-to-eye direction in AVA2, whereas the
|
||||
original runtime uses its global camera view direction. Nonzero orientation
|
||||
perturbations, LOD card growth and original per-leaf normal/AO computation remain
|
||||
unrecovered. New authored card fields are CPU metadata; the reference GLSL has
|
||||
not been extended to execute this authored-card path.
|
||||
|
||||
AVA2 static map collision now follows the source-level
|
||||
SpeedTreeWrapper::OnUpdateCollisionData policy: sphere/cylinder shapes participate,
|
||||
CO_BOX is skipped. AreaData-loaded tree instances register collision-only proxies
|
||||
in MapObjectManager's spatial index; building draw lists and object counts are
|
||||
unchanged. Shape centers swap source Y/Z and use the rendered instance yaw;
|
||||
positions/dimensions use generated_height/authored_size and instance scale.
|
||||
This scale adaptation has not been compared to the DLL's computed collider output.
|
||||
|
||||
Queries optionally receive actor sphere-center height. Sphere checks include the
|
||||
vertical distance; cylinder checks use the original CollisionData.cpp vertical
|
||||
interval rejection and axis-segment distance. Old callers without height retain
|
||||
2D projected queries. Actor movement/target completion now supply terrain height
|
||||
(or current actor Y) plus the 30-unit collision radius. This is a single ground
|
||||
sphere approximation, not the original bone-attached multiple dynamic spheres,
|
||||
continuous swept collision or full movement adjustment algorithm. Horizontal
|
||||
normals enable the existing sliding path. Weak lifetime tokens invalidate proxies
|
||||
on instance deletion/forest clearing/destruction; map clearing removes them.
|
||||
Programmatic tree creation or later instance pose edits outside AreaData loading
|
||||
are not automatically registered/synchronized with these static proxies.
|
||||
|
||||
Verified: active application builds; six targeted SDK/client/render tests pass.
|
||||
Four SDK tests plus 606 generated/deformed corpus models pass under ASan/UBSan:
|
||||
357 use authored leaf cards, 337 have fronds, 462 have billboards. The corpus now
|
||||
also checks native wind matrices, camera orientation, translated/yawed/scaled
|
||||
instances and finite normals. Client SpeedTree/collision tests pass under the
|
||||
sanitizers. Sanitized render_3d initially skipped in the isolated empty run dir;
|
||||
it was then run directly with the existing populated active run dir and passed.
|
||||
Tests cover pivot/mirroring, rotation order, zero wind, coherent group phase,
|
||||
property resizing, camera transforms, sphere/cylinder footprints and heights,
|
||||
box omission, movement blocking/height clearance, spatial queries and lifetime
|
||||
invalidation. No DLL execution or visual parity comparison was performed.
|
||||
|
||||
## 2026-10-12 Independent LOD, branch sampling, multiple spheres and GPU wind
|
||||
|
||||
Independent branch, leaf and frond LOD mesh streams are now built once per model.
|
||||
Grid topology records allow fewer longitudinal/radial samples while preserving
|
||||
endpoints and closed branch seams. Leaves use nested, seeded card subsets and
|
||||
pivot-relative growth 1+level*growth (9009 / 1001e840, 10020960, 10014b60).
|
||||
AVA2 chooses branch/frond detail independently, renders the two selected leaf
|
||||
levels with their recovered alpha thresholds, and includes the billboard as the
|
||||
last leaf level only when its atlas exists. Bounds include all LODs/card rotations;
|
||||
a transformed bounds test follows sphere culling to avoid oversized spheres
|
||||
keeping wholly behind-camera trees. Level count and growth are bounded to eight.
|
||||
The topology decimator/card subset ranking are SDK choices, not the DLL's original
|
||||
importance/clustering reducers; independent meshes do not imply original LOD parity.
|
||||
|
||||
Re-exported the original DLL into /tmp/ava2-speedtree-static (1219 functions).
|
||||
10002450 and disassembly 100036d2..100036e3 confirm child count truncation from
|
||||
6012 * branch_length / tree_size. Fields 6010/6011 are the attachment interval.
|
||||
Nonterminal children reseed with parent_seed+3 per child; the first interval is
|
||||
85..95% of the full interval. SampleBranchAttachment restores this rule; terminal
|
||||
sampling uses the running stream and full interval. Nonterminal azimuth sampling
|
||||
accounts for the parent percentage draw and child length-variance draw before the
|
||||
[-180,180] draw. Generation now traverses depth-first and interpolates attachment
|
||||
positions between centerline samples instead of snapping to a ring. These rules
|
||||
are corroborated by static control flow and independent integer/shuffle reference
|
||||
values. The complete original angular frame, leaf distribution and global RNG
|
||||
call sequence are still missing; full precise distribution has NOT been achieved.
|
||||
|
||||
Work remains bounded to 256 nodes and 65535 vertices per generated material,
|
||||
with radial/profile/level caps. WasGenerationTruncated exposes node/vertex/density
|
||||
budget truncation. Earlier fixed scheduling invented branches even when authored
|
||||
density implied none; current corpus mesh counts therefore differ from the earlier
|
||||
milestones. Truncation reporting is diagnostic, not a claim of original completeness.
|
||||
|
||||
RaceData now reads all collision attachments/spheres from MSM (source GameType.cpp
|
||||
LoadAttachingData/LoadCollisionData). BODY=1 spheres drive movement; DEFENDING and
|
||||
ATTACKING data remain available but do not block movement. Unattached source
|
||||
positions use the actor world transform; attached main-model spheres use the live
|
||||
bone world transform at the actor animation time. Radius stays authored as in the
|
||||
source. All body spheres are tested for movement/target completion and sliding,
|
||||
with a legacy ground-sphere fallback when usable body data is absent. Tests cover
|
||||
multiple spheres where only the later sphere blocks, and a real right-hand bone
|
||||
attachment. Other model indices, mounted-horse sharing, original swept/last-position
|
||||
collision and original collision movement adjustments remain outstanding.
|
||||
|
||||
The actual AVA2 HardwareScene Metal and embedded SPIR-V scene shaders now perform
|
||||
native four-matrix foliage deformation, inverse-transpose normals, generic leaf
|
||||
rocking and authored leaf camera/rocking rotation. Raw model/LOD streams are cached
|
||||
and shared across instances; per-frame matrices/phase/view parameters are uploaded
|
||||
as uniforms/instance data. The forest enables this path for native four-matrix
|
||||
frames. Software rendering materializes the SDK CPU result through an owned-model
|
||||
fallback callback. Billboard quads remain undeformed. Header layout is 576 bytes;
|
||||
vertex layout includes pivot XYZ/native phase at attribute 6. The earlier standalone
|
||||
foliage_shaders.h remains a reference and is not the active scene pipeline.
|
||||
|
||||
Validation: application build and seven targeted tests pass, including real Metal
|
||||
execution. Pixel masks from GPU matrix-only, generic-rocking and authored-camera
|
||||
paths, using compound controller rotations plus translation, are compared to SDK
|
||||
CPU positions/normals (edge tolerance <32 pixels on 64x64 targets and <=2 red-channel
|
||||
levels for shared lit pixels).
|
||||
GLSL compiles to embedded SPIR-V; Vulkan execution has not been tested. Four SDK
|
||||
tests and all 606 corpus models/all generated LODs pass ASan/UBSan finite/index/
|
||||
wind/camera checks. Client multi-sphere/bone/fallback tests and populated render_3d
|
||||
asset tests also pass under the sanitizers. Corpus now has 462 billboard models,
|
||||
282 frond models and 248 models with authored leaf cards; 347 report generation
|
||||
budget truncation. No original DLL execution or original output comparison exists.
|
||||
|
||||
## 2026-10-12 Generation baseline, branch-entry scheduling and terminal leaves
|
||||
|
||||
The first three planned work areas now have a reproducible baseline and another
|
||||
static-recovery implementation milestone. This does not complete original
|
||||
branch/frame generation or establish binary equivalence.
|
||||
|
||||
- `tools/generation_baseline.cpp` sorts input paths and writes JSONL with source
|
||||
seed, authored level count, generated nodes per level, terminal leaf calls,
|
||||
bounds, allocation-limit reasons and per-LOD vertices/triangles/grid/hash data.
|
||||
Hashes use explicit float/index fields, never struct padding. The baseline
|
||||
captured before these changes contains 213 files under pack_maker/Tree.
|
||||
`tools/generation_samples.json` pins representative source paths, SHA-256s and
|
||||
seeds; synthetic fixtures exercise repeated/different seeds and large budgets.
|
||||
`tools/compare_generation_baselines.py` compares inventories and reports
|
||||
topology/bounds changes and resolved/new truncation.
|
||||
- `10002450` entry draws are now length(6004), azimuth, angle(6007), gravity(6001),
|
||||
radius(6005), flexibility(6002), preserving variance draws even for zero
|
||||
variance. Missing sampled curves consume no draw. Nonterminal attachment
|
||||
sampling and the parent wind-profile draw use the reseeded shared stream;
|
||||
child entry reseeds again and discards one [0,100] draw. Child curve position
|
||||
is normalized within the authored attachment interval, rather than using the
|
||||
absolute parent attachment position. Tests use an independent integer/shuffle
|
||||
oracle to check each entry result and the trailing stream.
|
||||
- `10026460` is a distinct perturbation sampler: nearest cached index
|
||||
`int(position*499+0.5)`, amplitude `sample*variance`, no min/max mapping. Its
|
||||
two draws per frame are scheduled separately from normal curve evaluations.
|
||||
Token 6003 is a wind profile, not a growth spline; the approximate gravity
|
||||
centerline now uses token 6017. Original incremental frame/gravity integration
|
||||
still needs recovery, and sampled perturbations are not yet applied to frames.
|
||||
- Longitudinal rings now use the authored 6009 count, matching the original
|
||||
allocation of count+1 centerline records, instead of doubling/clamping to 32.
|
||||
Unsupported fixed child-length shortening and 0.65 radius shrinking were
|
||||
removed. The base-profile radius condition now uses the interpolated parent
|
||||
attachment radius and DLL float constant `1004c1a4 = 0.85`.
|
||||
- `10003af0` gets a distinct terminal path when authored leaves are present and
|
||||
the last level is not being emitted as a frond. It samples length/longitudinal
|
||||
segments, then azimuth, and uses the recovered 60-degree tilt (double constant
|
||||
`1004c1c8 = 1.0471975389728654`). It emits one card, not a complete terminal tube
|
||||
followed by three cards. The inherited frame remains approximate.
|
||||
- `10004380`/`10004540` ordinary leaf variants include mirrored pairs, selected
|
||||
using integer [0,1000000] sampling modulo the pool. Rocking group uses integer
|
||||
[0,10000] modulo the three default groups. One shared [-scalar,scalar] color
|
||||
perturbation is applied to authored RGB. Special flagged-leaf selection via
|
||||
`100044c0`, placement/orientation/lighting details and arbitrary rocking group
|
||||
counts remain incomplete; flagged variants are not substituted into the
|
||||
ordinary pool.
|
||||
- The SDK vertex indices, CPU render commands and SDL GPU index uploads are all
|
||||
uint32. Consequently the old per-material 65535-vertex limit was unnecessary
|
||||
and has been removed for branches/fronds. Mesh splitting is not required by
|
||||
these active consumers. The per-model guards are now 16384 branch nodes and
|
||||
2000000 base-geometry vertices, with terminal cards charged to vertices rather
|
||||
than branch nodes. Radial/length safety limits are 256/1024. These are SDK
|
||||
allocation guards, not recovered original limits; every triggered guard is
|
||||
exposed through GetGenerationStats/WasGenerationTruncated. Larger trees can
|
||||
consume more CPU/GPU memory than the earlier truncated approximation.
|
||||
- Zero-length fronds without children can produce empty geometry; public bounds
|
||||
now remain finite zero bounds in this case instead of infinities.
|
||||
|
||||
Validation: SDK four tests and active client seven targeted tests pass, and the
|
||||
active ava2_client builds. SDK ASan/UBSan four tests and all 606 original resources
|
||||
across all LODs pass finite/index/native-wind/camera checks. Two complete JSONL
|
||||
snapshot runs are byte-identical, including finite bounds. Synthetic regressions
|
||||
cover 98035 trunk vertices, 70000 leaf vertices, terminal hierarchy accounting,
|
||||
entry/perturbation draw semantics and explicit oversized-input guard reporting.
|
||||
The fixed 213-file comparison reduces truncation from 132 to 1. Full 606-file
|
||||
corpus truncation falls from the previous milestone's 347 to 3; the remaining
|
||||
three are identical copies of b3_umbrellathorn_rt_flowers4.spt (SHA-256
|
||||
44ec99e53b3158a6619ec7a5cb4110bfb67ff9943224b068a8bc99fa1d92c0d0), still hitting
|
||||
16384 nodes. This umbrella-thorn sample was not flagged in the old 213-file
|
||||
baseline; the new scheduling reaches the guard and comparison.json explicitly
|
||||
reports it as new_truncation. Its original full shape/size remains unresolved.
|
||||
Current output has 462 billboard, 336 frond and 263 authored-leaf
|
||||
models. Counts/hashes are replacement baselines, not original DLL oracle outputs.
|
||||
Evidence: sibling client's build/verification/speedtree-generation-baseline/.
|
||||
|
||||
## 2026-10-12 Inherited branch frames, special leaf gating and axial spacing
|
||||
|
||||
- `10002450` / `10005960`: frames now retain a full source Z-up row-vector basis.
|
||||
Local azimuth and compound roll/pitch rotations multiply the inherited parent
|
||||
basis. Child branches and terminal leaves inherit the frame of the actual
|
||||
attachment segment, rather than rebuilding a frame from only its direction.
|
||||
The first two `10026460` perturbation arguments are both zero (assembly at
|
||||
10002828/10002854); subsequent arguments are the axial segment percentage.
|
||||
Perturbations now rotate actual frames and geometry instead of being discarded.
|
||||
- Default source Z-up gravity follows the recovered angular influence:
|
||||
`-2*(profile-0.5)*(1-abs(pi/2-inclination)/(pi/2))*inclination*gravity`, rotating
|
||||
about `up x forward`. Vertical directions receive no gravity rotation, avoiding
|
||||
a zero-axis singularity. Positions advance along the preceding frame direction
|
||||
by the change in axial distance; no artificial fixed lateral bend remains.
|
||||
Nondefault original gravity/global direction configuration is still unsupported.
|
||||
- `10024760` retains token 16002 as the branch object's +0x24 exponent (default 1
|
||||
in `100061b0`). Assembly 10002fbb..10002fcb applies pow(ring/segments, exponent).
|
||||
Axial queries, profiles and perturbations now use that percentage. `10005110`
|
||||
attachment searches use cumulative physical distance and interpolate the
|
||||
enclosing segment, not uniform ring indices. Four corpus files have exponent
|
||||
zero; this is valid and intentionally follows the original pow behavior.
|
||||
Negative or >32 exponents still invoke an explicit SDK tessellation guard.
|
||||
Remaining flare parameters and bark texture controls are not restored.
|
||||
- Frond lateral/profile directions now follow each centerline frame, rather than
|
||||
one constant branch basis. Original edge averaging/profile smoothing remains
|
||||
separate unfinished work.
|
||||
- `10015a60` and constructor `10015800`: preserve special-leaf threshold token
|
||||
3000 (default 0.75), ancestor depth 3001 (default 1), probability 3002 (default
|
||||
0.8). `100044c0` tests the leaf position at depth zero, otherwise the selected
|
||||
ancestor's branch attachment position, stopping at the root. Strict threshold
|
||||
equality fails and consumes no RNG; probability equality succeeds.
|
||||
- `10004380` / `10004540`: flagged leaves now have a separate mirrored variant
|
||||
pool. Its gate consumes a probability draw only above threshold; accepted
|
||||
special variants use integer [0,100000] modulo the pool, ordinary variants
|
||||
use [0,1000000]. A failed gate falls back to ordinary variants; an empty ordinary
|
||||
pool emits no card. Generation stats/baselines expose special_leaf_cards.
|
||||
Existing default three rocking groups/color perturbation remain, but leaf
|
||||
normal construction, placement/orientation details and matrix group assignment
|
||||
still require recovery.
|
||||
|
||||
Regression coverage includes known source rotations, inherited frames, gravity
|
||||
sign/vertical singularity, 1024-step basis orthogonality, actual deterministic
|
||||
perturbation geometry, nonuniform/zero axial spacing and attachment distances,
|
||||
special threshold equality/no-draw semantics, probability draw count, ancestor
|
||||
traversal, forced special/ordinary variants and authored material colors.
|
||||
SDK four tests, client seven targeted tests and active application build pass.
|
||||
ASan/UBSan four SDK tests and the complete 606-resource/all-LOD/native-wind/camera
|
||||
corpus pass. Two snapshots are byte-identical, with 19 resources producing 68945
|
||||
special leaf cards. There is no new truncation; the same three umbrella-thorn
|
||||
copies remain guarded. Evidence is in the sibling client's
|
||||
build/verification/speedtree-frames-special-leaves/VALIDATION.md.
|
||||
This is additional static recovery, not full original DLL equivalence. Global RNG
|
||||
initialization/leaf-group scheduling, alternate source directions and complete
|
||||
leaf/frond geometry/lighting still differ; original LOD reducers remain unfinished.
|
||||
|
||||
## 2026-10-12 Frond limbs with terminal foliage: umbrella-thorn truncation fix
|
||||
|
||||
`10002450` determines the last-level leaf path from the branch level count,
|
||||
independently of frond activation. It calls `10003af0` for terminal leaves while
|
||||
frond generation applies to the current limb. The replacement incorrectly
|
||||
excluded terminal leaf generation when fronds were enabled at the last level.
|
||||
This expanded high-density foliage into complete terminal branch/frond nodes.
|
||||
|
||||
The three identical b3_umbrellathorn_rt_flowers4.spt assets have five branch levels,
|
||||
fronds starting at level 3, and level-3 child density 800. The replacement now
|
||||
emits level-3 frond limbs and level-4 leaves/flowers, without terminal tubes/fronds.
|
||||
Each copy generates 87 branch nodes (1/5/15/66), 18814 terminal cards / 75256 leaf
|
||||
vertices, and identical geometry/bounds. No node or vertex limit is raised.
|
||||
|
||||
A synthetic regression combines active fronds with 17500 terminal leaf cards:
|
||||
one frond limb, zero terminal branch nodes, 70000 leaf vertices, no truncation.
|
||||
The correction also restores previously suppressed terminal cards in other
|
||||
frond assets. Full 606-resource output now reports zero generation truncation,
|
||||
462 billboard, 324 frond and 480 authored-leaf models. Twelve formerly reported
|
||||
frond models had fronds only in the erroneous terminal path; they now have leaf
|
||||
cards there, matching the recovered last-level dispatch.
|
||||
|
||||
Verification and source/copy evidence are in the sibling client's
|
||||
build/verification/speedtree-frond-terminal-fix/VALIDATION.md. Original DLL output
|
||||
parity is still unverified; other remaining differences are unchanged.
|
||||
|
||||
## Remaining differences
|
||||
|
||||
Independent LOD meshes, main-bone multiple body spheres and the native GPU wind
|
||||
path are operational. Default inherited frame/perturbation/gravity rotations and
|
||||
special-leaf gating are recovered. Remaining original branch/leaf distribution,
|
||||
global random initialization/group scheduling, nondefault direction configuration,
|
||||
exact LOD importance/clustering reducers, frond smoothing and
|
||||
billboard dimensions/component schedules remain incomplete. Generation budgets
|
||||
can truncate assets and are explicitly reported. Multiple-sphere collision still
|
||||
needs original swept response, additional model indices and horse integration.
|
||||
Programmatically spawned/moved tree collision synchronization is incomplete.
|
||||
Newer SPT 21000 values have unresolved semantics; 22000 and later blocks are
|
||||
unsupported. Vulkan/D3D runtime and original Windows DLL parity remain unverified.
|
||||
@@ -15,6 +15,7 @@ layout(location = 2) in vec2 in_TexCoord;
|
||||
layout(location = 3) in vec4 in_WindWeights; // [0]:Trunk, [1]:Branch, [2]:Leaf, [3]:Phase
|
||||
layout(location = 4) in vec3 in_LeafPivotOffset; // Leaf center to vertex
|
||||
layout(location = 5) in uint in_Diffuse;
|
||||
layout(location = 6) in uint in_WindMatrixIndex;
|
||||
|
||||
layout(std140, binding = 0) uniform FrameBlock {
|
||||
mat4 u_ViewProj;
|
||||
@@ -30,6 +31,15 @@ layout(std140, binding = 1) uniform InstanceBlock {
|
||||
float u_TreeHeight;
|
||||
};
|
||||
|
||||
// Upload settings=(matrixCount, gustFrequency, gustStrength, 0).
|
||||
// matrixCount=0 selects generated wind; custom local-space matrices need no strength rescaling.
|
||||
layout(std140, binding = 3) uniform WindBlock {
|
||||
mat4 u_WindMatrices[4];
|
||||
vec4 u_WindSettings;
|
||||
// (enabled, phase, authored rocking range, authored rocking frequency).
|
||||
vec4 u_LegacyLeafWind;
|
||||
};
|
||||
|
||||
layout(location = 0) out vec3 v_WorldPos;
|
||||
layout(location = 1) out vec3 v_WorldNormal;
|
||||
layout(location = 2) out vec2 v_TexCoord;
|
||||
@@ -50,46 +60,48 @@ void main() {
|
||||
float leafW = in_WindWeights.b;
|
||||
float phase = in_WindWeights.a;
|
||||
|
||||
// Level 0: Global Wind Gust Wave
|
||||
float gustSpatial = dot(u_TreeOrigin.xz, u_WindDir.xz * 0.04);
|
||||
float gust = sin(u_Time * 0.8 + gustSpatial) * 0.5 + 0.5;
|
||||
float effectiveWind = u_WindStrength * (0.8 + 0.4 * gust);
|
||||
vec3 direction = vec3(u_WindDir.x, 0.0, u_WindDir.z);
|
||||
direction = length(direction) > 1e-7 ? normalize(direction) : vec3(1.0, 0.0, 0.0);
|
||||
mat3 orientation = mat3(u_ModelMatrix);
|
||||
orientation[0] = normalize(orientation[0]);
|
||||
orientation[1] = normalize(orientation[1]);
|
||||
orientation[2] = normalize(orientation[2]);
|
||||
vec3 localDirection = transpose(orientation) * direction;
|
||||
vec3 axis = normalize(cross(vec3(0.0, 1.0, 0.0), localDirection));
|
||||
float spatial = dot(u_TreeOrigin.xz, direction.xz) * 0.005;
|
||||
float gust = 0.5 + 0.5 * sin(u_Time * u_WindSettings.y + spatial);
|
||||
float strength = max(0.0, u_WindStrength);
|
||||
|
||||
vec3 windCrossAxis = normalize(cross(vec3(0.0, 1.0, 0.0), u_WindDir));
|
||||
// Every corner of a tree leaf card shares this angle and pivot.
|
||||
float rock = 0.25 * strength * leafW * sin(u_Time * 8.0 + phase * 15.0);
|
||||
if (u_LegacyLeafWind.x > 0.0)
|
||||
rock = 3.141592653589793 * u_LegacyLeafWind.z * strength * leafW
|
||||
* sin(u_LegacyLeafWind.y * u_LegacyLeafWind.w + phase * 15.0);
|
||||
vec3 rotatedOffset = RotateAngleAxis(in_LeafPivotOffset, localDirection, rock);
|
||||
localPos += rotatedOffset - in_LeafPivotOffset;
|
||||
localNormal = RotateAngleAxis(localNormal, localDirection, rock);
|
||||
|
||||
// Level 1: Trunk bending (quadratic height response, length-preserving)
|
||||
float trunkAngle = (trunkW * trunkW) * effectiveWind * 0.12 * sin(u_Time * 1.2 + gustSpatial);
|
||||
localPos = RotateAngleAxis(localPos, windCrossAxis, trunkAngle);
|
||||
localNormal = RotateAngleAxis(localNormal, windCrossAxis, trunkAngle);
|
||||
|
||||
// Level 2: Branch sway
|
||||
if (branchW > 0.01) {
|
||||
float branchOsc = sin(u_Time * 2.5 + phase * 6.28 + gustSpatial * 2.0);
|
||||
float branchAngle = branchW * effectiveWind * 0.15 * branchOsc;
|
||||
localPos = RotateAngleAxis(localPos, windCrossAxis, branchAngle);
|
||||
localNormal = RotateAngleAxis(localNormal, windCrossAxis, branchAngle);
|
||||
uint count = uint(clamp(u_WindSettings.x, 0.0, 4.0));
|
||||
mat4 windMatrix = mat4(1.0);
|
||||
if (count > 0u) {
|
||||
windMatrix = u_WindMatrices[in_WindMatrixIndex % count];
|
||||
} else {
|
||||
float bend = 0.12 * strength * (1.0 + u_WindSettings.z * gust)
|
||||
* sin(u_Time * 1.5 + spatial + float(in_WindMatrixIndex % 4u) * 0.7);
|
||||
windMatrix[0].xyz = RotateAngleAxis(vec3(1.0,0.0,0.0), axis, bend);
|
||||
windMatrix[1].xyz = RotateAngleAxis(vec3(0.0,1.0,0.0), axis, bend);
|
||||
windMatrix[2].xyz = RotateAngleAxis(vec3(0.0,0.0,1.0), axis, bend);
|
||||
}
|
||||
|
||||
// Level 3: Leaf flutter and tumble around leaf pivot (Leaf Shimmering!)
|
||||
if (leafW > 0.01) {
|
||||
float leafOsc = sin(u_Time * 8.0 + phase * 15.0 + dot(localPos, vec3(1.0)));
|
||||
float leafAngle = leafW * (0.2 + 0.2 * gust) * leafOsc;
|
||||
|
||||
vec3 leafRel = in_LeafPivotOffset;
|
||||
vec3 rotatedOffset = RotateAngleAxis(leafRel, u_WindDir, leafAngle);
|
||||
localPos += (rotatedOffset - leafRel);
|
||||
localNormal = RotateAngleAxis(localNormal, u_WindDir, leafAngle);
|
||||
}
|
||||
|
||||
float weight = clamp(trunkW + 0.4 * branchW, 0.0, 1.0);
|
||||
mat3 linear = mat3(1.0) * (1.0 - weight) + mat3(windMatrix) * weight;
|
||||
localPos = linear * localPos + windMatrix[3].xyz * weight;
|
||||
if (abs(determinant(linear)) > 1e-7)
|
||||
localNormal = transpose(inverse(linear)) * localNormal;
|
||||
vec3 worldPos = (u_ModelMatrix * vec4(localPos, 1.0)).xyz;
|
||||
vec3 worldNormal = normalize((u_ModelMatrix * vec4(localNormal, 0.0)).xyz);
|
||||
|
||||
// Spherical / Canopy Normal Blending (removes paper-thin leaf look)
|
||||
vec3 crownCenter = u_TreeOrigin + vec3(0.0, u_TreeHeight * 0.65, 0.0);
|
||||
vec3 sphericalNormal = normalize(worldPos - crownCenter);
|
||||
worldNormal = normalize(mix(worldNormal, sphericalNormal, leafW * 0.65));
|
||||
vec3 worldNormal = normalize(transpose(inverse(mat3(u_ModelMatrix))) * localNormal);
|
||||
|
||||
// Canopy interior AO
|
||||
vec3 crownCenter = u_TreeOrigin + vec3(0.0, u_TreeHeight * 0.65, 0.0);
|
||||
float distToCenter = length(worldPos - crownCenter);
|
||||
v_CanopyAO = clamp(distToCenter / (u_TreeHeight * 0.45), 0.35, 1.0);
|
||||
|
||||
@@ -111,7 +123,7 @@ layout(location = 1) in vec3 v_WorldNormal;
|
||||
layout(location = 2) in vec2 v_TexCoord;
|
||||
layout(location = 3) in float v_CanopyAO;
|
||||
|
||||
layout(binding = 0) uniform sampler2D u_DiffuseAtlas;
|
||||
layout(binding = 4) uniform sampler2D u_DiffuseAtlas;
|
||||
|
||||
layout(std140, binding = 2) uniform LightBlock {
|
||||
vec3 u_SunDir;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <array>
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
@@ -18,6 +19,79 @@ struct UVRect {
|
||||
float v1 = 1.0f;
|
||||
};
|
||||
|
||||
// The original SPT stores four UV pairs, not necessarily an axis-aligned rectangle.
|
||||
using UVQuad = std::array<float, 8>;
|
||||
|
||||
struct CollisionObject {
|
||||
enum class Type { Sphere, Cylinder, Box };
|
||||
Type type = Type::Sphere;
|
||||
std::array<float, 3> position{};
|
||||
std::array<float, 3> dimensions{};
|
||||
};
|
||||
|
||||
class LegacyRandom {
|
||||
public:
|
||||
explicit LegacyRandom(uint32_t seed);
|
||||
float Uniform(float low = 0.0f, float high = 1.0f);
|
||||
private:
|
||||
double Next();
|
||||
uint32_t state_;
|
||||
std::array<float, 128> shuffle_{};
|
||||
};
|
||||
|
||||
struct BranchSpline {
|
||||
struct Point { float x, y, dx, dy, handle; };
|
||||
float minimum = 0, maximum = 0, variance = 0;
|
||||
std::vector<Point> points;
|
||||
std::array<float, 500> samples{};
|
||||
bool samples_ready = false;
|
||||
bool BuildSamples();
|
||||
static bool Parse(const std::string& text, BranchSpline& out);
|
||||
float Evaluate(float position, LegacyRandom* random = nullptr) const;
|
||||
// 10026460: nearest cached sample times variance, without min/max mapping.
|
||||
float EvaluatePerturbation(float position, LegacyRandom& random) const;
|
||||
};
|
||||
|
||||
struct BranchLevel {
|
||||
uint32_t radial_segments = 6;
|
||||
uint32_t length_segments = 3;
|
||||
float length_exponent = 1; // 16002, branch object +0x24.
|
||||
std::array<BranchSpline, 9> curves; // Tokens 6000..6007, 6017.
|
||||
std::array<float,5> scalar_fields{0.3f,1.0f,0.3f,1.0f,1.0f}; // 6010..6014.
|
||||
bool has_attachment_range = false, has_child_density = false;
|
||||
std::array<bool,2> flags{true,false}; // 6015,6016; retained for topology recovery.
|
||||
};
|
||||
|
||||
struct BranchEntrySample {
|
||||
float length, azimuth, angle, gravity, radius, flexibility;
|
||||
};
|
||||
// Entry draw order of 10002450. Unsampled curves consume no random values.
|
||||
BranchEntrySample SampleBranchEntry(const BranchLevel& level,float position,
|
||||
float treeHeight,LegacyRandom& random);
|
||||
|
||||
struct GenerationStats {
|
||||
static constexpr size_t max_nodes = 16384, max_vertices = 2000000;
|
||||
std::array<size_t,8> nodes_by_level{};
|
||||
size_t generated_vertices = 0;
|
||||
size_t terminal_leaf_calls = 0;
|
||||
size_t special_leaf_cards = 0;
|
||||
bool node_limit = false, vertex_limit = false, density_limit = false, tessellation_limit = false;
|
||||
};
|
||||
|
||||
struct SpecialLeafSettings {
|
||||
float minimum_position = 0.75f, probability = 0.8f;
|
||||
uint32_t ancestor_depth = 1;
|
||||
};
|
||||
bool SampleSpecialLeaf(float position,const std::vector<float>& ancestors,
|
||||
const SpecialLeafSettings& settings,LegacyRandom& random);
|
||||
// Source Z-up row-vector basis. Convert directions to SDK Y-up at the boundary.
|
||||
struct BranchFrame {
|
||||
std::array<std::array<float,3>,3> basis{{{1,0,0},{0,1,0},{0,0,1}}};
|
||||
BranchFrame Rotate(float azimuth,float roll,float pitch) const;
|
||||
BranchFrame ApplyGravity(float gravity,float profile) const;
|
||||
std::array<float,3> SdkAxis(size_t axis) const;
|
||||
};
|
||||
|
||||
// Unified vertex layout for modern GPU foliage rendering
|
||||
// Compatible with Vulkan, Metal, DX11/12, OpenGL
|
||||
struct SpeedTreeVertex {
|
||||
@@ -27,20 +101,57 @@ struct SpeedTreeVertex {
|
||||
float wind_weights[4]; // [0]: Trunk bend, [1]: Branch sway, [2]: Leaf flutter, [3]: Phase
|
||||
float leaf_pivot_offset[3]; // Vector from leaf cluster pivot to vertex (for rotation/tumble)
|
||||
uint32_t diffuse; // RGBA8 (Canopy AO in alpha/rgb, default 0xFFFFFFFF)
|
||||
uint32_t wind_matrix_index = 0;
|
||||
bool authored_leaf_card = false;
|
||||
float leaf_rocking_phase = 0;
|
||||
};
|
||||
|
||||
// Represents a submesh (Trunk or Leaf/Canopy)
|
||||
float SampleBranchAttachment(uint32_t seed,uint32_t child,float low,float high);
|
||||
float SampleBranchAzimuth(uint32_t childSeed);
|
||||
|
||||
struct SpeedTreeMesh {
|
||||
std::string name;
|
||||
std::vector<SpeedTreeVertex> vertices;
|
||||
std::vector<uint32_t> indices;
|
||||
std::string texture;
|
||||
struct Grid { uint32_t first, rows, columns; bool closed; };
|
||||
std::vector<Grid> grids;
|
||||
bool is_leaf = false;
|
||||
bool is_double_sided = false;
|
||||
bool alpha_test = false;
|
||||
float alpha_ref = 0.45f;
|
||||
};
|
||||
|
||||
struct LeafDefinition {
|
||||
bool flag = false;
|
||||
std::array<float,3> color{0.8f,0.8f,0.8f};
|
||||
float scalar = 0.2f;
|
||||
std::string texture;
|
||||
std::array<float,3> pivot{0.5f,1,0}; // 4004.
|
||||
std::array<float,3> placement{0.12f,0.12f,0}; // 4005, retained.
|
||||
std::array<float,3> dimensions{10,10,0}; // 4006.
|
||||
};
|
||||
using LeafCorners = std::array<std::array<float,3>,4>;
|
||||
LeafCorners BuildLeafCorners(const LeafDefinition& leaf, bool mirrored, float scale = 1);
|
||||
// Angles are source Z-up degrees; offsets and result use SDK Y-up.
|
||||
std::array<float,3> OrientLeafOffset(std::array<float,3> offset,
|
||||
float azimuth, float pitch, float rocking);
|
||||
|
||||
struct FrondTexture {
|
||||
std::string filename;
|
||||
float aspect = 0.5f, size_scale = 1;
|
||||
float angle_min = 0, angle_max = 0;
|
||||
};
|
||||
struct FrondSettings {
|
||||
bool enabled = false;
|
||||
uint32_t start_level = 1, type = 1, blade_count = 2, profile_segments = 4;
|
||||
BranchSpline profile;
|
||||
uint32_t lod_levels = 4, segment_override = 2, reduction_mode = 1;
|
||||
std::array<float,4> lod_fields{1,0,0,0.05f}; // 13010..13013.
|
||||
std::vector<FrondTexture> textures;
|
||||
};
|
||||
|
||||
struct SpeedTreeSptInfo {
|
||||
bool ok = false;
|
||||
float size = 1000.0f;
|
||||
@@ -48,9 +159,45 @@ struct SpeedTreeSptInfo {
|
||||
std::string bark_texture;
|
||||
std::string leaf_texture;
|
||||
std::string shadow_texture;
|
||||
std::vector<LeafDefinition> leaves;
|
||||
SpecialLeafSettings special_leaves;
|
||||
std::vector<UVRect> leaf_uvs;
|
||||
std::vector<UVRect> frond_uvs;
|
||||
std::vector<UVRect> billboard_uvs;
|
||||
std::vector<UVQuad> leaf_uv_quads;
|
||||
std::vector<UVQuad> frond_uv_quads;
|
||||
std::vector<UVQuad> billboard_uv_quads;
|
||||
bool horizontal_billboard = false;
|
||||
bool billboard_360 = false;
|
||||
UVQuad supplemental_uv{}; // Token 20005; retained separately pending semantic recovery.
|
||||
std::vector<CollisionObject> collision_objects;
|
||||
float lod_near = 0.0f;
|
||||
float lod_far = 0.0f;
|
||||
uint32_t seed = 1;
|
||||
FrondSettings fronds;
|
||||
uint32_t wind_level = 0;
|
||||
uint32_t branch_level_count = 0;
|
||||
bool has_size = false;
|
||||
bool metadata_complete = false;
|
||||
bool has_extension_21000 = false;
|
||||
std::array<float,2> extension_21000{}; // Corpus-observed payload; semantics unresolved.
|
||||
uint32_t unsupported_token = 0;
|
||||
size_t parsed_bytes = 0;
|
||||
std::string error;
|
||||
std::vector<BranchLevel> branch_levels;
|
||||
float leaf_rocking_range = 0.08f;
|
||||
float leaf_rocking_frequency = 0.3f;
|
||||
bool leaf_rocking_enabled = true;
|
||||
uint32_t lod_method = 0;
|
||||
float lod_transition_width = 0.0f;
|
||||
float lod_alpha_exponent = 1.0f;
|
||||
float lod_transition_overlap = 0.5f;
|
||||
float leaf_lod_growth = 0;
|
||||
uint32_t branch_lod_levels = 1;
|
||||
uint32_t leaf_lod_levels = 1;
|
||||
|
||||
// Original near-to-far linear LOD response, clamped to [0, 1].
|
||||
float EvaluateLod(float distance) const;
|
||||
|
||||
static bool SniffFile(const std::string& filepath, SpeedTreeSptInfo& out);
|
||||
static bool SniffMemory(const uint8_t* data, size_t size, SpeedTreeSptInfo& out);
|
||||
@@ -74,58 +221,121 @@ struct WindParameters {
|
||||
float direction[3] = {1.0f, 0.0f, 0.0f}; // Normalized wind direction
|
||||
float gust_frequency = 0.8f;
|
||||
float gust_strength = 0.5f;
|
||||
// Column-major local-space affine matrices, matching the original runtime.
|
||||
// Empty selects the SDK's synthesized wind; custom matrices are applied as supplied.
|
||||
std::vector<std::array<float, 16>> matrices;
|
||||
bool legacy_leaf_rocking = false;
|
||||
float legacy_leaf_phase = 0.0f;
|
||||
};
|
||||
|
||||
// AVA2's source-level forest controller, with instance-owned phase state.
|
||||
class LegacyWindController {
|
||||
public:
|
||||
void Update(float time, float strength);
|
||||
const std::vector<std::array<float,16>>& GetMatrices() const { return matrices_; }
|
||||
float GetLeafPhase() const { return leaf_phase_; }
|
||||
private:
|
||||
float previous_time_ = 0, previous_strength_ = 0;
|
||||
bool initialized_ = false;
|
||||
float leaf_phase_ = 0, leaf_offset_ = 0;
|
||||
std::array<float,4> phases_{};
|
||||
std::vector<std::array<float,16>> matrices_;
|
||||
};
|
||||
|
||||
// Recovered discrete branch/frond selection; level zero is highest detail.
|
||||
int SelectDiscreteLod(float lod, uint32_t levels);
|
||||
|
||||
struct LodTransition {
|
||||
int first = -1, second = -1;
|
||||
float first_alpha = 255, second_alpha = 255;
|
||||
};
|
||||
LodTransition SelectLodTransition(float lod, uint32_t levels, float width,
|
||||
float overlap, float exponent, float baseAlpha = 84);
|
||||
|
||||
struct BillboardView {
|
||||
int texture_index = -1;
|
||||
float alpha_ref = 255;
|
||||
};
|
||||
// Angle in tree-local source XY plane, degrees. Returns at most two atlas views.
|
||||
std::vector<BillboardView> SelectBillboardViews(const SpeedTreeSptInfo& info,
|
||||
float angleDegrees, float distanceAlpha);
|
||||
|
||||
// Core Model class representing a unique species/variant of tree
|
||||
class SpeedTreeModel {
|
||||
public:
|
||||
SpeedTreeModel();
|
||||
~SpeedTreeModel() = default;
|
||||
|
||||
static std::shared_ptr<SpeedTreeModel> Create(const std::string& sptPath, float treeSize = 1000.0f) { return CreateFromSpt(sptPath, treeSize); }
|
||||
static std::shared_ptr<SpeedTreeModel> CreateFromSpt(const std::string& sptPath, float treeSize = 1000.0f);
|
||||
// A positive explicit size overrides the SPT size, as SetTreeSize does before Compute.
|
||||
static std::shared_ptr<SpeedTreeModel> Create(const std::string& sptPath, float treeSize = 0.0f, float treeVariance = 0.0f) { return CreateFromSpt(sptPath, treeSize, treeVariance); }
|
||||
static std::shared_ptr<SpeedTreeModel> CreateFromSpt(const std::string& sptPath, float treeSize = 0.0f, float treeVariance = 0.0f);
|
||||
static std::shared_ptr<SpeedTreeModel> CreateFromMemory(const uint8_t* data, size_t size,
|
||||
const std::string& name = "", float treeSize = 1000.0f);
|
||||
const std::string& name = "", float treeSize = 0.0f, float treeVariance = 0.0f);
|
||||
static std::shared_ptr<SpeedTreeModel> CreateProcedural(const std::string& species_name, float height = 1000.0f,
|
||||
const std::string& bark_tex = "",
|
||||
const std::string& leaf_tex = "");
|
||||
|
||||
const SpeedTreeMesh& GetTrunkMesh() const { return m_trunk; }
|
||||
const SpeedTreeMesh& GetLeafMesh() const { return m_leaf; }
|
||||
const SpeedTreeMesh& GetTrunkMesh(uint32_t lod = 0) const;
|
||||
const SpeedTreeMesh& GetLeafMesh(uint32_t lod = 0) const;
|
||||
const std::vector<SpeedTreeMesh>& GetFrondMeshes(uint32_t lod = 0) const;
|
||||
uint32_t GetBranchLodCount() const { return uint32_t(m_trunk_lods.size()+1); }
|
||||
uint32_t GetLeafLodCount() const { return uint32_t(m_leaf_lods.size()+1); }
|
||||
uint32_t GetFrondLodCount() const { return uint32_t(m_frond_lods.size()+1); }
|
||||
|
||||
// Camera position in tree-local Y-up space. Output has no wind deformation.
|
||||
std::vector<SpeedTreeMesh> BuildBillboardMeshes(const std::array<float,3>& camera,
|
||||
float distanceAlpha = 84) const;
|
||||
|
||||
const std::array<float,3>& GetBoundsMin() const { return m_bounds_min; }
|
||||
const std::array<float,3>& GetBoundsMax() const { return m_bounds_max; }
|
||||
float GetHeight() const { return m_height; }
|
||||
float GetRadius() const { return m_radius; }
|
||||
bool IsGrassOrShrub() const { return m_is_grass_or_shrub; }
|
||||
bool WasGenerationTruncated() const { return m_generation_truncated; }
|
||||
const GenerationStats& GetGenerationStats() const { return m_generation_stats; }
|
||||
const std::string& GetName() const { return m_name; }
|
||||
const std::string& GetBarkTexture() const { return m_bark_texture; }
|
||||
const std::string& GetLeafTexture() const { return m_leaf_texture; }
|
||||
const SpeedTreeSptInfo& GetSptInfo() const { return m_info; }
|
||||
|
||||
// CPU fallback vertex deformer for legacy clients/renderers without custom foliage vertex shaders
|
||||
// CPU deformer. Optional camera is a world-space eye position for authored leaf cards.
|
||||
void EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh,
|
||||
std::vector<float>& out_positions,
|
||||
std::vector<float>& out_normals,
|
||||
float worldX, float worldY, float worldZ,
|
||||
float yawDeg, float scale,
|
||||
const WindParameters& wind) const;
|
||||
const WindParameters& wind,
|
||||
const std::array<float,3>* camera = nullptr) const;
|
||||
|
||||
private:
|
||||
void BuildLods();
|
||||
void BuildGeometry(const SpeedTreeSptInfo& info);
|
||||
void BuildTreeGeometry(float H, const SpeedTreeSptInfo& info);
|
||||
void BuildAuthoredBranches(float H, const SpeedTreeSptInfo& info);
|
||||
void AppendFrond(const std::vector<std::array<float,3>>& centers,
|
||||
std::array<float,3> side, std::array<float,3> other, uint32_t group,
|
||||
const std::vector<BranchFrame>* frames = nullptr);
|
||||
void BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info);
|
||||
|
||||
std::string m_name;
|
||||
std::string m_spt_path;
|
||||
float m_height = 1000.0f;
|
||||
float m_generation_variance = 0.0f;
|
||||
float m_radius = 350.0f;
|
||||
bool m_is_grass_or_shrub = false;
|
||||
bool m_generation_truncated = false;
|
||||
GenerationStats m_generation_stats;
|
||||
|
||||
std::string m_bark_texture;
|
||||
std::string m_leaf_texture;
|
||||
SpeedTreeSptInfo m_info;
|
||||
|
||||
std::array<float,3> m_bounds_min{}, m_bounds_max{};
|
||||
SpeedTreeMesh m_trunk;
|
||||
SpeedTreeMesh m_leaf;
|
||||
std::vector<SpeedTreeMesh> m_fronds;
|
||||
std::vector<SpeedTreeMesh> m_trunk_lods, m_leaf_lods;
|
||||
std::vector<std::vector<SpeedTreeMesh>> m_frond_lods;
|
||||
};
|
||||
|
||||
// Forest management and batched instance tracking
|
||||
@@ -173,6 +383,7 @@ public:
|
||||
|
||||
private:
|
||||
WindParameters m_wind;
|
||||
LegacyWindController m_wind_controller;
|
||||
std::map<uint32_t, SpeedTreeProperty> m_properties;
|
||||
std::map<uint32_t, std::shared_ptr<SpeedTreeModel>> m_tree_templates;
|
||||
std::vector<std::unique_ptr<Instance>> m_instances;
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace speedtree {
|
||||
std::vector<BillboardView> SelectBillboardViews(const SpeedTreeSptInfo& info,
|
||||
float angle, float distanceAlpha) {
|
||||
std::vector<BillboardView> result;
|
||||
const size_t count=info.billboard_uv_quads.size();
|
||||
if (!count || count>32767 || !std::isfinite(angle) || !std::isfinite(distanceAlpha)) return result;
|
||||
distanceAlpha=std::clamp(distanceAlpha,84.0f,255.0f);
|
||||
if(distanceAlpha>=255) return result;
|
||||
if (!info.billboard_360 || count==1) return {{0,distanceAlpha}};
|
||||
angle=std::fmod(angle,360.0f); if(angle<0) angle+=360;
|
||||
// 10020390 remaps the cyclic angle into the interior half-step endpoints.
|
||||
const float halfStep=0.5f/float(count);
|
||||
auto transition=SelectLodTransition((1-2*halfStep)*angle/360+halfStep,
|
||||
uint32_t(count),halfStep,info.lod_transition_overlap,info.lod_alpha_exponent);
|
||||
auto append=[&](int level,float alpha) {
|
||||
if(level<0) return;
|
||||
int index=int(count)-level-1;
|
||||
if(index==int(count)-1) index=0;
|
||||
if(index<0 || size_t(index)>=count) return;
|
||||
alpha+=(255-alpha)*(distanceAlpha-84)/(255-84);
|
||||
// A failed alpha test contributes no pixels, so omit it altogether.
|
||||
if(alpha<255) result.push_back({index,alpha});
|
||||
};
|
||||
append(transition.first,transition.first_alpha);
|
||||
append(transition.second,transition.second_alpha);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<SpeedTreeMesh> SpeedTreeModel::BuildBillboardMeshes(
|
||||
const std::array<float,3>& camera,float distanceAlpha) const {
|
||||
std::vector<SpeedTreeMesh> result;
|
||||
for(float value:camera) if(!std::isfinite(value)) return result;
|
||||
if(!std::isfinite(distanceAlpha) || distanceAlpha>=255 || m_info.billboard_uv_quads.empty()) return result;
|
||||
const auto& lo=m_bounds_min;
|
||||
const auto& hi=m_bounds_max;
|
||||
if(!std::isfinite(lo[0])) return result;
|
||||
float cx=(lo[0]+hi[0])*0.5f,cz=(lo[2]+hi[2])*0.5f;
|
||||
float dx=camera[0]-cx,dz=camera[2]-cz;
|
||||
float length=std::hypot(dx,dz);
|
||||
float nx=length>1e-6f?dx/length:0,nz=length>1e-6f?dz/length:1;
|
||||
// The DLL uses computed geometry dimensions. Bounds here are those of our
|
||||
// generated approximation, not an assertion of original tree equivalence.
|
||||
float halfWidth=0.5f*std::max(hi[0]-lo[0],hi[2]-lo[2]);
|
||||
float rx=nz*halfWidth,rz=-nx*halfWidth;
|
||||
using Corners=std::array<std::array<float,3>,4>;
|
||||
Corners vertical{{{cx+rx,hi[1],cz+rz},{cx-rx,hi[1],cz-rz},
|
||||
{cx-rx,lo[1],cz-rz},{cx+rx,lo[1],cz+rz}}};
|
||||
auto append=[&](const Corners& corners,const UVQuad& uv,float alpha,bool horizontal) {
|
||||
if(alpha>=255) return;
|
||||
SpeedTreeMesh mesh;
|
||||
mesh.name=horizontal?"horizontal_billboard":"billboard";
|
||||
mesh.texture=m_leaf_texture;mesh.alpha_test=true;mesh.is_double_sided=true;
|
||||
mesh.alpha_ref=alpha/255.0f;
|
||||
mesh.indices={0,1,2,0,2,3};
|
||||
for(size_t i=0;i<4;++i) {
|
||||
SpeedTreeVertex vertex{};
|
||||
std::copy(corners[i].begin(),corners[i].end(),vertex.position);
|
||||
vertex.normal[0]=horizontal?0:nx;vertex.normal[1]=horizontal?1:0;
|
||||
vertex.normal[2]=horizontal?0:nz;
|
||||
vertex.uv[0]=uv[i*2];vertex.uv[1]=uv[i*2+1];vertex.diffuse=0xffffffff;
|
||||
mesh.vertices.push_back(vertex);
|
||||
}
|
||||
result.push_back(std::move(mesh));
|
||||
};
|
||||
// Source Z-up camera direction maps to SDK X/Z; original atan2(-Y,-X).
|
||||
float angle=std::atan2(-dz,-dx)*180/kPI;
|
||||
for(const auto& view:SelectBillboardViews(m_info,angle,distanceAlpha))
|
||||
append(vertical,m_info.billboard_uv_quads[size_t(view.texture_index)],view.alpha_ref,false);
|
||||
if(m_info.horizontal_billboard) {
|
||||
float mid=(lo[1]+hi[1])*0.5f;
|
||||
Corners horizontal{{{hi[0],mid,hi[2]},{lo[0],mid,hi[2]},
|
||||
{lo[0],mid,lo[2]},{hi[0],mid,lo[2]}}};
|
||||
append(horizontal,m_info.billboard_uv_quads.back(),distanceAlpha,true);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,289 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
|
||||
namespace speedtree {
|
||||
namespace {
|
||||
using V = std::array<float,3>;
|
||||
V add(V a,V b) { for (int i=0;i<3;++i) a[i]+=b[i]; return a; }
|
||||
V mul(V a,float b) { for (float& x:a) x*=b; return a; }
|
||||
V cross(V a,V b) { return {a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}; }
|
||||
V unit(V a) { float n=std::sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]); return n>1e-6f?mul(a,1/n):V{0,1,0}; }
|
||||
struct Node { V start; BranchFrame frame; float position,parent_radius; size_t level; uint32_t seed; std::vector<float> ancestors; };
|
||||
}
|
||||
|
||||
void SpeedTreeModel::BuildAuthoredBranches(float H,const SpeedTreeSptInfo& info) {
|
||||
m_trunk.vertices.clear(); m_trunk.indices.clear(); m_trunk.texture=m_bark_texture;
|
||||
m_leaf.vertices.clear(); m_leaf.indices.clear(); m_leaf.texture=m_leaf_texture;
|
||||
LegacyRandom random(info.seed);
|
||||
H=std::max(0.01f,H+random.Uniform(-m_generation_variance,m_generation_variance));
|
||||
m_height=H;
|
||||
auto value=[&](const BranchLevel& level,size_t curve,float t,float fallback) {
|
||||
return level.curves[curve].points.empty()?fallback:level.curves[curve].Evaluate(t,&random);
|
||||
};
|
||||
Node rootNode={{0,0,0},{},0,0,0,info.seed,{}};
|
||||
m_generation_stats={};
|
||||
m_radius=0;
|
||||
m_fronds.clear();
|
||||
LegacyRandom groupRandom(info.seed);
|
||||
std::array<float,3> rockingGroups{};
|
||||
for(float& phase:rockingGroups) phase=groupRandom.Uniform(0,10000);
|
||||
std::vector<uint32_t> ordinaryVariants,specialVariants;
|
||||
for(size_t i=0;i<info.leaves.size();++i) {
|
||||
auto& pool=info.leaves[i].flag?specialVariants:ordinaryVariants;
|
||||
pool.push_back(uint32_t(i*2));pool.push_back(uint32_t(i*2+1));
|
||||
}
|
||||
auto leaf=[&](V center,float width,float height,uint32_t group,bool terminal=false,float position=0,const std::vector<float>& ancestors=std::vector<float>{}) {
|
||||
const size_t vertices=info.leaves.empty()?8:4;
|
||||
if(m_generation_stats.generated_vertices+vertices>GenerationStats::max_vertices) {
|
||||
m_generation_truncated=true;m_generation_stats.vertex_limit=true;return;
|
||||
}
|
||||
m_generation_stats.generated_vertices+=vertices;
|
||||
float phase=terminal?0:random.Uniform();
|
||||
if(!info.leaves.empty()) {
|
||||
uint32_t variant=group%uint32_t(info.leaves.size()*2);
|
||||
if(terminal) {
|
||||
bool special=!specialVariants.empty() && SampleSpecialLeaf(position,ancestors,info.special_leaves,random);
|
||||
const auto& variants=special?specialVariants:ordinaryVariants;
|
||||
if(variants.empty()) {m_generation_stats.generated_vertices-=vertices;return;}
|
||||
const float range=special?100000.0f:1000000.0f;
|
||||
variant=variants.size()==1?variants[0]:variants[uint32_t(random.Uniform(0,range))%variants.size()];
|
||||
if(special) ++m_generation_stats.special_leaf_cards;
|
||||
group=uint32_t(random.Uniform(0,10000))%3;
|
||||
}
|
||||
const auto& definition=info.leaves[variant/2];
|
||||
uint32_t diffuse=0xffffffff;
|
||||
if(terminal) {
|
||||
// 10004540 applies one shared random color offset to RGB.
|
||||
float offset=random.Uniform(-definition.scalar,definition.scalar);
|
||||
diffuse=0xff000000;
|
||||
for(size_t axis=0;axis<3;++axis)
|
||||
diffuse|=uint32_t(std::clamp(definition.color[axis]+offset,0.0f,1.0f)*255)<<(axis*8);
|
||||
}
|
||||
auto corners=BuildLeafCorners(definition,(variant&1)!=0,H/info.size);
|
||||
UVQuad uv{1,0,0,0,0,1,1,1};
|
||||
if(!info.leaf_uv_quads.empty()) uv=info.leaf_uv_quads[(variant/2)%info.leaf_uv_quads.size()];
|
||||
uint32_t first=uint32_t(m_leaf.vertices.size());
|
||||
for(size_t i=0;i<4;++i) {
|
||||
SpeedTreeVertex vertex{};V point=add(center,corners[i]);
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
vertex.position[axis]=point[axis];vertex.leaf_pivot_offset[axis]=corners[i][axis];
|
||||
}
|
||||
vertex.normal[0]=1;
|
||||
vertex.uv[0]=uv[i*2];vertex.uv[1]=uv[i*2+1];vertex.diffuse=diffuse;
|
||||
vertex.wind_weights[0]=std::clamp(center[1]/H,0.0f,1.0f);
|
||||
vertex.wind_weights[2]=1;vertex.wind_weights[3]=phase;
|
||||
vertex.wind_matrix_index=group%4;vertex.authored_leaf_card=true;
|
||||
vertex.leaf_rocking_phase=float(variant+1)*rockingGroups[group%3];
|
||||
m_leaf.vertices.push_back(vertex);
|
||||
}
|
||||
for(uint32_t index:{0u,1u,2u,0u,2u,3u}) m_leaf.indices.push_back(first+index);
|
||||
return;
|
||||
}
|
||||
for (int plane=0;plane<2;++plane) {
|
||||
float angle=phase*kTAU+plane*kPI*0.5f;
|
||||
V right{std::cos(angle)*width*0.5f,0,std::sin(angle)*width*0.5f};
|
||||
V up{0,height*0.5f,0};
|
||||
V corners[4]={add(mul(right,-1),mul(up,-1)),add(right,mul(up,-1)),add(right,up),add(mul(right,-1),up)};
|
||||
UVQuad uv{0,1,1,1,1,0,0,0};
|
||||
if (!info.leaf_uv_quads.empty()) uv=info.leaf_uv_quads[group%info.leaf_uv_quads.size()];
|
||||
uint32_t first=uint32_t(m_leaf.vertices.size());
|
||||
// All corners share the same rocking angle and branch weight.
|
||||
float weight=std::clamp(center[1]/H,0.0f,1.0f);
|
||||
for (int i=0;i<4;++i) {
|
||||
SpeedTreeVertex v{}; V p=add(center,corners[i]);
|
||||
V normal=unit({p[0],p[1]-H*0.6f,p[2]});
|
||||
for (int j=0;j<3;++j) { v.position[j]=p[j];v.normal[j]=normal[j];v.leaf_pivot_offset[j]=corners[i][j]; }
|
||||
v.uv[0]=uv[i*2];v.uv[1]=uv[i*2+1];v.diffuse=0xffffffff;
|
||||
v.wind_weights[0]=weight;v.wind_weights[2]=1;v.wind_weights[3]=phase;
|
||||
v.wind_matrix_index=group%4;
|
||||
m_leaf.vertices.push_back(v);
|
||||
}
|
||||
for (uint32_t index:{0u,1u,2u,0u,2u,3u}) m_leaf.indices.push_back(first+index);
|
||||
}
|
||||
};
|
||||
size_t processed=0;
|
||||
std::function<void(Node)> generate;
|
||||
generate=[&](Node node) {
|
||||
if(processed>=GenerationStats::max_nodes) {
|
||||
m_generation_truncated=true;m_generation_stats.node_limit=true;return;
|
||||
}
|
||||
size_t nodeIndex=processed++;
|
||||
const auto& level=info.branch_levels[node.level];
|
||||
++m_generation_stats.nodes_by_level[node.level];
|
||||
const auto entry=SampleBranchEntry(level,node.position,H,random);
|
||||
const float length=std::max(0.0f,entry.length);
|
||||
float branchRadius=std::max(0.0f,entry.radius);
|
||||
// 10002450 caps the child base profile to 0.85 * parent attachment radius,
|
||||
// rather than shortening every child or applying a fixed 0.65 radius ratio.
|
||||
const float baseProfile=std::max(0.02f,value(level,6,0,1));
|
||||
if(node.parent_radius>0 && branchRadius*baseProfile>node.parent_radius*0.85f)
|
||||
branchRadius=node.parent_radius*0.85f;
|
||||
bool frond=info.fronds.enabled && info.fronds.type<=1 && node.level>=info.fronds.start_level;
|
||||
uint32_t radial=std::clamp(level.radial_segments,3u,256u);
|
||||
uint32_t rings=std::clamp(level.length_segments,1u,1024u);
|
||||
if(radial!=level.radial_segments || rings!=level.length_segments) {
|
||||
m_generation_truncated=true;m_generation_stats.tessellation_limit=true;
|
||||
}
|
||||
// Evaluate radius along the limb once per ring, not independently per seam vertex.
|
||||
const size_t tubeVertices=size_t(rings+1)*(radial+1);
|
||||
bool tube=!frond && m_generation_stats.generated_vertices+tubeVertices<=GenerationStats::max_vertices;
|
||||
if(!frond && !tube) {m_generation_truncated=true;m_generation_stats.vertex_limit=true;}
|
||||
if(tube) m_generation_stats.generated_vertices+=tubeVertices;
|
||||
uint32_t base=uint32_t(m_trunk.vertices.size());
|
||||
std::vector<V> centers;
|
||||
std::vector<float> radii;
|
||||
std::vector<float> percentages;
|
||||
const float exponent=std::clamp(level.length_exponent,0.0f,32.0f);
|
||||
if(exponent!=level.length_exponent) {m_generation_truncated=true;m_generation_stats.tessellation_limit=true;}
|
||||
// Root and children preserve the inherited full basis. Source frame
|
||||
// perturbations are degrees; entry angle/azimuth are already radians.
|
||||
float roll=level.curves[0].EvaluatePerturbation(0,random)*kPI/180;
|
||||
float pitch=level.curves[0].EvaluatePerturbation(0,random)*kPI/180;
|
||||
BranchFrame frame=node.frame.Rotate(entry.azimuth,roll,entry.angle+pitch);
|
||||
std::vector<BranchFrame> frames;
|
||||
V center=node.start;
|
||||
V side=frame.SdkAxis(0),other=frame.SdkAxis(1);
|
||||
for (uint32_t ring=0;ring<=rings;++ring) {
|
||||
float t=ring?std::pow(float(ring)/rings,exponent):0;
|
||||
float profile=std::clamp(value(level,6,t,1-t),0.02f,2.0f);
|
||||
value(level,3,t,0); // Original wind profile draw, not a growth curve.
|
||||
float growth=value(level,8,t,0.5f);
|
||||
if(ring) {
|
||||
// Original positions advance along the preceding ring direction.
|
||||
center=add(center,mul(frames.back().SdkAxis(2),length*(t-percentages.back())));
|
||||
frame=frame.ApplyGravity(entry.gravity,growth);
|
||||
float roll=level.curves[0].EvaluatePerturbation(t,random)*kPI/180;
|
||||
float pitch=level.curves[0].EvaluatePerturbation(t,random)*kPI/180;
|
||||
frame=frame.Rotate(0,roll,pitch);
|
||||
} else frame=frame.ApplyGravity(entry.gravity,growth);
|
||||
frames.push_back(frame);
|
||||
percentages.push_back(t);
|
||||
V ringSide=frame.SdkAxis(0),ringOther=frame.SdkAxis(1);
|
||||
centers.push_back(center);
|
||||
float radius=branchRadius*profile;
|
||||
radii.push_back(radius);
|
||||
if(tube) for (uint32_t segment=0;segment<=radial;++segment) {
|
||||
float angle=float(segment)/radial*kTAU;
|
||||
V normal=add(mul(ringSide,std::cos(angle)),mul(ringOther,std::sin(angle)));
|
||||
V p=add(center,mul(normal,radius)); SpeedTreeVertex v{};
|
||||
for (int j=0;j<3;++j) { v.position[j]=p[j];v.normal[j]=normal[j]; }
|
||||
v.uv[0]=float(segment)/radial;v.uv[1]=t*length/std::max(branchRadius*6,0.01f);
|
||||
v.wind_weights[0]=std::clamp(center[1]/H,0.0f,1.0f);
|
||||
v.wind_matrix_index=uint32_t(node.level%4);v.diffuse=0xffffffff;
|
||||
m_radius=std::max(m_radius,std::hypot(p[0],p[2]));
|
||||
m_trunk.vertices.push_back(v);
|
||||
}
|
||||
}
|
||||
// Tangents include taper and centerline curvature; radial normals alone
|
||||
// are incorrect once authored radius/growth curves bend a limb.
|
||||
if(tube) for (uint32_t ring=0;ring<=rings;++ring) for (uint32_t segment=0;segment<=radial;++segment) {
|
||||
uint32_t prev=base+(ring?ring-1:ring)*(radial+1)+segment;
|
||||
uint32_t next=base+std::min(ring+1,rings)*(radial+1)+segment;
|
||||
V longitudinal{};
|
||||
for (int j=0;j<3;++j) longitudinal[j]=m_trunk.vertices[next].position[j]-m_trunk.vertices[prev].position[j];
|
||||
float angle=float(segment)/radial*kTAU;
|
||||
V tangent=add(mul(frames[ring].SdkAxis(0),-std::sin(angle)),mul(frames[ring].SdkAxis(1),std::cos(angle)));
|
||||
V normal=unit(cross(longitudinal,tangent));
|
||||
auto& vertex=m_trunk.vertices[base+ring*(radial+1)+segment];
|
||||
for (int j=0;j<3;++j) vertex.normal[j]=normal[j];
|
||||
}
|
||||
if(tube) for (uint32_t ring=0;ring<rings;++ring) for (uint32_t segment=0;segment<radial;++segment) {
|
||||
uint32_t a=base+ring*(radial+1)+segment,b=a+radial+1;
|
||||
for (uint32_t index:{a,b,b+1,a,b+1,a+1}) m_trunk.indices.push_back(index);
|
||||
}
|
||||
if(frond) AppendFrond(centers,side,other,uint32_t(nodeIndex),&frames);
|
||||
if(tube) m_trunk.grids.push_back({base,rings+1,radial+1,true});
|
||||
size_t next=node.level+1;
|
||||
if (next<info.branch_levels.size() && next<8 && processed<GenerationStats::max_nodes) {
|
||||
// 10002450 selects 10003af0 at the last authored level independently
|
||||
// of frond activation. Frond limbs can carry terminal leaves/flowers.
|
||||
bool terminal=next+1==info.branch_levels.size() && !info.leaves.empty();
|
||||
uint32_t count=node.level==0?8u:4u;
|
||||
if(level.has_child_density) {
|
||||
float density=level.scalar_fields[2]*length/H;
|
||||
const size_t limit=terminal?GenerationStats::max_vertices/4:GenerationStats::max_nodes;
|
||||
if(density>limit) {m_generation_truncated=true;m_generation_stats.density_limit=true;}
|
||||
count=std::isfinite(density)?uint32_t(std::clamp(density,0.0f,float(limit))):0;
|
||||
}
|
||||
uint32_t emitted=0;
|
||||
for (uint32_t i=0;i<count && processed<GenerationStats::max_nodes;++i) {
|
||||
if(terminal && m_generation_stats.generated_vertices+4>GenerationStats::max_vertices) {
|
||||
m_generation_truncated=true;m_generation_stats.vertex_limit=true;break;
|
||||
}
|
||||
++emitted;
|
||||
float t=0.3f+0.65f*(float(i)+0.5f)/count;
|
||||
if(level.has_attachment_range) {
|
||||
// The original terminal-leaf path uses the current stream
|
||||
// and full interval, without per-child reseeding/narrowing.
|
||||
float low=level.scalar_fields[0],high=level.scalar_fields[1];
|
||||
if(next+1<info.branch_levels.size()) {
|
||||
random=LegacyRandom(node.seed+3*(i+1));
|
||||
if(i==0) {float width=high-low;high=low+width*0.95f;low+=width*0.85f;}
|
||||
}
|
||||
float sampled=random.Uniform(low,high);
|
||||
t=std::clamp(sampled,0.0f,1.0f);
|
||||
}
|
||||
// Parent samples attachment and wind profile, then reseeds a
|
||||
// nonterminal child and consumes its dummy [0,100] draw.
|
||||
value(level,3,t,0);
|
||||
if(level.has_attachment_range && next+1<info.branch_levels.size()) {
|
||||
random=LegacyRandom(node.seed+3*(i+1));random.Uniform(0,100);
|
||||
}
|
||||
float childPosition=t;
|
||||
if(level.has_attachment_range) {
|
||||
float width=level.scalar_fields[1]-level.scalar_fields[0];
|
||||
childPosition=width!=0?(t-level.scalar_fields[0])/width:0;
|
||||
}
|
||||
// 10005110 locates physical distance along the generated limb;
|
||||
// ring indices are nonuniform when the authored exponent != 1.
|
||||
auto upper=std::upper_bound(percentages.begin(),percentages.end(),t);
|
||||
size_t segment=std::clamp(size_t(upper-percentages.begin()),size_t(1),percentages.size()-1)-1;
|
||||
float span=percentages[segment+1]-percentages[segment];
|
||||
float blend=span>0?(t-percentages[segment])/span:0;
|
||||
V start=add(mul(centers[segment],1-blend),mul(centers[segment+1],blend));
|
||||
float parentRadius=radii[segment]*(1-blend)+radii[segment+1]*blend;
|
||||
if(terminal) {
|
||||
// 10003af0: length / authored longitudinal segment count,
|
||||
// azimuth draw, then a fixed 60 degree local tilt (double
|
||||
// constant at 1004c1c8). The inherited frame is approximate.
|
||||
const auto& last=info.branch_levels[next];
|
||||
float offset=value(last,4,childPosition,0.25f)*H/std::max(1u,last.length_segments);
|
||||
float angle=random.Uniform(-180,180)*kPI/180;
|
||||
V direction=frames[segment].Rotate(angle,0,kPI/3).SdkAxis(2);
|
||||
++m_generation_stats.terminal_leaf_calls;
|
||||
std::vector<float> ancestry=node.ancestors;ancestry.insert(ancestry.begin(),node.position);
|
||||
leaf(add(start,mul(direction,offset)),H*0.12f,H*0.1f,uint32_t(nodeIndex),true,childPosition,ancestry);
|
||||
} else {
|
||||
std::vector<float> ancestry=node.ancestors;ancestry.insert(ancestry.begin(),node.position);
|
||||
generate({start,frames[segment],childPosition,parentRadius,next,node.seed+3*(i+1),std::move(ancestry)});
|
||||
}
|
||||
}
|
||||
if(emitted<count) {
|
||||
m_generation_truncated=true;
|
||||
if(!m_generation_stats.vertex_limit) m_generation_stats.node_limit=true;
|
||||
}
|
||||
} else if(next<info.branch_levels.size()) {
|
||||
m_generation_truncated=true;m_generation_stats.node_limit=true;
|
||||
} else if(!frond) {
|
||||
for (uint32_t i=1;i<=3;++i) {
|
||||
V center=centers[std::min(size_t(rings*(0.5f+float(i)/6)),centers.size()-1)];
|
||||
leaf(center,H*0.12f,H*0.1f,uint32_t(nodeIndex));
|
||||
}
|
||||
}
|
||||
};
|
||||
generate(rootNode);
|
||||
for(const auto& mesh:m_fronds) for(const auto& vertex:mesh.vertices)
|
||||
m_radius=std::max(m_radius,std::hypot(vertex.position[0],vertex.position[2]));
|
||||
// Actual branch and leaf bounds, including card corners.
|
||||
for (const auto& v:m_leaf.vertices) {
|
||||
float radius=std::hypot(v.position[0],v.position[2]);
|
||||
if(v.authored_leaf_card) {
|
||||
float offset=0;for(float value:v.leaf_pivot_offset) offset+=value*value;
|
||||
radius=std::hypot(v.position[0]-v.leaf_pivot_offset[0],v.position[2]-v.leaf_pivot_offset[2])+std::sqrt(offset);
|
||||
}
|
||||
m_radius=std::max(m_radius,radius);
|
||||
}
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,186 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
|
||||
namespace speedtree {
|
||||
bool SampleSpecialLeaf(float position,const std::vector<float>& ancestors,
|
||||
const SpecialLeafSettings& settings,LegacyRandom& random) {
|
||||
// 100044c0 walks at most depth ancestors, stopping at the root. Threshold
|
||||
// equality fails without consuming RNG; probability equality succeeds.
|
||||
if(settings.ancestor_depth && !ancestors.empty())
|
||||
position=ancestors[std::min(size_t(settings.ancestor_depth-1),ancestors.size()-1)];
|
||||
return position>settings.minimum_position && random.Uniform()<=settings.probability;
|
||||
}
|
||||
|
||||
BranchFrame BranchFrame::Rotate(float azimuth,float roll,float pitch) const {
|
||||
// 10002450/10005960: row-vector local rotations multiply inherited frames.
|
||||
// Roll/pitch perturbations compose after the azimuth rotation in source axes.
|
||||
float a=std::cos(azimuth),b=std::sin(azimuth),c=std::cos(roll),d=std::sin(roll);
|
||||
float e=std::cos(pitch),f=std::sin(pitch);
|
||||
const std::array<std::array<float,3>,3> z{{{a,b,0},{-b,a,0},{0,0,1}}};
|
||||
const std::array<std::array<float,3>,3> tilt{{{c*e,d*e,-f},{-d,c,0},{c*f,d*f,e}}};
|
||||
BranchFrame spun,result;
|
||||
for(size_t r=0;r<3;++r) for(size_t axis=0;axis<3;++axis) {
|
||||
spun.basis[r][axis]=0;
|
||||
for(size_t k=0;k<3;++k) spun.basis[r][axis]+=z[r][k]*basis[k][axis];
|
||||
}
|
||||
for(size_t r=0;r<3;++r) for(size_t axis=0;axis<3;++axis) {
|
||||
result.basis[r][axis]=0;
|
||||
for(size_t k=0;k<3;++k) result.basis[r][axis]+=tilt[r][k]*spun.basis[k][axis];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::array<float,3> BranchFrame::SdkAxis(size_t axis) const {
|
||||
const auto& v=basis[axis];return {v[0],v[2],v[1]};
|
||||
}
|
||||
|
||||
BranchFrame BranchFrame::ApplyGravity(float gravity,float profile) const {
|
||||
// 10002450, default source Z-up: axis = up x direction; angular influence
|
||||
// peaks at horizontal and vanishes for either vertical direction.
|
||||
const auto& forward=basis[2];
|
||||
float magnitude=std::hypot(forward[0],forward[1]);
|
||||
if(magnitude<1e-7f || gravity==0) return *this;
|
||||
std::array<float,3> axis{-forward[1]/magnitude,forward[0]/magnitude,0};
|
||||
float inclination=std::acos(std::clamp(forward[2],-1.0f,1.0f));
|
||||
float influence=1-std::abs(kPI/2-inclination)/(kPI/2);
|
||||
float angle=-2*(profile-0.5f)*influence*inclination*gravity;
|
||||
float c=std::cos(angle),s=std::sin(angle);
|
||||
BranchFrame result;
|
||||
for(size_t i=0;i<3;++i) {
|
||||
const auto& v=basis[i];float dot=axis[0]*v[0]+axis[1]*v[1];
|
||||
std::array<float,3> cross{axis[1]*v[2],-axis[0]*v[2],axis[0]*v[1]-axis[1]*v[0]};
|
||||
for(size_t j=0;j<3;++j) result.basis[i][j]=v[j]*c+cross[j]*s+axis[j]*dot*(1-c);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
LegacyRandom::LegacyRandom(uint32_t seed) : state_(seed % 2147483647u) {
|
||||
if (state_ == 0) state_ = 1;
|
||||
for (float& value : shuffle_) value = static_cast<float>(Next());
|
||||
}
|
||||
|
||||
double LegacyRandom::Next() {
|
||||
// Park-Miller multiplier/modulus and the 128-entry shuffle recovered from
|
||||
// 10027a50, 10027f50, 10027bb0. Use 64-bit math instead of x86 overflow.
|
||||
state_ = uint32_t((uint64_t(state_) * 16807u) % 2147483647u);
|
||||
return double(state_) / 2147483648.0; // DLL constant 0x1015c510 = 2^-31.
|
||||
}
|
||||
|
||||
float LegacyRandom::Uniform(float low, float high) {
|
||||
size_t index = std::min(size_t(Next() * shuffle_.size()), shuffle_.size() - 1);
|
||||
float value = shuffle_[index];
|
||||
shuffle_[index] = static_cast<float>(Next());
|
||||
return low + (high - low) * value;
|
||||
}
|
||||
|
||||
float SampleBranchAttachment(uint32_t seed,uint32_t child,float low,float high) {
|
||||
// 10002450 nonterminal path: reseed each child with parent_seed + 3*(child+1).
|
||||
// The first child samples the upper 85..95% of the authored interval.
|
||||
LegacyRandom random(seed+3*(child+1));
|
||||
if(child==0) { float width=high-low;high=low+width*0.95f;low+=width*0.85f; }
|
||||
return random.Uniform(low,high);
|
||||
}
|
||||
|
||||
float SampleBranchAzimuth(uint32_t childSeed) {
|
||||
// Nonterminal 10002450 path: after reseeding, the parent consumes the
|
||||
// percentage draw; the child consumes length-spline variance, then azimuth.
|
||||
LegacyRandom random(childSeed);random.Uniform();random.Uniform();
|
||||
return random.Uniform(-180,180)*kPI/180;
|
||||
}
|
||||
|
||||
BranchEntrySample SampleBranchEntry(const BranchLevel& level,float position,
|
||||
float height,LegacyRandom& random) {
|
||||
auto curve=[&](size_t i,float fallback) {
|
||||
return level.curves[i].samples_ready?level.curves[i].Evaluate(position,&random):fallback;
|
||||
};
|
||||
BranchEntrySample sample;
|
||||
sample.length=height*curve(4,0.25f);
|
||||
sample.azimuth=random.Uniform(-180,180)*kPI/180;
|
||||
sample.angle=curve(7,-25)*kPI/180;
|
||||
sample.gravity=curve(1,0);
|
||||
sample.radius=height*curve(5,0.008f);
|
||||
sample.flexibility=curve(2,0);
|
||||
return sample;
|
||||
}
|
||||
|
||||
bool BranchSpline::Parse(const std::string& text, BranchSpline& out) {
|
||||
BranchSpline parsed;
|
||||
std::istringstream input(text);
|
||||
std::string tag;
|
||||
char marker;
|
||||
uint32_t count;
|
||||
if (!(input >> tag >> parsed.minimum >> parsed.maximum >> parsed.variance >> marker >> count)
|
||||
|| tag != "BezierSpline" || marker != '{' || count < 2 || count > 4096
|
||||
|| !std::isfinite(parsed.minimum) || !std::isfinite(parsed.maximum)
|
||||
|| !std::isfinite(parsed.variance)) return false;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
Point point;
|
||||
if (!(input >> point.x >> point.y >> point.dx >> point.dy >> point.handle)) return false;
|
||||
if (!std::isfinite(point.x) || !std::isfinite(point.y) || !std::isfinite(point.dx)
|
||||
|| !std::isfinite(point.dy) || !std::isfinite(point.handle) || point.handle < 0
|
||||
|| (!parsed.points.empty() && point.x <= parsed.points.back().x)) return false;
|
||||
float length = std::hypot(point.dx, point.dy);
|
||||
if (length > 0) { point.dx /= length; point.dy /= length; }
|
||||
parsed.points.push_back(point);
|
||||
}
|
||||
if (!(input >> marker) || marker != '}') return false;
|
||||
if (!parsed.BuildSamples()) return false;
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BranchSpline::BuildSamples() {
|
||||
samples_ready = false;
|
||||
if (points.size() < 2) return false;
|
||||
std::array<std::array<float,2>,500> raw{};
|
||||
// 10026aa0 uses equal parameter intervals between nodes, not x intervals.
|
||||
for (size_t i=0;i<500;++i) {
|
||||
float position=float(i)/500.0f*float(points.size()-1);
|
||||
size_t segment=std::min(size_t(position),points.size()-2);
|
||||
float t=position-float(segment), u=1-t;
|
||||
const auto& a=points[segment];const auto& b=points[segment+1];
|
||||
for (int axis=0;axis<2;++axis) {
|
||||
float av=axis?a.y:a.x,bv=axis?b.y:b.x;
|
||||
float c1=av+(axis?a.dy:a.dx)*a.handle;
|
||||
float c2=bv-(axis?b.dy:b.dx)*b.handle;
|
||||
raw[i][axis]=u*u*u*av+3*u*u*t*c1+3*u*t*t*c2+t*t*t*bv;
|
||||
}
|
||||
}
|
||||
samples[0]=points.front().y;
|
||||
size_t previous=0;
|
||||
for(size_t i=1;i<499;++i) {
|
||||
float x=float(i)/500.0f;
|
||||
size_t segment=previous;
|
||||
for(size_t j=previous;j<499;++j) {
|
||||
if(raw[j][0]<=x && x<raw[j+1][0]) { segment=j;break; }
|
||||
}
|
||||
float width=raw[segment+1][0]-raw[segment][0];
|
||||
samples[i]=width!=0 ? raw[segment][1]+(raw[segment+1][1]-raw[segment][1])
|
||||
*((x-raw[segment][0])/width) : raw[segment][1];
|
||||
if(!std::isfinite(samples[i])) return false;
|
||||
previous=segment;
|
||||
}
|
||||
samples[499]=points.back().y;
|
||||
samples_ready=true;
|
||||
return true;
|
||||
}
|
||||
|
||||
float BranchSpline::Evaluate(float position, LegacyRandom* random) const {
|
||||
if (!samples_ready || !std::isfinite(position)) return minimum;
|
||||
float x=std::clamp(position,0.0f,1.0f);
|
||||
size_t index=std::min(size_t(x*499.0f),size_t(499));
|
||||
constexpr float step=0.0020040080416947603f; // DLL 0x1015c4b8.
|
||||
float y=samples[index];
|
||||
if(index<499) y+=(samples[index+1]-y)*((x-float(index)*step)/step);
|
||||
float result=minimum+(maximum-minimum)*y;
|
||||
return result+(random?random->Uniform(-variance,variance):0.0f);
|
||||
}
|
||||
|
||||
float BranchSpline::EvaluatePerturbation(float position,LegacyRandom& random) const {
|
||||
if(!samples_ready || !std::isfinite(position)) return 0;
|
||||
const size_t index=size_t(std::clamp(position,0.0f,1.0f)*499.0f+0.5f);
|
||||
const float amplitude=samples[index]*variance;
|
||||
return random.Uniform(-amplitude,amplitude);
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -47,8 +47,9 @@ bool SpeedTreeForest::RegisterProperty(uint32_t crc, const std::string& prtPath)
|
||||
|
||||
bool SpeedTreeForest::RegisterPropertyData(const SpeedTreeProperty& prop) {
|
||||
if (prop.crc == 0) return false;
|
||||
auto model = SpeedTreeModel::CreateFromSpt(prop.tree_file, prop.tree_size, prop.tree_variance);
|
||||
if (!model) return false;
|
||||
m_properties[prop.crc] = prop;
|
||||
auto model = SpeedTreeModel::CreateFromSpt(prop.tree_file, prop.tree_size);
|
||||
m_tree_templates[prop.crc] = model;
|
||||
return true;
|
||||
}
|
||||
@@ -105,6 +106,10 @@ void SpeedTreeForest::DeleteInstance(Instance* pTree) {
|
||||
|
||||
void SpeedTreeForest::Update(float dt) {
|
||||
m_wind.time += dt;
|
||||
m_wind_controller.Update(m_wind.time,m_wind.strength);
|
||||
m_wind.matrices=m_wind_controller.GetMatrices();
|
||||
m_wind.legacy_leaf_rocking=true;
|
||||
m_wind.legacy_leaf_phase=m_wind_controller.GetLeafPhase();
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel_GetMainTree(std::map<uint32_t, std::shared_ptr<SpeedTreeModel>>& map, uint32_t crc) {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace speedtree {
|
||||
void SpeedTreeModel::AppendFrond(const std::vector<std::array<float,3>>& centers,
|
||||
std::array<float,3> side,std::array<float,3> other,uint32_t group,const std::vector<BranchFrame>* frames) {
|
||||
const auto& settings=m_info.fronds;
|
||||
if(centers.size()<2 || settings.type>1) return;
|
||||
// Texture selection/call ordering remains an SDK scheduling choice.
|
||||
size_t textureIndex=settings.textures.empty()?0:group%settings.textures.size();
|
||||
if(m_fronds.size()<=textureIndex) m_fronds.resize(textureIndex+1);
|
||||
auto& mesh=m_fronds[textureIndex];
|
||||
mesh.name="frond";mesh.alpha_test=true;mesh.alpha_ref=84.0f/255;
|
||||
mesh.is_double_sided=true;
|
||||
mesh.texture=m_leaf_texture;
|
||||
float aspect=1,scale=1,angle=0;
|
||||
if(!settings.textures.empty()) {
|
||||
const auto& texture=settings.textures[textureIndex];
|
||||
// Composite UVs refer to the shared composite material; otherwise use
|
||||
// the individual authored filename.
|
||||
if(m_info.frond_uv_quads.empty()) mesh.texture=texture.filename;
|
||||
aspect=texture.aspect;scale=texture.size_scale;
|
||||
LegacyRandom random(m_info.seed+group);
|
||||
angle=random.Uniform(texture.angle_min,texture.angle_max)*kPI/180;
|
||||
if(group&1) angle=-angle;
|
||||
}
|
||||
std::vector<float> distances(centers.size());
|
||||
for(size_t i=1;i<centers.size();++i) {
|
||||
float squared=0;
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
float delta=centers[i][axis]-centers[i-1][axis];squared+=delta*delta;
|
||||
}
|
||||
distances[i]=distances[i-1]+std::sqrt(squared);
|
||||
}
|
||||
// 10009040: half-width = centerline length * 0.5 * aspect * size scale.
|
||||
float width=distances.back()*0.5f*aspect*scale;
|
||||
if(!std::isfinite(width) || width<=0 || distances.back()<=1e-6f) return;
|
||||
uint32_t blades=settings.type==0?std::clamp(settings.blade_count,1u,8u):1;
|
||||
uint32_t segments=settings.type==0?2:std::clamp(settings.profile_segments,2u,16u)*2-1;
|
||||
const size_t vertexCount=size_t(blades)*segments*centers.size();
|
||||
// The SDK and client upload uint32 indices; 16-bit DLL buffers impose no
|
||||
// per-material limit here. Retain a shared per-model allocation budget.
|
||||
if(m_generation_stats.generated_vertices+vertexCount>GenerationStats::max_vertices) {
|
||||
m_generation_truncated=true;m_generation_stats.vertex_limit=true;return;
|
||||
}
|
||||
m_generation_stats.generated_vertices+=vertexCount;
|
||||
UVQuad uv{1,0,0,0,0,1,1,1};
|
||||
if(!m_info.frond_uv_quads.empty()) uv=m_info.frond_uv_quads[textureIndex%m_info.frond_uv_quads.size()];
|
||||
for(uint32_t blade=0;blade<blades;++blade) {
|
||||
float theta=angle+float(blade)*kPI/float(blades);
|
||||
std::array<float,3> lateral{},normal{};
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
lateral[axis]=side[axis]*std::cos(theta)+other[axis]*std::sin(theta);
|
||||
normal[axis]=-side[axis]*std::sin(theta)+other[axis]*std::cos(theta);
|
||||
}
|
||||
uint32_t base=uint32_t(mesh.vertices.size());
|
||||
for(size_t ring=0;ring<centers.size();++ring) for(uint32_t column=0;column<segments;++column) {
|
||||
if(frames && frames->size()==centers.size()) {
|
||||
const auto ringSide=(*frames)[ring].SdkAxis(0),ringOther=(*frames)[ring].SdkAxis(1);
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
lateral[axis]=ringSide[axis]*std::cos(theta)+ringOther[axis]*std::sin(theta);
|
||||
normal[axis]=-ringSide[axis]*std::sin(theta)+ringOther[axis]*std::cos(theta);
|
||||
}
|
||||
}
|
||||
float u=float(column)/float(segments-1),v=distances[ring]/distances.back();
|
||||
float across=(2*u-1)*width,offset=0,slope=0;
|
||||
if(settings.type==1 && !settings.profile.points.empty()) {
|
||||
float t=std::abs(2*u-1);
|
||||
offset=(settings.profile.Evaluate(t)-settings.profile.Evaluate(0))*width;
|
||||
float low=std::max(0.0f,t-0.002f),high=std::min(1.0f,t+0.002f);
|
||||
slope=(settings.profile.Evaluate(high)-settings.profile.Evaluate(low))/(high-low);
|
||||
if(u<0.5f) slope=-slope;
|
||||
}
|
||||
SpeedTreeVertex vertex{};
|
||||
float length=std::sqrt(1+slope*slope);
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
vertex.position[axis]=centers[ring][axis]+lateral[axis]*across+normal[axis]*offset;
|
||||
vertex.normal[axis]=(normal[axis]-lateral[axis]*slope)/length;
|
||||
}
|
||||
// Bilinear mapping retains authored rotated/nonrectangular atlas quads.
|
||||
for(size_t axis=0;axis<2;++axis)
|
||||
vertex.uv[axis]=(1-v)*((1-u)*uv[axis]+u*uv[2+axis])
|
||||
+v*((1-u)*uv[6+axis]+u*uv[4+axis]);
|
||||
vertex.diffuse=0xffffffff;
|
||||
vertex.wind_weights[0]=std::clamp(centers[ring][1]/m_height,0.0f,1.0f);
|
||||
vertex.wind_matrix_index=group%4;
|
||||
mesh.vertices.push_back(vertex);
|
||||
}
|
||||
mesh.grids.push_back({base,uint32_t(centers.size()),segments,false});
|
||||
for(uint32_t ring=0;ring+1<centers.size();++ring) for(uint32_t column=0;column+1<segments;++column) {
|
||||
uint32_t a=base+ring*segments+column,b=a+segments;
|
||||
for(uint32_t index:{a,b,b+1,a,b+1,a+1}) mesh.indices.push_back(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,27 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <cmath>
|
||||
|
||||
namespace speedtree {
|
||||
LeafCorners BuildLeafCorners(const LeafDefinition& leaf,bool mirrored,float scale) {
|
||||
// 10014b60: even leaf variants use 1-pivot.x, odd variants pivot.x.
|
||||
float px=mirrored?leaf.pivot[0]:1-leaf.pivot[0];
|
||||
float right=(1-px)*leaf.dimensions[0]*scale;
|
||||
float left=-px*leaf.dimensions[0]*scale;
|
||||
float top=(1-leaf.pivot[1])*leaf.dimensions[1]*scale;
|
||||
float bottom=-leaf.pivot[1]*leaf.dimensions[1]*scale;
|
||||
return {{{0,top,right},{0,top,left},{0,bottom,left},{0,bottom,right}}};
|
||||
}
|
||||
|
||||
std::array<float,3> OrientLeafOffset(std::array<float,3> offset,
|
||||
float azimuth,float pitch,float rocking) {
|
||||
// 10014b60 / 10005960: Rz(azimuth) * Ry(pitch) * Rx(rocking).
|
||||
// Swap SDK Y/Z into source coordinates before evaluating the composition.
|
||||
float x=offset[0],y=offset[2],z=offset[1];
|
||||
float a=rocking*kPI/180,c=std::cos(a),s=std::sin(a);
|
||||
float ry=y*c-z*s,rz=y*s+z*c;
|
||||
a=pitch*kPI/180;c=std::cos(a);s=std::sin(a);
|
||||
float rx=x*c+rz*s;z=-x*s+rz*c;
|
||||
a=azimuth*kPI/180;c=std::cos(a);s=std::sin(a);
|
||||
return {rx*c-ry*s,z,rx*s+ry*c};
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace speedtree {
|
||||
void LegacyWindController::Update(float time,float strength) {
|
||||
if(!std::isfinite(time)||!std::isfinite(strength)||strength<0) return;
|
||||
if(!initialized_) { previous_strength_=strength;initialized_=true; }
|
||||
constexpr float frequency[4][2]={{0.15f,0.17f},{0.25f,0.15f},{0.19f,0.05f},{0.15f,0.22f}};
|
||||
float dt=time-previous_time_;
|
||||
// 10025480 updates the offset by (old-new)*8*time to preserve leaf phase.
|
||||
leaf_offset_+=(previous_strength_-strength)*8.0f*time;
|
||||
leaf_phase_=time*8.0f*strength+leaf_offset_;
|
||||
matrices_.resize(4);
|
||||
for(size_t i=0;i<4;++i) {
|
||||
phases_[i]+=dt;
|
||||
if(strength!=0) phases_[i]=phases_[i]*previous_strength_/strength;
|
||||
float base=strength*35.0f/57.2957795f;
|
||||
float ax=base*std::sin(strength*20.0f*frequency[i][0]*phases_[i]);
|
||||
float ay=base*std::cos(strength*20.0f*frequency[i][1]*phases_[i]);
|
||||
float sx=std::sin(ax),sy=std::sin(ay),cx=std::cos(ax),cy=std::cos(ay);
|
||||
std::array<float,16> original{cy,0,-sy,0, sx*sy,cx,sx*cy,0, sy*cx,-sx,cx*cy,0, 0,0,0,1};
|
||||
// Source trees are Z-up; SDK geometry is Y-up. P*M*P swaps Y and Z.
|
||||
constexpr size_t map[4]={0,2,1,3};
|
||||
for(size_t col=0;col<4;++col) for(size_t row=0;row<4;++row)
|
||||
matrices_[i][col*4+row]=original[map[col]*4+map[row]];
|
||||
}
|
||||
previous_time_=time;previous_strength_=strength;
|
||||
}
|
||||
|
||||
int SelectDiscreteLod(float lod,uint32_t levels) {
|
||||
if(levels==0) return -1;
|
||||
if(!std::isfinite(lod)) return -1;
|
||||
lod=std::clamp(lod,0.0f,1.0f);
|
||||
uint32_t index=static_cast<uint32_t>((1.0f-lod)*levels);
|
||||
return int(std::min(index,levels-1));
|
||||
}
|
||||
|
||||
LodTransition SelectLodTransition(float lod,uint32_t levels,float width,
|
||||
float overlap,float exponent,float baseAlpha) {
|
||||
LodTransition result;
|
||||
if(levels==0 || levels>32767 || !std::isfinite(lod) || !std::isfinite(width)
|
||||
|| !std::isfinite(overlap) || !std::isfinite(exponent) || !std::isfinite(baseAlpha)) return result;
|
||||
lod=std::clamp(lod,0.0f,1.0f);baseAlpha=std::clamp(baseAlpha,0.0f,255.0f);
|
||||
float distance=1-lod, step=1.0f/float(levels);
|
||||
uint32_t nearest=uint32_t(std::floor(distance/step+0.5f));
|
||||
float delta=distance-float(nearest)*step;
|
||||
// 100207a0. Unlike opacity fading, these values are alpha-test thresholds.
|
||||
if(nearest>0 && nearest<levels && width>0 && overlap<1 && exponent>0 && std::abs(delta)<=width) {
|
||||
float phase=1-(width-delta)/(2*width);
|
||||
float divisor=1-overlap;
|
||||
float a=std::min(1.0f,1-(phase-overlap)/divisor);
|
||||
float b=std::min(1.0f,phase/divisor);
|
||||
result.first=int(nearest)-1;result.second=int(nearest);
|
||||
result.first_alpha=baseAlpha+(255-baseAlpha)*std::pow(std::max(0.0f,1-a),exponent);
|
||||
result.second_alpha=baseAlpha+(255-baseAlpha)*std::pow(std::max(0.0f,1-b),exponent);
|
||||
} else { result.first=SelectDiscreteLod(lod,levels);result.first_alpha=baseAlpha; }
|
||||
return result;
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <numeric>
|
||||
|
||||
namespace speedtree {
|
||||
namespace {
|
||||
SpeedTreeMesh ReduceGrid(const SpeedTreeMesh& source,uint32_t level) {
|
||||
if(source.grids.empty()) return source;
|
||||
SpeedTreeMesh out=source;out.vertices.clear();out.indices.clear();out.grids.clear();
|
||||
const uint32_t step=1u<<level;
|
||||
for(const auto& grid:source.grids) {
|
||||
uint32_t rows=std::max(1u,(grid.rows-1)/step);
|
||||
uint32_t cols=std::max(grid.closed?3u:1u,(grid.columns-1)/step);
|
||||
rows=std::min(rows,grid.rows-1);cols=std::min(cols,grid.columns-1);
|
||||
uint32_t base=uint32_t(out.vertices.size());
|
||||
for(uint32_t r=0;r<=rows;++r) for(uint32_t c=0;c<=cols;++c)
|
||||
out.vertices.push_back(source.vertices[grid.first+(r*(grid.rows-1)/rows)*grid.columns+c*(grid.columns-1)/cols]);
|
||||
for(uint32_t r=0;r<rows;++r) for(uint32_t c=0;c<cols;++c) {
|
||||
uint32_t a=base+r*(cols+1)+c,b=a+cols+1;
|
||||
for(uint32_t index:{a,b,b+1,a,b+1,a+1}) out.indices.push_back(index);
|
||||
}
|
||||
out.grids.push_back({base,rows+1,cols+1,grid.closed});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
SpeedTreeMesh ReduceLeaves(const SpeedTreeMesh& source,uint32_t level,float growth,
|
||||
const std::vector<size_t>& order) {
|
||||
if(source.vertices.empty() || source.vertices.size()%4 || source.indices.size()!=source.vertices.size()/4*6) return source;
|
||||
SpeedTreeMesh out=source;out.vertices.clear();out.indices.clear();out.grids.clear();
|
||||
size_t count=std::max(size_t(1),order.size()/(1u<<level));
|
||||
std::vector<size_t> kept(order.begin(),order.begin()+count);
|
||||
std::sort(kept.begin(),kept.end());
|
||||
float factor=std::clamp(1+float(level)*growth,0.01f,8.0f);
|
||||
for(size_t card:kept) {
|
||||
uint32_t base=uint32_t(out.vertices.size());
|
||||
for(size_t corner=0;corner<4;++corner) {
|
||||
auto vertex=source.vertices[card*4+corner];
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
vertex.position[axis]+=(factor-1)*vertex.leaf_pivot_offset[axis];
|
||||
vertex.leaf_pivot_offset[axis]*=factor;
|
||||
}
|
||||
out.vertices.push_back(vertex);
|
||||
}
|
||||
for(size_t i=0;i<6;++i) out.indices.push_back(base+source.indices[card*6+i]-uint32_t(card*4));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
void SpeedTreeModel::BuildLods() {
|
||||
m_trunk_lods.clear();m_leaf_lods.clear();m_frond_lods.clear();
|
||||
// Bounded SDK reduction of recovered generated topology. Original clustering
|
||||
// and importance-based reducers are still undergoing static recovery.
|
||||
uint32_t branches=std::clamp(m_info.branch_lod_levels,1u,8u);
|
||||
uint32_t leaves=std::clamp(m_info.leaf_lod_levels,1u,8u);
|
||||
uint32_t fronds=std::clamp(m_info.fronds.lod_levels,1u,8u);
|
||||
for(uint32_t level=1;level<branches;++level) m_trunk_lods.push_back(ReduceGrid(m_trunk,level));
|
||||
std::vector<size_t> order(m_leaf.vertices.size()/4);std::iota(order.begin(),order.end(),0);
|
||||
LegacyRandom random(m_info.seed);
|
||||
for(size_t i=order.size();i>1;--i) std::swap(order[i-1],order[std::min(size_t(random.Uniform()*float(i)),i-1)]);
|
||||
for(uint32_t level=1;level<leaves;++level) m_leaf_lods.push_back(ReduceLeaves(m_leaf,level,m_info.leaf_lod_growth,order));
|
||||
for(uint32_t level=1;level<fronds;++level) {
|
||||
std::vector<SpeedTreeMesh> meshes;
|
||||
for(const auto& mesh:m_fronds) meshes.push_back(ReduceGrid(mesh,level));
|
||||
m_frond_lods.push_back(std::move(meshes));
|
||||
}
|
||||
}
|
||||
const SpeedTreeMesh& SpeedTreeModel::GetTrunkMesh(uint32_t lod) const {
|
||||
return lod==0 || m_trunk_lods.empty()?m_trunk:m_trunk_lods[std::min(size_t(lod-1),m_trunk_lods.size()-1)];
|
||||
}
|
||||
const SpeedTreeMesh& SpeedTreeModel::GetLeafMesh(uint32_t lod) const {
|
||||
return lod==0 || m_leaf_lods.empty()?m_leaf:m_leaf_lods[std::min(size_t(lod-1),m_leaf_lods.size()-1)];
|
||||
}
|
||||
const std::vector<SpeedTreeMesh>& SpeedTreeModel::GetFrondMeshes(uint32_t lod) const {
|
||||
return lod==0 || m_frond_lods.empty()?m_fronds:m_frond_lods[std::min(size_t(lod-1),m_frond_lods.size()-1)];
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -1,7 +1,4 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
@@ -9,19 +6,6 @@ namespace speedtree {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string ToLower(std::string s) {
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string BaseName(std::string p) {
|
||||
for (char& c : p) if (c == '\\') c = '/';
|
||||
size_t s = p.find_last_of('/');
|
||||
return (s == std::string::npos) ? p : p.substr(s + 1);
|
||||
}
|
||||
|
||||
std::string StripQuotes(const std::string& s) {
|
||||
size_t start = s.find_first_not_of(" \t\r\n\"");
|
||||
if (start == std::string::npos) return "";
|
||||
@@ -29,23 +13,6 @@ std::string StripQuotes(const std::string& s) {
|
||||
return s.substr(start, end - start + 1);
|
||||
}
|
||||
|
||||
bool EndsWithCI(const std::string& s, const char* suf) {
|
||||
size_t n = std::strlen(suf);
|
||||
if (s.size() < n) return false;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (std::tolower((unsigned char)s[s.size() - n + i]) != std::tolower((unsigned char)suf[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string AsDds(std::string s) {
|
||||
if (s.empty()) return s;
|
||||
size_t dot = s.find_last_of('.');
|
||||
if (dot != std::string::npos) s.resize(dot);
|
||||
return s + ".dds";
|
||||
}
|
||||
|
||||
std::string ResolvePath(const std::string& raw) {
|
||||
if (raw.empty()) return raw;
|
||||
std::string clean = raw;
|
||||
@@ -59,10 +26,7 @@ std::string ResolvePath(const std::string& raw) {
|
||||
std::vector<std::string> roots = {
|
||||
"",
|
||||
"build/dev/",
|
||||
"build/dev/ymir work/",
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/",
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/property/",
|
||||
"/Users/shen/Work/Code/Metin2/ava2-client/"
|
||||
"build/dev/ymir work/"
|
||||
};
|
||||
for (const auto& r : roots) {
|
||||
std::string cand = r + clean;
|
||||
@@ -115,118 +79,4 @@ bool SpeedTreeProperty::LoadFromFile(const std::string& filename, SpeedTreePrope
|
||||
return !out.tree_file.empty() && (!has_yprt || out.crc != 0);
|
||||
}
|
||||
|
||||
bool SpeedTreeSptInfo::SniffFile(const std::string& filepath, SpeedTreeSptInfo& out) {
|
||||
std::string resolved = ResolvePath(filepath);
|
||||
std::ifstream f(resolved, std::ios::binary);
|
||||
if (!f.is_open()) return false;
|
||||
f.seekg(0, std::ios::end);
|
||||
size_t size = static_cast<size_t>(f.tellg());
|
||||
f.seekg(0, std::ios::beg);
|
||||
if (size < 16) return false;
|
||||
|
||||
std::vector<uint8_t> data(size);
|
||||
f.read(reinterpret_cast<char*>(data.data()), size);
|
||||
return SniffMemory(data.data(), size, out);
|
||||
}
|
||||
|
||||
bool SpeedTreeSptInfo::SniffMemory(const uint8_t* p, size_t n, SpeedTreeSptInfo& out) {
|
||||
if (!p || n < 16) return false;
|
||||
out.ok = true;
|
||||
out.size = 1000.0f;
|
||||
out.variance = 0.0f;
|
||||
out.bark_texture.clear();
|
||||
out.leaf_texture.clear();
|
||||
out.shadow_texture.clear();
|
||||
out.leaf_uvs.clear();
|
||||
out.frond_uvs.clear();
|
||||
out.billboard_uvs.clear();
|
||||
|
||||
auto i32_at = [p, n](size_t o) -> int32_t {
|
||||
if (o + 4 > n) return 0;
|
||||
int32_t val = 0;
|
||||
std::memcpy(&val, p + o, 4);
|
||||
return val;
|
||||
};
|
||||
|
||||
// Parse tokens
|
||||
for (size_t o = 0; o + 8 <= n; ++o) {
|
||||
int32_t token = i32_at(o);
|
||||
if (token == 2000) {
|
||||
// Branch texture name
|
||||
int32_t len = i32_at(o + 4);
|
||||
if (len > 0 && len < 256 && o + 8 + len <= n) {
|
||||
std::string s(reinterpret_cast<const char*>(p + o + 8), len);
|
||||
out.bark_texture = BaseName(s);
|
||||
}
|
||||
} else if (token == 2001) {
|
||||
float sz = 0.0f;
|
||||
std::memcpy(&sz, p + o + 4, 4);
|
||||
if (sz > 1.0f && sz < 50000.0f) out.size = sz;
|
||||
} else if (token == 2002) {
|
||||
float var = 0.0f;
|
||||
std::memcpy(&var, p + o + 4, 4);
|
||||
out.variance = var;
|
||||
} else if (token == 10000 && i32_at(o + 4) == 10002) {
|
||||
size_t c = o + 4;
|
||||
for (int32_t section : {10002, 10003, 10004}) {
|
||||
if (c + 8 > n || i32_at(c) != section) break;
|
||||
int32_t count = i32_at(c + 4);
|
||||
c += 8;
|
||||
if (count <= 0 || count > 64 || c + count * 32 > n) break;
|
||||
auto& target = (section == 10002) ? out.leaf_uvs : (section == 10003 ? out.frond_uvs : out.billboard_uvs);
|
||||
for (int32_t i = 0; i < count; ++i, c += 32) {
|
||||
float f[8];
|
||||
std::memcpy(f, p + c, sizeof(f));
|
||||
target.push_back({f[2], 1.0f - f[1], f[0], 1.0f - f[5]});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// String scan fallback for bark & composite maps
|
||||
std::string cur;
|
||||
std::vector<std::string> str_refs;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char c = p[i];
|
||||
if (c >= 0x20 && c < 0x7F) {
|
||||
cur += static_cast<char>(c);
|
||||
} else {
|
||||
if (cur.size() >= 4 && (EndsWithCI(cur, ".tga") || EndsWithCI(cur, ".dds"))) {
|
||||
str_refs.push_back(BaseName(cur));
|
||||
}
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& r : str_refs) {
|
||||
std::string low = ToLower(r);
|
||||
if (out.bark_texture.empty() && low.find("bark") != std::string::npos) {
|
||||
out.bark_texture = AsDds(r);
|
||||
} else if (out.leaf_texture.empty() && (low.find("leaf") != std::string::npos || low.find("leaves") != std::string::npos || low.find("grass") != std::string::npos)) {
|
||||
out.leaf_texture = AsDds(r);
|
||||
}
|
||||
}
|
||||
|
||||
std::string bytes(reinterpret_cast<const char*>(p), n);
|
||||
auto find_token = [&](const char* needle) -> std::string {
|
||||
size_t pos = bytes.find(needle);
|
||||
if (pos == std::string::npos) return "";
|
||||
size_t end = pos + std::strlen(needle);
|
||||
while (end < bytes.size() && (std::isalnum((unsigned char)bytes[end]) || bytes[end] == '_' || bytes[end] == '-')) {
|
||||
++end;
|
||||
}
|
||||
return bytes.substr(pos, end - pos);
|
||||
};
|
||||
|
||||
std::string comp = find_token("CompositeMap");
|
||||
if (!comp.empty()) out.leaf_texture = AsDds(comp);
|
||||
std::string shadow = find_token("CompositeShadowMap");
|
||||
if (!shadow.empty()) out.shadow_texture = AsDds(shadow);
|
||||
|
||||
if (out.bark_texture.empty()) out.bark_texture = "beechbark.dds";
|
||||
if (out.leaf_texture.empty()) out.leaf_texture = "compositemap.dds";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
// Metadata grammar recovered from AVA2 SpeedTreeRT.dll (SHA-256 ddba9b9b...6967b).
|
||||
// See ../REVERSE-ENGINEERING.md for function addresses, coverage and limitations.
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <cctype>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace speedtree {
|
||||
namespace {
|
||||
constexpr size_t kMaxFileSize = 64 * 1024 * 1024;
|
||||
|
||||
struct Unsupported { uint32_t token; };
|
||||
|
||||
class Reader {
|
||||
public:
|
||||
Reader(const uint8_t* bytes, size_t length) : data(bytes), size(length) {}
|
||||
size_t pos = 0;
|
||||
size_t remaining() const { return size - pos; }
|
||||
uint8_t byte() {
|
||||
if(!remaining()) throw std::runtime_error("truncated SPT byte");
|
||||
return data[pos++];
|
||||
}
|
||||
void skip(size_t count) {
|
||||
if (count > remaining()) throw std::runtime_error("truncated SPT payload");
|
||||
pos += count;
|
||||
}
|
||||
uint32_t u32() {
|
||||
if (remaining() < 4) throw std::runtime_error("truncated SPT token/value");
|
||||
uint32_t v = uint32_t(data[pos]) | (uint32_t(data[pos+1]) << 8)
|
||||
| (uint32_t(data[pos+2]) << 16) | (uint32_t(data[pos+3]) << 24);
|
||||
pos += 4;
|
||||
return v;
|
||||
}
|
||||
float f32() {
|
||||
float value = std::bit_cast<float>(u32());
|
||||
if (!std::isfinite(value)) throw std::runtime_error("non-finite SPT value");
|
||||
return value;
|
||||
}
|
||||
uint32_t count(size_t minBytes) {
|
||||
uint32_t n = u32();
|
||||
if (n > remaining() / minBytes) throw std::runtime_error("invalid SPT count");
|
||||
return n;
|
||||
}
|
||||
std::string string() {
|
||||
uint32_t length = count(1);
|
||||
std::string result(reinterpret_cast<const char*>(data + pos), length);
|
||||
skip(length);
|
||||
return result;
|
||||
}
|
||||
void expect(uint32_t token) {
|
||||
uint32_t actual = u32();
|
||||
if (actual != token) throw std::runtime_error("expected SPT marker " + std::to_string(token)
|
||||
+ ", got " + std::to_string(actual));
|
||||
}
|
||||
void floats(size_t n) { while (n--) f32(); }
|
||||
private:
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
std::string TextureName(std::string name) {
|
||||
std::replace(name.begin(), name.end(), '\\', '/');
|
||||
size_t slash = name.find_last_of('/');
|
||||
if (slash != std::string::npos) name.erase(0, slash + 1);
|
||||
// Existing clients use the DDS conversion of the author's TGA texture.
|
||||
size_t dot = name.find_last_of('.');
|
||||
if (dot != std::string::npos) {
|
||||
std::string ext = name.substr(dot);
|
||||
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
if (ext == ".tga") name.replace(dot, std::string::npos, ".dds");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
// Consume only known field widths. Unknown fields stop metadata extraction;
|
||||
// never resynchronize by scanning through string/float bytes for a token.
|
||||
BranchLevel Branch(Reader& r) {
|
||||
BranchLevel level;
|
||||
r.expect(1016);
|
||||
for (uint32_t t; (t = r.u32()) != 1017;) {
|
||||
if ((t >= 6000 && t <= 6007) || t == 6017) {
|
||||
if (!BranchSpline::Parse(r.string(), level.curves[t == 6017 ? 8 : t - 6000]))
|
||||
throw std::runtime_error("invalid branch BezierSpline");
|
||||
} else if (t == 6008) level.radial_segments = r.u32();
|
||||
else if (t == 6009) level.length_segments = r.u32();
|
||||
else if (t >= 6010 && t <= 6014) {
|
||||
level.scalar_fields[t-6010]=r.f32();
|
||||
if(t==6010 || t==6011) level.has_attachment_range=true;
|
||||
if(t==6012) level.has_child_density=true;
|
||||
}
|
||||
else if (t == 6015 || t == 6016) {
|
||||
// Reader bool fields occupy exactly one byte.
|
||||
level.flags[t-6015]=r.byte()!=0;
|
||||
}
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
void General(Reader& r, SpeedTreeSptInfo& out) {
|
||||
for (uint32_t t; (t = r.u32()) != 1003;) {
|
||||
switch (t) {
|
||||
case 2000: out.bark_texture = TextureName(r.string()); break;
|
||||
case 2001: out.lod_far = r.f32(); break;
|
||||
case 2002: r.skip(1); break;
|
||||
case 2003: out.lod_near = r.f32(); break;
|
||||
case 2004: r.u32(); break;
|
||||
case 2005: out.seed = r.u32(); break;
|
||||
case 2006: out.size = r.f32(); out.has_size = true; break;
|
||||
case 2007: out.variance = r.f32(); break;
|
||||
case 1014: {
|
||||
uint32_t n = r.count(8);
|
||||
out.branch_level_count = n;
|
||||
while (n--) out.branch_levels.push_back(Branch(r));
|
||||
r.expect(1015);
|
||||
break;
|
||||
}
|
||||
default: throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Leaf(Reader& r, SpeedTreeSptInfo& out) {
|
||||
for (uint32_t t; (t = r.u32()) != 1005;) {
|
||||
if (t == 1009) {
|
||||
out.leaves.clear();
|
||||
r.expect(1006);
|
||||
uint32_t n = r.count(8);
|
||||
while (n--) {
|
||||
r.expect(1007);LeafDefinition leaf;
|
||||
for (uint32_t field; (field = r.u32()) != 1008;) {
|
||||
if (field == 4000) leaf.flag=r.byte()!=0;
|
||||
else if (field == 4001) for(float& value:leaf.color) value=r.f32();
|
||||
else if (field == 4002) leaf.scalar=r.f32();
|
||||
else if (field == 4003) {
|
||||
leaf.texture=TextureName(r.string());
|
||||
if (out.leaf_texture.empty()) out.leaf_texture=leaf.texture;
|
||||
} else if (field>=4004 && field<=4006) {
|
||||
auto& vector=field==4004?leaf.pivot:field==4005?leaf.placement:leaf.dimensions;
|
||||
for(float& value:vector) value=r.f32();
|
||||
} else if(field==4007) r.f32(); // The original reader discards this obsolete value.
|
||||
else throw Unsupported{field};
|
||||
}
|
||||
out.leaves.push_back(std::move(leaf));
|
||||
}
|
||||
r.expect(1010);
|
||||
} else if(t==3000) out.special_leaves.minimum_position=r.f32();
|
||||
else if(t==3001) out.special_leaves.ancestor_depth=r.u32();
|
||||
else if(t==3002) out.special_leaves.probability=r.f32();
|
||||
else if (t == 3003 || t == 3006 || t == 3009) r.skip(1);
|
||||
else if (t == 3001 || t == 3008) r.u32();
|
||||
else if (t >= 3000 && t <= 3010) r.f32();
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
|
||||
void GeneralWind(Reader& r, SpeedTreeSptInfo& out) {
|
||||
for (uint32_t t; (t = r.u32()) != 1012;) {
|
||||
if (t == 5004) {
|
||||
out.leaf_rocking_range=r.f32();out.leaf_rocking_frequency=r.f32();r.f32();
|
||||
} else if (t >= 5000 && t <= 5003) r.floats(3);
|
||||
else if (t == 5005) r.f32();
|
||||
else if (t == 5006) {
|
||||
// This deprecated file flag is ignored by 100257e0, not applied to
|
||||
// CWindEngine rocking state (initialized true by 10025440).
|
||||
r.skip(1);
|
||||
}
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
|
||||
void Uvs(Reader& r, std::vector<UVQuad>& quads, std::vector<UVRect>& rects) {
|
||||
uint32_t count = r.count(32);
|
||||
quads.clear(); rects.clear();
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
UVQuad quad;
|
||||
for (float& v : quad) v = r.f32();
|
||||
quads.push_back(quad);
|
||||
UVRect bounds{quad[0], quad[1], quad[0], quad[1]};
|
||||
for (size_t j = 2; j < 8; j += 2) {
|
||||
bounds.u0 = std::min(bounds.u0, quad[j]); bounds.u1 = std::max(bounds.u1, quad[j]);
|
||||
bounds.v0 = std::min(bounds.v0, quad[j+1]); bounds.v1 = std::max(bounds.v1, quad[j+1]);
|
||||
}
|
||||
rects.push_back(bounds);
|
||||
}
|
||||
}
|
||||
|
||||
void TextureCoords(Reader& r, SpeedTreeSptInfo& out, bool supplemental) {
|
||||
uint32_t end = supplemental ? 20001 : 10001;
|
||||
for (uint32_t t; (t = r.u32()) != end;) {
|
||||
if (!supplemental && t == 10002) Uvs(r, out.leaf_uv_quads, out.leaf_uvs);
|
||||
else if (!supplemental && t == 10003) Uvs(r, out.billboard_uv_quads, out.billboard_uvs);
|
||||
else if (!supplemental && t == 10004) Uvs(r, out.frond_uv_quads, out.frond_uvs);
|
||||
else if (t == 10005 || t == 20002) out.leaf_texture = TextureName(r.string());
|
||||
else if (t == 10006 || t == 20003) out.horizontal_billboard = r.byte()!=0;
|
||||
else if (t == 10007 || t == 20004) out.billboard_360 = r.byte()!=0;
|
||||
else if (t == 20005) for (float& value : out.supplemental_uv) value=r.f32();
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
|
||||
void Lod(Reader& r, SpeedTreeSptInfo& out) {
|
||||
for (uint32_t t; (t = r.u32()) != 9001;) {
|
||||
if (t == 9002) out.lod_method=r.u32();
|
||||
else if (t == 9003) out.lod_transition_width=r.f32();
|
||||
else if (t == 9004) out.lod_alpha_exponent=r.f32();
|
||||
else if (t == 9009) out.leaf_lod_growth=r.f32();
|
||||
else if (t == 9005) {
|
||||
for (uint32_t field; (field = r.u32()) != 9006;) {
|
||||
if (field == 9007) out.branch_lod_levels=r.u32();
|
||||
else if (field == 9011) out.leaf_lod_levels=r.u32();
|
||||
else if (field == 9008 || (field >= 9010 && field <= 9014)) r.f32();
|
||||
else throw Unsupported{field};
|
||||
}
|
||||
} else throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
|
||||
void Lighting(Reader& r) {
|
||||
for (uint32_t t; (t = r.u32()) != 8001;) {
|
||||
if (t == 8003 || t == 8005 || t == 8009) r.floats(13);
|
||||
else if (t >= 8002 && t <= 8009) r.skip(4);
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
|
||||
void Collisions(Reader& r, SpeedTreeSptInfo& out) {
|
||||
for (uint32_t t; (t = r.u32()) != 12001;) {
|
||||
if (t < 12002 || t > 12004) throw Unsupported{t};
|
||||
CollisionObject object;
|
||||
object.type = static_cast<CollisionObject::Type>(t - 12002);
|
||||
for (float& value : object.position) value = r.f32();
|
||||
for (uint32_t i = 0; i < t - 12001; ++i) object.dimensions[i] = r.f32();
|
||||
out.collision_objects.push_back(object);
|
||||
}
|
||||
}
|
||||
|
||||
void Fronds(Reader& r, SpeedTreeSptInfo& out) {
|
||||
auto& settings=out.fronds;
|
||||
for (uint32_t t; (t = r.u32()) != 13001;) {
|
||||
switch(t) {
|
||||
case 13002: settings.start_level=r.u32();break;
|
||||
case 13003: settings.type=r.u32();break;
|
||||
case 13004: settings.blade_count=r.u32();break;
|
||||
case 13005:
|
||||
if(!BranchSpline::Parse(r.string(),settings.profile))
|
||||
throw std::runtime_error("invalid frond profile spline");
|
||||
break;
|
||||
case 13006: settings.profile_segments=r.u32();break;
|
||||
case 13007: settings.enabled=r.byte()!=0;break;
|
||||
case 13008: {
|
||||
uint32_t n=r.count(8);settings.textures.clear();
|
||||
while(n--) {
|
||||
r.expect(14000);FrondTexture texture;
|
||||
for(uint32_t field;(field=r.u32())!=14001;) {
|
||||
if(field==14002) texture.filename=TextureName(r.string());
|
||||
else if(field==14003) texture.aspect=r.f32();
|
||||
else if(field==14004) texture.size_scale=r.f32();
|
||||
else if(field==14005) texture.angle_min=r.f32();
|
||||
else if(field==14006) texture.angle_max=r.f32();
|
||||
else throw Unsupported{field};
|
||||
}
|
||||
settings.textures.push_back(std::move(texture));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 13009: settings.lod_levels=r.u32();break;
|
||||
case 13010: case 13011: case 13012: case 13013:
|
||||
settings.lod_fields[t-13010]=r.f32();break;
|
||||
case 14007: settings.segment_override=r.u32();break;
|
||||
case 14008: settings.reduction_mode=r.u32();break;
|
||||
default: throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Extensions(Reader& r, SpeedTreeSptInfo& out) {
|
||||
while (r.remaining()) {
|
||||
uint32_t t = r.u32();
|
||||
switch (t) {
|
||||
case 8000: Lighting(r); break;
|
||||
case 9000: Lod(r, out); break;
|
||||
case 10000: TextureCoords(r, out, false); break;
|
||||
case 11000:
|
||||
for (uint32_t field; (field = r.u32()) != 11001;) {
|
||||
if (field != 11002) throw Unsupported{field};
|
||||
out.wind_level = r.u32();
|
||||
}
|
||||
break;
|
||||
case 12000: Collisions(r, out); break;
|
||||
case 13000: Fronds(r, out); break;
|
||||
case 15000:
|
||||
for (uint32_t i = 0; i < out.branch_level_count; ++i) {
|
||||
r.expect(15002); r.skip(1); r.expect(15003); r.f32();
|
||||
}
|
||||
r.expect(15001);
|
||||
break;
|
||||
case 16000:
|
||||
for (uint32_t i = 0; i < out.branch_level_count; ++i) {
|
||||
r.expect(16002); out.branch_levels[i].length_exponent=r.f32(); r.expect(16003); r.u32();
|
||||
for (uint32_t field = 16004; field <= 16012; ++field) { r.expect(field); r.f32(); }
|
||||
}
|
||||
r.expect(16001);
|
||||
break;
|
||||
case 16013: r.u32(); break;
|
||||
case 16014: out.lod_transition_overlap=r.f32(); break;
|
||||
case 18000:
|
||||
for (uint32_t field; (field = r.u32()) != 18001;) {
|
||||
if (field >= 18002 && field <= 18004) r.floats(3);
|
||||
else if (field == 18005) out.shadow_texture = TextureName(r.string());
|
||||
else throw Unsupported{field};
|
||||
}
|
||||
break;
|
||||
case 19000:
|
||||
for (uint32_t field; (field = r.u32()) != 19001;) {
|
||||
if (field != 19002) throw Unsupported{field};
|
||||
r.string();
|
||||
}
|
||||
break;
|
||||
case 20000: TextureCoords(r, out, true); break;
|
||||
case 21000:
|
||||
// All 283 corpus occurrences are exactly two token-tagged floats.
|
||||
// Preserve values without applying an unverified semantic meaning.
|
||||
out.extension_21000[0]=r.f32();r.expect(21001);
|
||||
out.extension_21000[1]=r.f32();out.has_extension_21000=true;break;
|
||||
default: throw Unsupported{t};
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool SpeedTreeSptInfo::SniffFile(const std::string& filepath, SpeedTreeSptInfo& out) {
|
||||
out = {};
|
||||
std::string path = filepath;
|
||||
std::replace(path.begin(), path.end(), '\\', '/');
|
||||
if (path.size() > 2 && path[1] == ':') {
|
||||
path.erase(0, 2);
|
||||
while (!path.empty() && path.front() == '/') path.erase(0, 1);
|
||||
}
|
||||
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
||||
if (!file) { out.error = "SPT file not found"; return false; }
|
||||
auto length = file.tellg();
|
||||
if (length < 0 || static_cast<uint64_t>(length) > kMaxFileSize) {
|
||||
out.error = "invalid SPT file size"; return false;
|
||||
}
|
||||
std::vector<uint8_t> data(static_cast<size_t>(length));
|
||||
file.seekg(0);
|
||||
if (!file.read(reinterpret_cast<char*>(data.data()), data.size())) {
|
||||
out.error = "SPT file read failed"; return false;
|
||||
}
|
||||
return SniffMemory(data.data(), data.size(), out);
|
||||
}
|
||||
|
||||
bool SpeedTreeSptInfo::SniffMemory(const uint8_t* data, size_t length, SpeedTreeSptInfo& out) {
|
||||
out = {};
|
||||
if (!data || length < 24 || length > kMaxFileSize) {
|
||||
out.error = "invalid SPT buffer size"; return false;
|
||||
}
|
||||
Reader r(data, length);
|
||||
SpeedTreeSptInfo parsed;
|
||||
bool mainComplete = false;
|
||||
try {
|
||||
r.expect(1000);
|
||||
if (r.string() != "__IdvSpt_02_") throw std::runtime_error("unsupported SPT signature");
|
||||
bool general = false;
|
||||
for (uint32_t t; (t = r.u32()) != 1001;) {
|
||||
if (t == 1002) { General(r, parsed); general = true; }
|
||||
else if (t == 1004) Leaf(r, parsed);
|
||||
else if (t == 1011) GeneralWind(r, parsed);
|
||||
else throw Unsupported{t};
|
||||
}
|
||||
if (!general || !parsed.has_size || parsed.size <= 0 || parsed.variance < 0)
|
||||
throw std::runtime_error("invalid or missing general tree information");
|
||||
mainComplete = true;
|
||||
Extensions(r, parsed);
|
||||
parsed.metadata_complete = true;
|
||||
} catch (const Unsupported& unsupported) {
|
||||
parsed.unsupported_token = unsupported.token;
|
||||
parsed.error = "unsupported SPT token " + std::to_string(unsupported.token);
|
||||
if (!mainComplete) { out.error = parsed.error; out.parsed_bytes = r.pos; return false; }
|
||||
} catch (const std::exception& error) {
|
||||
out.error = error.what(); out.parsed_bytes = r.pos; return false;
|
||||
}
|
||||
parsed.ok = true;
|
||||
parsed.parsed_bytes = r.pos;
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
float SpeedTreeSptInfo::EvaluateLod(float distance) const {
|
||||
if (!std::isfinite(distance) || !(lod_far > lod_near)) return 1.0f;
|
||||
return std::clamp(1.0f - (distance - lod_near) / (lod_far - lod_near), 0.0f, 1.0f);
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace speedtree {
|
||||
@@ -47,7 +48,7 @@ SpeedTreeModel::SpeedTreeModel() {
|
||||
m_leaf.alpha_ref = 0.45f;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromSpt(const std::string& sptPath, float treeSize) {
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromSpt(const std::string& sptPath, float treeSize, float treeVariance) {
|
||||
auto model = std::make_shared<SpeedTreeModel>();
|
||||
model->m_spt_path = sptPath;
|
||||
|
||||
@@ -56,37 +57,25 @@ std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromSpt(const std::string&
|
||||
model->m_name = (last_slash == std::string::npos) ? sptPath : sptPath.substr(last_slash + 1);
|
||||
|
||||
SpeedTreeSptInfo info;
|
||||
if (SpeedTreeSptInfo::SniffFile(sptPath, info)) {
|
||||
if (info.size > 1.0f) model->m_height = info.size;
|
||||
else model->m_height = treeSize;
|
||||
model->BuildGeometry(info);
|
||||
} else {
|
||||
model->m_height = treeSize;
|
||||
info.size = treeSize;
|
||||
info.bark_texture = "beechbark.dds";
|
||||
info.leaf_texture = "compositemap.dds";
|
||||
model->BuildGeometry(info);
|
||||
}
|
||||
if (!SpeedTreeSptInfo::SniffFile(sptPath, info)) return nullptr;
|
||||
model->m_height = (std::isfinite(treeSize) && treeSize > 0.0f) ? treeSize : info.size;
|
||||
if (!std::isfinite(treeVariance) || treeVariance < 0) return nullptr;
|
||||
model->m_generation_variance = treeSize > 0 ? treeVariance : info.variance;
|
||||
model->BuildGeometry(info);
|
||||
return model;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromMemory(const uint8_t* data, size_t size,
|
||||
const std::string& name, float treeSize) {
|
||||
const std::string& name, float treeSize, float treeVariance) {
|
||||
auto model = std::make_shared<SpeedTreeModel>();
|
||||
model->m_name = name.empty() ? "tree" : name;
|
||||
|
||||
SpeedTreeSptInfo info;
|
||||
if (SpeedTreeSptInfo::SniffMemory(data, size, info)) {
|
||||
if (info.size > 1.0f) model->m_height = info.size;
|
||||
else model->m_height = treeSize;
|
||||
model->BuildGeometry(info);
|
||||
} else {
|
||||
model->m_height = treeSize;
|
||||
info.size = treeSize;
|
||||
info.bark_texture = "beechbark.dds";
|
||||
info.leaf_texture = "compositemap.dds";
|
||||
model->BuildGeometry(info);
|
||||
}
|
||||
if (!SpeedTreeSptInfo::SniffMemory(data, size, info)) return nullptr;
|
||||
model->m_height = (std::isfinite(treeSize) && treeSize > 0.0f) ? treeSize : info.size;
|
||||
if (!std::isfinite(treeVariance) || treeVariance < 0) return nullptr;
|
||||
model->m_generation_variance = treeSize > 0 ? treeVariance : info.variance;
|
||||
model->BuildGeometry(info);
|
||||
return model;
|
||||
}
|
||||
|
||||
@@ -118,12 +107,45 @@ void SpeedTreeModel::BuildGeometry(const SpeedTreeSptInfo& info) {
|
||||
lowerName.find("flower") != std::string::npos ||
|
||||
m_height < 150.0f);
|
||||
|
||||
if((info.fronds.enabled || !info.leaves.empty()) && !info.branch_levels.empty()) m_is_grass_or_shrub=false;
|
||||
float H = m_height;
|
||||
if (m_is_grass_or_shrub) {
|
||||
BuildGrassShrubGeometry(H, info);
|
||||
} else {
|
||||
BuildTreeGeometry(H, info);
|
||||
}
|
||||
// Also expose counts for the procedural/grass fallback paths.
|
||||
m_generation_stats.generated_vertices=m_trunk.vertices.size()+m_leaf.vertices.size();
|
||||
for(const auto& mesh:m_fronds) m_generation_stats.generated_vertices+=mesh.vertices.size();
|
||||
BuildLods();
|
||||
m_bounds_min.fill(std::numeric_limits<float>::infinity());
|
||||
m_bounds_max.fill(-m_bounds_min[0]);
|
||||
std::vector<const SpeedTreeMesh*> allMeshes{&m_trunk,&m_leaf};
|
||||
for(const auto& mesh:m_trunk_lods) allMeshes.push_back(&mesh);
|
||||
for(const auto& mesh:m_leaf_lods) allMeshes.push_back(&mesh);
|
||||
for(const auto& mesh:m_fronds) allMeshes.push_back(&mesh);
|
||||
for(const auto& level:m_frond_lods) for(const auto& mesh:level) allMeshes.push_back(&mesh);
|
||||
for(const auto* mesh:allMeshes) for(const auto& vertex:mesh->vertices)
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
m_bounds_min[axis]=std::min(m_bounds_min[axis],vertex.position[axis]);
|
||||
m_bounds_max[axis]=std::max(m_bounds_max[axis],vertex.position[axis]);
|
||||
if(vertex.authored_leaf_card) {
|
||||
float squared=0;for(float value:vertex.leaf_pivot_offset) squared+=value*value;
|
||||
float extent=std::sqrt(squared),pivot=vertex.position[axis]-vertex.leaf_pivot_offset[axis];
|
||||
m_bounds_min[axis]=std::min(m_bounds_min[axis],pivot-extent);
|
||||
m_bounds_max[axis]=std::max(m_bounds_max[axis],pivot+extent);
|
||||
}
|
||||
}
|
||||
if(std::isfinite(m_bounds_min[0])) {
|
||||
float rx=std::max(std::abs(m_bounds_min[0]),std::abs(m_bounds_max[0]));
|
||||
float rz=std::max(std::abs(m_bounds_min[2]),std::abs(m_bounds_max[2]));
|
||||
float ry=std::max(std::abs(m_bounds_min[1]-m_height*0.5f),std::abs(m_bounds_max[1]-m_height*0.5f));
|
||||
m_radius=std::max(m_radius,std::sqrt(rx*rx+ry*ry+rz*rz));
|
||||
} else {
|
||||
// A zero-length authored frond with no children can legitimately emit
|
||||
// no geometry. Keep its public bounds finite for culling and snapshots.
|
||||
m_bounds_min.fill(0);m_bounds_max.fill(0);m_radius=0;
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
@@ -164,6 +186,13 @@ void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& in
|
||||
{uv.u0, uv.v0}
|
||||
};
|
||||
|
||||
if (!info.leaf_uv_quads.empty()) {
|
||||
const auto& quad = info.leaf_uv_quads.front();
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
uvs[c][0] = quad[c * 2]; uvs[c][1] = quad[c * 2 + 1];
|
||||
}
|
||||
}
|
||||
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
SpeedTreeVertex vert{};
|
||||
vert.position[0] = corners[c][0];
|
||||
@@ -205,6 +234,7 @@ void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& in
|
||||
|
||||
void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
bool conifer = IsConifer(m_name);
|
||||
if (!info.branch_levels.empty()) { BuildAuthoredBranches(H, info); return; }
|
||||
|
||||
m_trunk.vertices.clear();
|
||||
m_trunk.indices.clear();
|
||||
@@ -285,6 +315,8 @@ void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
if (uv_pool.empty()) uv_pool = info.frond_uvs;
|
||||
if (uv_pool.empty()) uv_pool.push_back({0.0f, 0.0f, 1.0f, 1.0f});
|
||||
|
||||
const auto& quad_pool = info.leaf_uv_quads.empty() ? info.frond_uv_quads : info.leaf_uv_quads;
|
||||
|
||||
int cluster_count = conifer ? 16 : 14;
|
||||
float crown_center_y = H * (conifer ? 0.60f : 0.65f);
|
||||
|
||||
@@ -331,6 +363,13 @@ void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
{uv.u0, uv.v0}
|
||||
};
|
||||
|
||||
if (!quad_pool.empty()) {
|
||||
const auto& quad = quad_pool[k % quad_pool.size()];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
uvs[i][0] = quad[i * 2]; uvs[i][1] = quad[i * 2 + 1];
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
SpeedTreeVertex vert{};
|
||||
vert.position[0] = pts[i][0];
|
||||
@@ -358,7 +397,7 @@ void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
float norm_y = pts[i][1] / H;
|
||||
vert.wind_weights[0] = norm_y * norm_y; // Level 1: Trunk bend (H^2)
|
||||
vert.wind_weights[1] = std::clamp(spread / (H * 0.3f), 0.0f, 1.0f); // Level 2: Branch sway
|
||||
vert.wind_weights[2] = (i >= 2) ? 1.0f : 0.6f; // Level 3: Leaf flutter
|
||||
vert.wind_weights[2] = 1.0f; // Level 3: Leaf flutter
|
||||
vert.wind_weights[3] = cluster_phase; // Phase offset
|
||||
|
||||
// Leaf Pivot Offset: Relative vector from cluster center to this vertex
|
||||
@@ -385,77 +424,4 @@ void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedTreeModel::EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh,
|
||||
std::vector<float>& out_positions,
|
||||
std::vector<float>& out_normals,
|
||||
float worldX, float worldY, float worldZ,
|
||||
float yawDeg, float scale,
|
||||
const WindParameters& wind) const {
|
||||
size_t nverts = src_mesh.vertices.size();
|
||||
out_positions.resize(nverts * 3);
|
||||
out_normals.resize(nverts * 3);
|
||||
|
||||
float rad = yawDeg * (kPI / 180.0f);
|
||||
float cos_y = std::cos(rad);
|
||||
float sin_y = std::sin(rad);
|
||||
|
||||
float gust_spatial = (worldX + worldZ) * 0.005f;
|
||||
float gust = std::sin(wind.time * wind.gust_frequency + gust_spatial) * 0.5f + 0.5f;
|
||||
float eff_wind = wind.strength * (0.8f + 0.4f * gust);
|
||||
|
||||
for (size_t i = 0; i < nverts; ++i) {
|
||||
const auto& v = src_mesh.vertices[i];
|
||||
|
||||
// 1. Scale
|
||||
float lx = v.position[0] * scale;
|
||||
float ly = v.position[1] * scale;
|
||||
float lz = v.position[2] * scale;
|
||||
|
||||
// 2. Leaf tumble around pivot (Level 3 wind)
|
||||
if (src_mesh.is_leaf && v.wind_weights[2] > 0.01f) {
|
||||
float leaf_osc = std::sin(wind.time * 8.0f + v.wind_weights[3] * 15.0f + lx + lz);
|
||||
float leaf_angle = v.wind_weights[2] * 0.25f * leaf_osc * eff_wind;
|
||||
float cos_l = std::cos(leaf_angle);
|
||||
float sin_l = std::sin(leaf_angle);
|
||||
|
||||
// Rotate pivot offset around wind axis
|
||||
float rel_x = v.leaf_pivot_offset[0] * scale;
|
||||
float rel_z = v.leaf_pivot_offset[2] * scale;
|
||||
float rot_rel_x, rot_rel_z;
|
||||
RotateY(rel_x, rel_z, cos_l, sin_l, rot_rel_x, rot_rel_z);
|
||||
|
||||
lx += (rot_rel_x - rel_x);
|
||||
lz += (rot_rel_z - rel_z);
|
||||
}
|
||||
|
||||
// 3. Trunk & Branch sway (Level 1 & 2 wind)
|
||||
float trunk_flex = v.wind_weights[0] * 0.08f * eff_wind;
|
||||
float branch_flex = v.wind_weights[1] * 0.05f * eff_wind;
|
||||
float sway = std::sin(wind.time * 1.5f + gust_spatial) * trunk_flex +
|
||||
std::cos(wind.time * 2.8f + v.wind_weights[3] * 6.28f) * branch_flex;
|
||||
|
||||
lx += wind.direction[0] * sway * (m_height * scale);
|
||||
lz += wind.direction[2] * sway * (m_height * scale);
|
||||
|
||||
// 4. World Yaw Rotation
|
||||
float rx, rz;
|
||||
RotateY(lx, lz, cos_y, sin_y, rx, rz);
|
||||
|
||||
out_positions[i * 3 + 0] = worldX + rx;
|
||||
out_positions[i * 3 + 1] = worldY + ly;
|
||||
out_positions[i * 3 + 2] = worldZ + rz;
|
||||
|
||||
// Rotate normal
|
||||
float nx = v.normal[0];
|
||||
float ny = v.normal[1];
|
||||
float nz = v.normal[2];
|
||||
float rnx, rnz;
|
||||
RotateY(nx, nz, cos_y, sin_y, rnx, rnz);
|
||||
|
||||
out_normals[i * 3 + 0] = rnx;
|
||||
out_normals[i * 3 + 1] = ny;
|
||||
out_normals[i * 3 + 2] = rnz;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace speedtree {
|
||||
namespace {
|
||||
using V = std::array<float, 3>;
|
||||
V normalize(V v) {
|
||||
float len = std::sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
|
||||
if (len > 1e-7f) for (float& x : v) x /= len;
|
||||
return v;
|
||||
}
|
||||
V rotate(V v, V axis, float angle) {
|
||||
float c = std::cos(angle), s = std::sin(angle);
|
||||
float dot = v[0]*axis[0]+v[1]*axis[1]+v[2]*axis[2];
|
||||
V cross{axis[1]*v[2]-axis[2]*v[1],axis[2]*v[0]-axis[0]*v[2],axis[0]*v[1]-axis[1]*v[0]};
|
||||
for (size_t i = 0; i < 3; ++i) v[i] = v[i]*c+cross[i]*s+axis[i]*dot*(1-c);
|
||||
return v;
|
||||
}
|
||||
V yaw(V v, float c, float s) { return {v[0]*c+v[2]*s,v[1],-v[0]*s+v[2]*c}; }
|
||||
}
|
||||
|
||||
void SpeedTreeModel::EvaluateCpuTransformedVertices(const SpeedTreeMesh& mesh,
|
||||
std::vector<float>& positions, std::vector<float>& normals, float x, float y, float z,
|
||||
float yawDeg, float scale, const WindParameters& wind, const std::array<float,3>* camera) const {
|
||||
positions.resize(mesh.vertices.size()*3); normals.resize(mesh.vertices.size()*3);
|
||||
float angle = yawDeg*kPI/180, c = std::cos(angle), s = std::sin(angle);
|
||||
V direction = normalize({wind.direction[0],0,wind.direction[2]});
|
||||
if (direction[0] == 0 && direction[2] == 0) direction = {1,0,0};
|
||||
V localDirection = yaw(direction,c,-s);
|
||||
V axis = normalize({localDirection[2],0,-localDirection[0]});
|
||||
if (axis[0] == 0 && axis[2] == 0) axis = {0,0,-1};
|
||||
float spatial = (x*direction[0]+z*direction[2])*0.005f;
|
||||
float gust = 0.5f+0.5f*std::sin(wind.time*wind.gust_frequency+spatial);
|
||||
float strength = std::max(0.0f,wind.strength);
|
||||
float cameraAzimuth=0,cameraPitch=0;
|
||||
if(camera && std::all_of(camera->begin(),camera->end(),[](float value){return std::isfinite(value);})) {
|
||||
V local=yaw(normalize({(*camera)[0]-x,(*camera)[1]-y,(*camera)[2]-z}),c,-s);
|
||||
cameraAzimuth=std::atan2(local[2],local[0])*180/kPI;
|
||||
cameraPitch=-std::asin(std::clamp(local[1],-1.0f,1.0f))*180/kPI;
|
||||
}
|
||||
for (size_t i = 0; i < mesh.vertices.size(); ++i) {
|
||||
const auto& v = mesh.vertices[i];
|
||||
V p{v.position[0],v.position[1],v.position[2]}, n{v.normal[0],v.normal[1],v.normal[2]};
|
||||
// One angle per card, around its authored pivot; zero strength is neutral.
|
||||
if(mesh.is_leaf && v.authored_leaf_card) {
|
||||
float phase=wind.legacy_leaf_rocking?wind.legacy_leaf_phase:wind.time*8*strength;
|
||||
float rock=m_info.leaf_rocking_enabled?180*m_info.leaf_rocking_range*strength
|
||||
*std::sin(phase*m_info.leaf_rocking_frequency+v.leaf_rocking_phase):0;
|
||||
V offset{v.leaf_pivot_offset[0],v.leaf_pivot_offset[1],v.leaf_pivot_offset[2]};
|
||||
V transformed=OrientLeafOffset(offset,cameraAzimuth,cameraPitch,rock);
|
||||
for(size_t axis=0;axis<3;++axis) p[axis]+=transformed[axis]-offset[axis];
|
||||
n=OrientLeafOffset(n,cameraAzimuth,cameraPitch,rock);
|
||||
} else if (mesh.is_leaf) {
|
||||
float rock = 0.25f*strength*v.wind_weights[2]
|
||||
*std::sin(wind.time*8+v.wind_weights[3]*15);
|
||||
if(wind.legacy_leaf_rocking) {
|
||||
rock=m_info.leaf_rocking_enabled ? kPI*m_info.leaf_rocking_range*strength
|
||||
*v.wind_weights[2]*std::sin(wind.legacy_leaf_phase*m_info.leaf_rocking_frequency
|
||||
+v.wind_weights[3]*15) : 0.0f;
|
||||
}
|
||||
V offset{v.leaf_pivot_offset[0],v.leaf_pivot_offset[1],v.leaf_pivot_offset[2]};
|
||||
V rotated = rotate(offset,localDirection,rock);
|
||||
for (size_t j = 0; j < 3; ++j) p[j] += rotated[j]-offset[j];
|
||||
n = rotate(n,localDirection,rock);
|
||||
}
|
||||
float weight = std::clamp(v.wind_weights[0]+0.4f*v.wind_weights[1],0.0f,1.0f);
|
||||
std::array<float,16> matrix{};
|
||||
if (!wind.matrices.empty()) matrix = wind.matrices[v.wind_matrix_index % wind.matrices.size()];
|
||||
else {
|
||||
float bend = 0.12f*strength*(1+wind.gust_strength*gust)
|
||||
*std::sin(wind.time*1.5f+spatial+float(v.wind_matrix_index%4)*0.7f);
|
||||
for (size_t j = 0; j < 3; ++j) {
|
||||
V basis{}; basis[j] = 1;
|
||||
V column = rotate(basis,axis,bend);
|
||||
for (size_t k = 0; k < 3; ++k) matrix[j*4+k] = column[k];
|
||||
}
|
||||
matrix[15] = 1;
|
||||
}
|
||||
// Original 10011e10: p' = p + weight * (M*p - p).
|
||||
float a[3][3];
|
||||
V transformed{};
|
||||
for (size_t row = 0; row < 3; ++row) {
|
||||
for (size_t col = 0; col < 3; ++col)
|
||||
a[row][col] = (row==col ? 1-weight : 0)+weight*matrix[col*4+row];
|
||||
transformed[row] = a[row][0]*p[0]+a[row][1]*p[1]+a[row][2]*p[2]+weight*matrix[12+row];
|
||||
}
|
||||
// Inverse transpose of the blended linear map, so normals follow bending.
|
||||
V cof0{a[1][1]*a[2][2]-a[1][2]*a[2][1],a[1][2]*a[2][0]-a[1][0]*a[2][2],a[1][0]*a[2][1]-a[1][1]*a[2][0]};
|
||||
V cof1{a[0][2]*a[2][1]-a[0][1]*a[2][2],a[0][0]*a[2][2]-a[0][2]*a[2][0],a[0][1]*a[2][0]-a[0][0]*a[2][1]};
|
||||
V cof2{a[0][1]*a[1][2]-a[0][2]*a[1][1],a[0][2]*a[1][0]-a[0][0]*a[1][2],a[0][0]*a[1][1]-a[0][1]*a[1][0]};
|
||||
float det = a[0][0]*cof0[0]+a[0][1]*cof0[1]+a[0][2]*cof0[2];
|
||||
if (std::abs(det) > 1e-7f) n = {(cof0[0]*n[0]+cof0[1]*n[1]+cof0[2]*n[2])/det,
|
||||
(cof1[0]*n[0]+cof1[1]*n[1]+cof1[2]*n[2])/det,
|
||||
(cof2[0]*n[0]+cof2[1]*n[1]+cof2[2]*n[2])/det};
|
||||
p = yaw(transformed,c,s); n = normalize(yaw(n,c,s));
|
||||
for (size_t j = 0; j < 3; ++j) { positions[i*3+j] = p[j]*scale+(j==0?x:j==1?y:z); normals[i*3+j]=n[j]; }
|
||||
}
|
||||
}
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,481 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include "speedtree/foliage_shaders.h"
|
||||
#include <bit>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <cstring>
|
||||
|
||||
using namespace speedtree;
|
||||
void check(bool v,const char* message) { if(!v) throw std::runtime_error(message); }
|
||||
bool close(float a,float b) { return std::abs(a-b)<0.002f; }
|
||||
struct Stream {
|
||||
std::vector<uint8_t> data;
|
||||
void u(uint32_t v) { for(int i=0;i<4;++i)data.push_back(uint8_t(v>>(i*8))); }
|
||||
void f(float v) { u(std::bit_cast<uint32_t>(v)); }
|
||||
void s(const std::string& s) { u(uint32_t(s.size()));data.insert(data.end(),s.begin(),s.end()); }
|
||||
};
|
||||
Stream authored(uint32_t seed,float radius,float density=-1,uint32_t levels=2) {
|
||||
Stream b;b.u(1000);b.s("__IdvSpt_02_");b.u(1002);
|
||||
b.u(2005);b.u(seed);b.u(2006);b.f(1000);b.u(2007);b.f(30);
|
||||
b.u(1014);b.u(levels);
|
||||
for(uint32_t level=0;level<levels;++level) {
|
||||
b.u(1016);b.u(6008);b.u(6);b.u(6009);b.u(4);
|
||||
for(uint32_t t:{6001u,6003u,6004u,6005u,6006u,6007u}) {
|
||||
float low=0,high=0;
|
||||
if(t==6003) high=1;
|
||||
if(t==6004) low=high=level==0?0.7f:0.25f;
|
||||
if(t==6005) low=high=level==0?radius:0.008f;
|
||||
if(t==6006) high=1;
|
||||
if(t==6007) low=high=level==0?0:-30;
|
||||
b.u(t);b.s("BezierSpline "+std::to_string(low)+" "+std::to_string(high)
|
||||
+" 0 { 2 0 1 1 -1 0.1 1 0 1 -1 0.1 }");
|
||||
}
|
||||
if(level==0 && density>=0) {
|
||||
b.u(6010);b.f(0.3f);b.u(6011);b.f(1);b.u(6012);b.f(density);
|
||||
}
|
||||
b.u(1017);
|
||||
}
|
||||
b.u(1015);b.u(1003);b.u(1001);return b;
|
||||
}
|
||||
|
||||
void frondTests() {
|
||||
auto make=[](uint32_t type,bool enabled,float scale) {
|
||||
auto b=authored(17,0.04f);
|
||||
b.u(13000);b.u(13002);b.u(1);b.u(13003);b.u(type);
|
||||
b.u(13004);b.u(3);b.u(13006);b.u(4);b.u(13007);b.data.push_back(enabled);
|
||||
b.u(13005);b.s("BezierSpline 0 0.25 0 { 2 0 0 1 1 0.2 1 1 1 1 0.2 }");
|
||||
b.u(13008);b.u(1);b.u(14000);b.u(14002);b.s("D:/textures/frond.tga");
|
||||
b.u(14003);b.f(0.5f);b.u(14004);b.f(scale);
|
||||
b.u(14005);b.f(0);b.u(14006);b.f(0);b.u(14001);b.u(13001);
|
||||
return b;
|
||||
};
|
||||
for(uint32_t type:{0u,1u}) {
|
||||
auto bytes=make(type,true,1);
|
||||
auto model=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"grass");
|
||||
check(model && !model->GetFrondMeshes().empty(),"fronds not generated");
|
||||
check(!model->IsGrassOrShrub(),"filename heuristic suppressed authored fronds");
|
||||
check(model->GetLeafMesh().vertices.empty(),"frond limbs also generated leaf cards");
|
||||
const auto& mesh=model->GetFrondMeshes()[0];
|
||||
check(!mesh.vertices.empty() && mesh.texture=="frond.dds" && mesh.alpha_test
|
||||
&& mesh.is_double_sided,"frond material lost");
|
||||
check(mesh.vertices.size()==size_t(type==0?8*3*5*2:8*5*7),"frond cross-section topology");
|
||||
WindParameters wind;wind.strength=0;std::vector<float> positions,normals;
|
||||
model->EvaluateCpuTransformedVertices(mesh,positions,normals,0,0,0,0,1,wind);
|
||||
for(size_t i=0;i<mesh.vertices.size();++i) {
|
||||
for(size_t axis=0;axis<3;++axis) {
|
||||
check(close(positions[i*3+axis],mesh.vertices[i].position[axis]),"zero wind changed frond");
|
||||
check(std::isfinite(normals[i*3+axis]),"frond normal not finite");
|
||||
}
|
||||
check(mesh.vertices[i].wind_weights[2]==0,"fronds incorrectly leaf-rocked");
|
||||
}
|
||||
auto disabled=make(type,false,1);
|
||||
auto off=SpeedTreeModel::CreateFromMemory(disabled.data.data(),disabled.data.size());
|
||||
check(off->GetFrondMeshes().empty() && !off->GetLeafMesh().vertices.empty(),"disabled fronds changed tree");
|
||||
auto wider=make(type,true,2);
|
||||
auto big=SpeedTreeModel::CreateFromMemory(wider.data.data(),wider.data.size());
|
||||
auto span=[type](const SpeedTreeMesh& m) {
|
||||
float sum=0;for(int axis=0;axis<3;++axis) {
|
||||
float d=m.vertices[0].position[axis]-m.vertices[type==0?1:6].position[axis];sum+=d*d;
|
||||
}return std::sqrt(sum);
|
||||
};
|
||||
check(close(span(big->GetFrondMeshes()[0]),2*span(mesh)),"frond size scale ignored");
|
||||
}
|
||||
}
|
||||
|
||||
void leafTests() {
|
||||
auto bytes=authored(17,0.04f);bytes.data.resize(bytes.data.size()-4);
|
||||
bytes.u(1004);bytes.u(1009);bytes.u(1006);bytes.u(1);bytes.u(1007);
|
||||
bytes.u(4003);bytes.s("D:/trees/leaf.tga");
|
||||
bytes.u(4004);bytes.f(0.25f);bytes.f(0.75f);bytes.f(0);
|
||||
bytes.u(4005);bytes.f(0.1f);bytes.f(0.2f);bytes.f(0.3f);
|
||||
bytes.u(4006);bytes.f(80);bytes.f(120);bytes.f(0);
|
||||
bytes.u(1008);bytes.u(1010);bytes.u(1005);bytes.u(1001);
|
||||
auto model=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"grass",1000,0);
|
||||
check(model && !model->GetLeafMesh().vertices.empty(),"authored leaves missing");
|
||||
check(model->GetSptInfo().leaves[0].dimensions[0]==80
|
||||
&& model->GetSptInfo().leaves[0].placement[2]==0.3f,"leaf metadata lost");
|
||||
const auto& mesh=model->GetLeafMesh();
|
||||
const auto& vertex=mesh.vertices[0];
|
||||
check(vertex.authored_leaf_card && close(vertex.leaf_pivot_offset[1],30),"leaf pivot not applied");
|
||||
check(mesh.vertices.size()==8*4,"terminal path must emit one card per attachment");
|
||||
check(model->GetTrunkMesh().grids.size()==1 && model->GetGenerationStats().terminal_leaf_calls==8,
|
||||
"terminal leaves incorrectly emitted branch tubes");
|
||||
WindParameters wind;wind.strength=0;std::vector<float> positions,normals;
|
||||
model->EvaluateCpuTransformedVertices(mesh,positions,normals,0,0,0,0,1,wind);
|
||||
for(size_t i=0;i<positions.size();++i) check(close(positions[i],mesh.vertices[i/3].position[i%3]),"zero wind changed authored leaf");
|
||||
std::array<float,3> camera{0,0,4000};
|
||||
model->EvaluateCpuTransformedVertices(mesh,positions,normals,0,0,0,90,2,wind,&camera);
|
||||
for(size_t i=0;i<normals.size()/3;++i)
|
||||
check(close(normals[i*3],0) && close(normals[i*3+1],0) && close(normals[i*3+2],1),"leaf camera heading under instance yaw");
|
||||
wind.strength=0.2f;wind.legacy_leaf_rocking=true;wind.legacy_leaf_phase=1.6f;
|
||||
// Identity matrix isolates local rocking from branch bending.
|
||||
wind.matrices={std::array<float,16>{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}};
|
||||
model->EvaluateCpuTransformedVertices(mesh,positions,normals,0,0,0,0,1,wind);
|
||||
for(size_t i=0;i<4;++i) {
|
||||
const auto& v=mesh.vertices[i];
|
||||
float phase=wind.legacy_leaf_phase*model->GetSptInfo().leaf_rocking_frequency+v.leaf_rocking_phase;
|
||||
float angle=180*model->GetSptInfo().leaf_rocking_range*wind.strength*std::sin(phase);
|
||||
auto expected=OrientLeafOffset({v.leaf_pivot_offset[0],v.leaf_pivot_offset[1],v.leaf_pivot_offset[2]},0,0,angle);
|
||||
for(size_t axis=0;axis<3;++axis) check(close(positions[i*3+axis],v.position[axis]-v.leaf_pivot_offset[axis]+expected[axis]),"legacy grouped leaf rocking");
|
||||
check(v.leaf_rocking_phase==vertex.leaf_rocking_phase,"card corners have different rocking phase");
|
||||
}
|
||||
auto scaled=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"tree",2000,0);
|
||||
check(close(scaled->GetLeafMesh().vertices[0].leaf_pivot_offset[1],60),"property size ignored for leaf dimensions");
|
||||
auto dense=authored(17,0.04f,25000,2);dense.data.resize(dense.data.size()-4);
|
||||
dense.data.insert(dense.data.end(),bytes.data.begin()+authored(17,0.04f).data.size()-4,bytes.data.end());
|
||||
auto full=SpeedTreeModel::CreateFromMemory(dense.data.data(),dense.data.size(),"dense",1000,0);
|
||||
check(full && !full->WasGenerationTruncated() && full->GetLeafMesh().vertices.size()==70000,
|
||||
"terminal cards limited by node/16-bit budget");
|
||||
check(full->GetGenerationStats().nodes_by_level[0]==1 && full->GetGenerationStats().nodes_by_level[1]==0,
|
||||
"terminal cards counted as branch nodes");
|
||||
// Regression for umbrella-thorn: active fronds do not turn terminal leaves
|
||||
// into complete branch/frond nodes, even with more cards than the node guard.
|
||||
dense.u(13000);dense.u(13002);dense.u(0);dense.u(13003);dense.u(0);
|
||||
dense.u(13004);dense.u(1);dense.u(13007);dense.data.push_back(1);dense.u(13001);
|
||||
auto flowering=SpeedTreeModel::CreateFromMemory(dense.data.data(),dense.data.size(),"frondFlowers",1000,0);
|
||||
check(flowering && !flowering->WasGenerationTruncated(),"frond terminal leaves hit branch budget");
|
||||
check(flowering->GetTrunkMesh().vertices.empty() && !flowering->GetFrondMeshes().empty()
|
||||
&& flowering->GetFrondMeshes()[0].vertices.size()==10,"frond terminal path emitted extra fronds");
|
||||
check(flowering->GetLeafMesh().vertices.size()==70000
|
||||
&& flowering->GetGenerationStats().terminal_leaf_calls==17500
|
||||
&& flowering->GetGenerationStats().nodes_by_level[1]==0,"frond lost terminal flowers");
|
||||
}
|
||||
|
||||
void lodTests() {
|
||||
auto bytes=authored(17,0.04f);
|
||||
bytes.u(9000);bytes.u(9005);bytes.u(9007);bytes.u(3);bytes.u(9011);bytes.u(3);bytes.u(9006);
|
||||
bytes.u(9009);bytes.f(0.25f);bytes.u(9001);
|
||||
auto model=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size());
|
||||
check(model && model->GetBranchLodCount()==3 && model->GetLeafLodCount()==3,"independent LOD count");
|
||||
size_t branches=model->GetTrunkMesh().indices.size(),leaves=model->GetLeafMesh().vertices.size();
|
||||
for(uint32_t level=1;level<3;++level) {
|
||||
const auto& trunk=model->GetTrunkMesh(level);const auto& leaf=model->GetLeafMesh(level);
|
||||
check(trunk.indices.size()<branches && leaf.vertices.size()<leaves,"LOD did not reduce geometry");
|
||||
branches=trunk.indices.size();leaves=leaf.vertices.size();
|
||||
for(const auto* mesh:{&trunk,&leaf}) for(uint32_t index:mesh->indices)
|
||||
check(index<mesh->vertices.size(),"LOD index outside mesh");
|
||||
for(const auto& grid:trunk.grids) for(uint32_t row=0;row<grid.rows;++row)
|
||||
for(size_t axis=0;axis<3;++axis) check(close(trunk.vertices[grid.first+row*grid.columns].position[axis],
|
||||
trunk.vertices[grid.first+row*grid.columns+grid.columns-1].position[axis]),"LOD opened branch seam");
|
||||
}
|
||||
auto same=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size());
|
||||
check(model->GetLeafMesh(2).indices==same->GetLeafMesh(2).indices,"LOD selection nondeterministic");
|
||||
auto frond=authored(17,0.04f);frond.u(13000);frond.u(13007);frond.data.push_back(1);
|
||||
frond.u(13003);frond.u(0);frond.u(13009);frond.u(3);frond.u(13001);
|
||||
model=SpeedTreeModel::CreateFromMemory(frond.data.data(),frond.data.size());
|
||||
check(model->GetFrondLodCount()==3 && !model->GetFrondMeshes().empty(),"frond LOD missing");
|
||||
check(model->GetFrondMeshes(2)[0].indices.size()<model->GetFrondMeshes()[0].indices.size(),"frond not reduced");
|
||||
auto distributed=authored(17,0.04f,10,3);
|
||||
model=SpeedTreeModel::CreateFromMemory(distributed.data.data(),distributed.data.size(),"tree",1000,0);
|
||||
check(model->GetTrunkMesh().grids.size()==36,"authored branch density ignored");
|
||||
auto grid=model->GetTrunkMesh().grids[1];float y=0;
|
||||
for(uint32_t column=0;column+1<grid.columns;++column) y+=model->GetTrunkMesh().vertices[grid.first+column].position[1];
|
||||
check(close(y/float(grid.columns-1),700*SampleBranchAttachment(17,0,0.3f,1)),"child seed/attachment interpolation not used");
|
||||
for(uint32_t child=0;child<20;++child) {
|
||||
float t=SampleBranchAttachment(17,child,0.3f,1);
|
||||
check(t>=0.3f && t<=1,"attachment outside authored range");
|
||||
if(child==0) check(t>=0.895f && t<=0.965f,"first attachment upper interval");
|
||||
check(t==SampleBranchAttachment(17,child,0.3f,1),"indexed branch sample unstable");
|
||||
float azimuth=SampleBranchAzimuth(17+3*(child+1));
|
||||
check(azimuth>=-kPI && azimuth<=kPI && azimuth==SampleBranchAzimuth(17+3*(child+1)),"branch azimuth bounds/reproducibility");
|
||||
}
|
||||
}
|
||||
|
||||
void frameAndSpecialLeafTests() {
|
||||
BranchFrame identity;
|
||||
auto axis=identity.Rotate(kPI/2,0,kPI/2).SdkAxis(2);
|
||||
check(close(axis[0],0)&&close(axis[1],0)&&close(axis[2],1),"source frame axes/rotation order");
|
||||
auto parent=identity.Rotate(0,0,kPI/2);
|
||||
auto inherited=parent.Rotate(0,0,kPI/2).SdkAxis(2);
|
||||
check(close(inherited[0],0)&&close(inherited[1],-1),"frame not inherited");
|
||||
auto down=parent.ApplyGravity(1,0).SdkAxis(2);
|
||||
auto up=parent.ApplyGravity(1,1).SdkAxis(2);
|
||||
check(close(down[1],-1)&&close(up[1],1),"gravity rotation direction");
|
||||
check(identity.ApplyGravity(1,0).basis==identity.basis,"vertical gravity singularity");
|
||||
BranchFrame frame;
|
||||
for(int i=0;i<1024;++i) frame=frame.Rotate(0,0.003f,-0.005f);
|
||||
for(size_t i=0;i<3;++i) for(size_t j=0;j<3;++j) {
|
||||
float dot=0;for(size_t k=0;k<3;++k)dot+=frame.basis[i][k]*frame.basis[j][k];
|
||||
check(close(dot,i==j?1:0),"frame lost orthogonality");
|
||||
}
|
||||
auto perturbTree=[](float variance) {
|
||||
auto bytes=authored(17,0.04f,0,2);Stream extra,marker;marker.u(1017);
|
||||
extra.u(6000);extra.s("BezierSpline 0 0 "+std::to_string(variance)+" { 2 0 1 1 0 0.1 1 1 1 0 0.1 }");
|
||||
auto end=std::search(bytes.data.begin(),bytes.data.end(),marker.data.begin(),marker.data.end());
|
||||
check(end!=bytes.data.end(),"perturb fixture missing branch end");
|
||||
bytes.data.insert(end,extra.data.begin(),extra.data.end());
|
||||
return SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"perturb",1000,0);
|
||||
};
|
||||
auto straight=perturbTree(0),bent=perturbTree(20),repeat=perturbTree(20);
|
||||
check(straight && bent && repeat,"frame perturb generator failed");
|
||||
auto endpoint=[](const SpeedTreeMesh& mesh) {
|
||||
const auto grid=mesh.grids.front();std::array<float,3> center{};
|
||||
for(uint32_t c=0;c+1<grid.columns;++c) for(size_t axis=0;axis<3;++axis)
|
||||
center[axis]+=mesh.vertices[grid.first+(grid.rows-1)*grid.columns+c].position[axis]/float(grid.columns-1);
|
||||
return std::sqrt(center[0]*center[0]+center[1]*center[1]+center[2]*center[2]);
|
||||
};
|
||||
check(close(endpoint(straight->GetTrunkMesh()),700),"zero perturb changed centerline length");
|
||||
check(endpoint(bent->GetTrunkMesh())<699,"perturb sampled but not applied to geometry");
|
||||
for(size_t i=0;i<bent->GetTrunkMesh().vertices.size();++i) for(size_t axis=0;axis<3;++axis)
|
||||
check(bent->GetTrunkMesh().vertices[i].position[axis]==repeat->GetTrunkMesh().vertices[i].position[axis],"frame perturb not deterministic");
|
||||
auto powered=authored(17,0.04f,10,3);
|
||||
powered.u(16000);
|
||||
for(int level=0;level<3;++level) {
|
||||
powered.u(16002);powered.f(2);powered.u(16003);powered.u(0);
|
||||
for(uint32_t t=16004;t<=16012;++t){powered.u(t);powered.f(0);}
|
||||
}
|
||||
powered.u(16001);
|
||||
auto curvedSpacing=SpeedTreeModel::CreateFromMemory(powered.data.data(),powered.data.size(),"spacing",1000,0);
|
||||
check(curvedSpacing && curvedSpacing->GetSptInfo().branch_levels[0].length_exponent==2,"axial exponent skipped");
|
||||
const auto& spacing=curvedSpacing->GetTrunkMesh();const auto rootGrid=spacing.grids[0];
|
||||
float firstY=0;for(uint32_t c=0;c+1<rootGrid.columns;++c)firstY+=spacing.vertices[rootGrid.first+rootGrid.columns+c].position[1]/float(rootGrid.columns-1);
|
||||
check(close(firstY,700.0f/16),"axial exponent not applied");
|
||||
const auto childGrid=spacing.grids[1];float childY=0;
|
||||
for(uint32_t c=0;c+1<childGrid.columns;++c)childY+=spacing.vertices[childGrid.first+c].position[1]/float(childGrid.columns-1);
|
||||
check(close(childY,700*SampleBranchAttachment(17,0,0.3f,1)),"attachment used uniform ring indices");
|
||||
Stream exponentMarker;exponentMarker.u(16002);
|
||||
auto zeroExponent=powered;
|
||||
auto where=std::search(zeroExponent.data.begin(),zeroExponent.data.end(),exponentMarker.data.begin(),exponentMarker.data.end());
|
||||
check(where!=zeroExponent.data.end(),"zero exponent fixture missing");
|
||||
std::fill(where+4,where+8,0);
|
||||
auto collapsed=SpeedTreeModel::CreateFromMemory(zeroExponent.data.data(),zeroExponent.data.size(),"zeroExponent",1000,0);
|
||||
check(collapsed && !collapsed->WasGenerationTruncated(),"valid zero exponent rejected");
|
||||
const auto& collapsedMesh=collapsed->GetTrunkMesh();
|
||||
float collapsedY=0;for(uint32_t c=0;c+1<rootGrid.columns;++c)collapsedY+=collapsedMesh.vertices[rootGrid.columns+c].position[1]/float(rootGrid.columns-1);
|
||||
check(close(collapsedY,700),"zero exponent not evaluated as original pow");
|
||||
SpecialLeafSettings settings;settings.ancestor_depth=0;
|
||||
LegacyRandom threshold(20),untouched(20);
|
||||
check(!SampleSpecialLeaf(0.75f,{},settings,threshold),"special threshold equality accepted");
|
||||
check(threshold.Uniform()==untouched.Uniform(),"failed threshold consumed random draw");
|
||||
settings.minimum_position=0.5f;settings.probability=1;
|
||||
LegacyRandom sampled(20),expected(20);expected.Uniform();
|
||||
check(SampleSpecialLeaf(0.6f,{},settings,sampled),"special gate failed");
|
||||
check(sampled.Uniform()==expected.Uniform(),"special probability draw count");
|
||||
settings.ancestor_depth=2;
|
||||
LegacyRandom ancestors(20);
|
||||
check(!SampleSpecialLeaf(1,{0.8f,0.2f,0.9f},settings,ancestors),"wrong ancestor selected");
|
||||
settings.ancestor_depth=999;settings.minimum_position=0.85f;
|
||||
check(SampleSpecialLeaf(0,{0.1f,0.9f},settings,ancestors),"ancestor traversal did not stop at root");
|
||||
|
||||
auto make=[](float minimum,uint32_t depth,float probability) {
|
||||
auto bytes=authored(17,0.04f);bytes.data.resize(bytes.data.size()-4);
|
||||
bytes.u(1004);bytes.u(3000);bytes.f(minimum);bytes.u(3001);bytes.u(depth);bytes.u(3002);bytes.f(probability);
|
||||
bytes.u(1009);bytes.u(1006);bytes.u(2);
|
||||
for(uint32_t i=0;i<2;++i) {
|
||||
bytes.u(1007);bytes.u(4000);bytes.data.push_back(i==1);
|
||||
bytes.u(4001);bytes.f(i==0?1:0);bytes.f(i==1?1:0);bytes.f(0);
|
||||
bytes.u(4002);bytes.f(0);bytes.u(4004);bytes.f(0.5f);bytes.f(1);bytes.f(0);
|
||||
bytes.u(4006);bytes.f(i?200:80);bytes.f(i?300:120);bytes.f(0);bytes.u(1008);
|
||||
}
|
||||
bytes.u(1010);bytes.u(1005);bytes.u(1001);return bytes;
|
||||
};
|
||||
for(auto args:{std::array<float,3>{-1,0,1},std::array<float,3>{1,0,1},std::array<float,3>{0.1f,1,1}}) {
|
||||
auto bytes=make(args[0],uint32_t(args[1]),args[2]);
|
||||
auto model=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"special",1000,0);
|
||||
bool special=args[0]<0;
|
||||
check(model && model->GetLeafMesh().vertices.size()==32,"special leaf pool generated wrong count");
|
||||
check(model->GetGenerationStats().special_leaf_cards==(special?8:0),"special card statistics");
|
||||
check(model->GetSptInfo().special_leaves.ancestor_depth==uint32_t(args[1])
|
||||
&& model->GetSptInfo().special_leaves.minimum_position==args[0],"special metadata skipped");
|
||||
for(const auto& v:model->GetLeafMesh().vertices)check(v.diffuse==(special?0xff00ff00:0xff0000ff),"wrong special variant/color selected");
|
||||
}
|
||||
}
|
||||
|
||||
void generationRecoveryTests() {
|
||||
// Independent integer/shuffle oracle for the recovered entry draw sequence.
|
||||
// Constant curves still consume variance draws, even when variance is zero.
|
||||
BranchLevel level;
|
||||
for(size_t i:{1u,2u,4u,5u,7u}) {
|
||||
check(BranchSpline::Parse("BezierSpline 0.2 0.2 0.1 { 2 0 1 1 0 0.1 1 1 1 0 0.1 }",level.curves[i]),"entry fixture");
|
||||
}
|
||||
uint32_t state=20;std::array<float,128> table{};
|
||||
auto next=[&]() {state=uint32_t(uint64_t(state)*16807%2147483647);return double(state)/2147483648.0;};
|
||||
for(auto& x:table)x=float(next());
|
||||
auto draw=[&](float low,float high) {size_t index=size_t(next()*128);float x=table[index];table[index]=float(next());return low+(high-low)*x;};
|
||||
LegacyRandom random(20);random.Uniform(0,100);draw(0,100);
|
||||
auto sample=SampleBranchEntry(level,0.4f,1000,random);
|
||||
check(close(sample.length,(0.2f+draw(-0.1f,0.1f))*1000),"entry length draw order");
|
||||
check(close(sample.azimuth,draw(-180,180)*kPI/180),"entry azimuth draw order");
|
||||
check(close(sample.angle,(0.2f+draw(-0.1f,0.1f))*kPI/180),"entry angle draw order");
|
||||
check(close(sample.gravity,0.2f+draw(-0.1f,0.1f)),"entry gravity draw order");
|
||||
check(close(sample.radius,(0.2f+draw(-0.1f,0.1f))*1000),"entry radius draw order");
|
||||
check(close(sample.flexibility,0.2f+draw(-0.1f,0.1f)),"entry flexibility draw order");
|
||||
check(random.Uniform()==draw(0,1),"entry trailing stream differs");
|
||||
auto missing=level;missing.curves[4]={};
|
||||
LegacyRandom noLength(20),expected(20);expected.Uniform(-180,180);
|
||||
SampleBranchEntry(missing,0.4f,1000,noLength);
|
||||
for(int i=0;i<4;++i)expected.Uniform();
|
||||
check(noLength.Uniform()==expected.Uniform(),"absent curve consumed a draw");
|
||||
BranchSpline perturb;
|
||||
check(BranchSpline::Parse("BezierSpline 100 200 3 { 2 0 0 1 1 0.2 1 1 1 1 0.2 }",perturb),"perturb fixture");
|
||||
LegacyRandom perturbRandom(8),perturbExpected(8);
|
||||
check(close(perturb.EvaluatePerturbation(0.5f,perturbRandom),perturbExpected.Uniform(-perturb.samples[250]*3,perturb.samples[250]*3)),"perturb uses min/max or interpolation");
|
||||
|
||||
auto bytes=authored(17,0.04f,4000,2);
|
||||
auto large=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"large",1000,0);
|
||||
check(large && !large->WasGenerationTruncated(),"ordinary high density clipped");
|
||||
check(large->GetTrunkMesh().vertices.size()>65535,"32 bit trunk still clipped");
|
||||
check(large->GetTrunkMesh().grids.size()==2801,"density or node count still capped at 128/256");
|
||||
for(uint32_t index:large->GetTrunkMesh().indices)check(index<large->GetTrunkMesh().vertices.size(),"large index out of range");
|
||||
const auto& stats=large->GetGenerationStats();
|
||||
check(stats.nodes_by_level[0]==1 && stats.nodes_by_level[1]==2800,"branch hierarchy stats wrong");
|
||||
auto again=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"large",1000,0);
|
||||
check(large->GetTrunkMesh().indices==again->GetTrunkMesh().indices,"large tree scheduling unstable");
|
||||
for(size_t i=0;i<large->GetTrunkMesh().vertices.size();++i)
|
||||
for(int axis=0;axis<3;++axis) check(large->GetTrunkMesh().vertices[i].position[axis]==again->GetTrunkMesh().vertices[i].position[axis],"large tree positions unstable");
|
||||
auto zero=authored(17,0.04f,0,2);
|
||||
std::string constant="0.700000",replacement="0.000000";
|
||||
auto where=std::search(zero.data.begin(),zero.data.end(),constant.begin(),constant.end());
|
||||
check(where!=zero.data.end(),"zero fixture length missing");
|
||||
while(where!=zero.data.end()) {
|
||||
std::copy(replacement.begin(),replacement.end(),where);
|
||||
where=std::search(zero.data.begin(),zero.data.end(),constant.begin(),constant.end());
|
||||
}
|
||||
zero.u(13000);zero.u(13002);zero.u(0);zero.u(13003);zero.u(0);
|
||||
zero.u(13007);zero.data.push_back(1);zero.u(13001);
|
||||
auto empty=SpeedTreeModel::CreateFromMemory(zero.data.data(),zero.data.size(),"empty",1000,0);
|
||||
check(empty && empty->GetTrunkMesh().vertices.empty(),"empty frond emitted geometry");
|
||||
for(float x:empty->GetBoundsMin())check(std::isfinite(x),"empty model bounds infinite");
|
||||
for(float x:empty->GetBoundsMax())check(std::isfinite(x),"empty model bounds infinite");
|
||||
auto hostile=authored(17,0.04f,1e8f,2);
|
||||
auto bounded=SpeedTreeModel::CreateFromMemory(hostile.data.data(),hostile.data.size(),"bounded",1000,0);
|
||||
check(bounded && bounded->WasGenerationTruncated() && bounded->GetGenerationStats().node_limit
|
||||
&& bounded->GetGenerationStats().density_limit,"allocation guard not reported");
|
||||
size_t nodes=0;for(auto n:bounded->GetGenerationStats().nodes_by_level)nodes+=n;
|
||||
check(nodes==GenerationStats::max_nodes,"node allocation guard exceeded");
|
||||
}
|
||||
|
||||
void tests() {
|
||||
BranchSpline spline;
|
||||
check(BranchSpline::Parse("BezierSpline 2 6 0 { 2 0 0 1 1 0.2 1 1 1 1 0.2 }",spline),"spline rejected");
|
||||
check(close(spline.Evaluate(0),2)&&close(spline.Evaluate(0.5f),3.996f)&&close(spline.Evaluate(1),6),"Bezier evaluation");
|
||||
check(!BranchSpline::Parse("BezierSpline 0 1 0 { 4294967295 }",spline),"unbounded curve count");
|
||||
check(BranchSpline::Parse("BezierSpline 1 1 -0.1 { 2 0 1 1 0 0.1 1 1 1 0 0.1 }",spline),"signed authored variance rejected");
|
||||
LegacyRandom random(1),again(1),different(2);
|
||||
bool differs=false;
|
||||
for(int i=0;i<100;++i) { float v=random.Uniform();check(v>=0&&v<1&&v==again.Uniform(),"seed reproducibility");differs|=v!=different.Uniform(); }
|
||||
check(differs,"seeds ignored");
|
||||
auto bytes=authored(17,0.04f),other=authored(18,0.04f),thick=authored(17,0.08f);
|
||||
auto a=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"pine");
|
||||
auto b=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"beech");
|
||||
auto variant=SpeedTreeModel::CreateFromMemory(other.data.data(),other.data.size());
|
||||
auto bigger=SpeedTreeModel::CreateFromMemory(thick.data.data(),thick.data.size());
|
||||
check(a&&b&&variant&&bigger,"authored generator failed");
|
||||
const auto& mesh=a->GetTrunkMesh();
|
||||
check(mesh.vertices.size()>100&&mesh.indices.size()>500,"limbs not generated");
|
||||
check(mesh.vertices.size()==b->GetTrunkMesh().vertices.size(),"name changed authored topology");
|
||||
for(size_t i=0;i<mesh.vertices.size();++i) for(int j=0;j<3;++j)
|
||||
check(mesh.vertices[i].position[j]==b->GetTrunkMesh().vertices[i].position[j],"name changed authored shape");
|
||||
check(a->GetHeight()!=variant->GetHeight(),"seed/size variance ignored");
|
||||
auto exact=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"tree",1200,0);
|
||||
auto varied=SpeedTreeModel::CreateFromMemory(bytes.data.data(),bytes.data.size(),"tree",1200,50);
|
||||
check(exact->GetHeight()==1200 && varied->GetHeight()!=1200,"property size/variance ignored");
|
||||
check(std::hypot(mesh.vertices[0].position[0],mesh.vertices[0].position[2])<std::hypot(bigger->GetTrunkMesh().vertices[0].position[0],bigger->GetTrunkMesh().vertices[0].position[2]),"radius curve ignored");
|
||||
|
||||
WindParameters wind;wind.strength=0;wind.time=1.3f;
|
||||
std::vector<float> p,n;
|
||||
a->EvaluateCpuTransformedVertices(a->GetLeafMesh(),p,n,0,0,0,0,1,wind);
|
||||
for(size_t i=0;i<p.size();++i) check(close(p[i],a->GetLeafMesh().vertices[i/3].position[i%3]),"zero wind moved foliage");
|
||||
// Full matrix weight and inverse-transpose normal against a known affine map.
|
||||
SpeedTreeMesh sample;sample.vertices.resize(1);sample.vertices[0].position[0]=2;
|
||||
sample.vertices[0].position[1]=3;sample.vertices[0].position[2]=4;
|
||||
sample.vertices[0].normal[0]=1;sample.vertices[0].wind_weights[0]=0.5f;
|
||||
std::array<float,16> matrix{2,0,0,0, 0,1,0,0, 0,0,1,0, 10,0,0,1};
|
||||
wind.matrices={matrix};
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,0,0,0,0,1,wind);
|
||||
check(close(p[0],8)&&close(p[1],3)&&close(p[2],4)&&close(n[0],1),"weighted matrix transform");
|
||||
sample.vertices[0].normal[1]=1;
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,0,0,0,0,1,wind);
|
||||
check(close(1.5f*n[0]-n[1],0),"normal not perpendicular to transformed tangent");
|
||||
sample.vertices[0].wind_weights[0]=0;
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,0,0,0,0,1,wind);
|
||||
check(close(p[0],2),"zero-weight anchor moved");
|
||||
|
||||
wind.matrices.clear();wind.strength=1;wind.time=0.7f;
|
||||
sample.vertices[0].wind_weights[0]=1;
|
||||
sample.vertices[0].position[0]=0;sample.vertices[0].position[2]=0;
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,0,0,0,0,1,wind);
|
||||
auto upright=p;
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,0,0,0,90,1,wind);
|
||||
for(int i=0;i<3;++i)check(close(p[i],upright[i]),"instance yaw rotated world wind direction");
|
||||
sample.vertices[0].position[0]=2;sample.vertices[0].position[2]=4;
|
||||
sample.vertices[0].wind_weights[0]=0;
|
||||
|
||||
// A complete leaf card uses a rigid local rock followed by one shared matrix weight.
|
||||
wind.matrices.clear();wind.strength=1;wind.gust_strength=0;
|
||||
const auto& leaves=a->GetLeafMesh();
|
||||
a->EvaluateCpuTransformedVertices(leaves,p,n,0,0,0,0,1,wind);
|
||||
auto distance=[&](const float* x,const float* y) { return std::hypot(std::hypot(x[0]-y[0],x[1]-y[1]),x[2]-y[2]); };
|
||||
// Blending identity and a rotation induces bounded contraction; card edges
|
||||
// still share one affine transform, so opposite edges remain equal.
|
||||
check(close(distance(p.data(),p.data()+3),distance(p.data()+9,p.data()+6)),"card corners use different rocking angles");
|
||||
for(size_t i=0;i<n.size();i+=3) check(close(distance(n.data()+i,std::array<float,3>{}.data()),1),"deformed normal not normalized");
|
||||
wind.strength=0;wind.matrices.clear();
|
||||
a->EvaluateCpuTransformedVertices(sample,p,n,10,20,30,90,2,wind);
|
||||
check(close(p[0],18)&&close(p[1],26)&&close(p[2],26),"instance scale/yaw/translation order");
|
||||
}
|
||||
|
||||
int main(int argc,char** argv) {
|
||||
try {
|
||||
tests();
|
||||
frameAndSpecialLeafTests();
|
||||
generationRecoveryTests();
|
||||
frondTests();
|
||||
leafTests();
|
||||
lodTests();
|
||||
if(argc==3&&std::string(argv[1])=="--shaders") {
|
||||
std::filesystem::create_directories(argv[2]);
|
||||
std::ofstream(std::filesystem::path(argv[2])/"foliage.vert")<<GetFoliageVertexShaderGLSL();
|
||||
std::ofstream(std::filesystem::path(argv[2])/"foliage.frag")<<GetFoliageFragmentShaderGLSL();
|
||||
} else if(argc==2) {
|
||||
size_t count=0,billboards=0,fronds=0,authoredLeaves=0,truncated=0;
|
||||
for(const auto& file:std::filesystem::recursive_directory_iterator(argv[1])) {
|
||||
if(file.path().extension()!=".spt")continue;
|
||||
auto model=SpeedTreeModel::CreateFromSpt(file.path().string());check(bool(model),"corpus model rejected");++count;
|
||||
if(model->WasGenerationTruncated()) ++truncated;
|
||||
if(!model->GetLeafMesh().vertices.empty() && model->GetLeafMesh().vertices[0].authored_leaf_card) ++authoredLeaves;
|
||||
auto quads=model->BuildBillboardMeshes({1000,2000,4000});
|
||||
if(!quads.empty()) ++billboards;
|
||||
for(const auto& quad:quads) {
|
||||
check(quad.vertices.size()==4 && quad.indices.size()==6,"invalid corpus billboard topology");
|
||||
for(const auto& vertex:quad.vertices) {
|
||||
for(float value:vertex.position) check(std::isfinite(value),"non-finite billboard position");
|
||||
for(float value:vertex.uv) check(std::isfinite(value),"non-finite billboard UV");
|
||||
}
|
||||
}
|
||||
std::vector<const SpeedTreeMesh*> meshes{&model->GetTrunkMesh(),&model->GetLeafMesh()};
|
||||
bool hasFronds=false;
|
||||
for(const auto& mesh:model->GetFrondMeshes()) {
|
||||
meshes.push_back(&mesh);hasFronds|=!mesh.vertices.empty();
|
||||
}
|
||||
if(hasFronds) ++fronds;
|
||||
for(uint32_t level=1;level<model->GetBranchLodCount();++level) meshes.push_back(&model->GetTrunkMesh(level));
|
||||
for(uint32_t level=1;level<model->GetLeafLodCount();++level) meshes.push_back(&model->GetLeafMesh(level));
|
||||
for(uint32_t level=1;level<model->GetFrondLodCount();++level)
|
||||
for(const auto& mesh:model->GetFrondMeshes(level)) meshes.push_back(&mesh);
|
||||
for(const auto* mesh:meshes) {
|
||||
check(mesh->vertices.size()<=GenerationStats::max_vertices,"mesh budget exceeded");
|
||||
for(const auto& v:mesh->vertices) for(int j=0;j<3;++j)
|
||||
check(std::isfinite(v.position[j])&&std::isfinite(v.normal[j]),"non-finite corpus geometry");
|
||||
for(uint32_t index:mesh->indices)check(index<mesh->vertices.size(),"mesh index out of range");
|
||||
WindParameters wind;wind.time=2.5f;std::vector<float> p,n;
|
||||
model->EvaluateCpuTransformedVertices(*mesh,p,n,0,0,0,45,1,wind);
|
||||
for(float value:p)check(std::isfinite(value),"non-finite wind deformation");
|
||||
LegacyWindController controller;controller.Update(2.5f,0.2f);
|
||||
wind.strength=0.2f;wind.matrices=controller.GetMatrices();
|
||||
wind.legacy_leaf_rocking=true;wind.legacy_leaf_phase=controller.GetLeafPhase();
|
||||
std::array<float,3> camera{3000,2000,4000};
|
||||
model->EvaluateCpuTransformedVertices(*mesh,p,n,100,200,300,45,2,wind,&camera);
|
||||
for(float value:p)check(std::isfinite(value),"non-finite native wind/camera deformation");
|
||||
for(float value:n)check(std::isfinite(value),"non-finite native wind/camera normal");
|
||||
}
|
||||
}
|
||||
check(count>0,"empty corpus");std::cout<<"Generated and deformed "<<count<<" SPT models; "<<billboards<<" have billboard meshes; "<<fronds<<" have frond meshes; "<<authoredLeaves<<" use authored leaf cards; "<<truncated<<" report generation budget truncation\n";
|
||||
}
|
||||
std::cout<<"Branch and wind regressions passed\n";
|
||||
}catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <cmath>
|
||||
#include <bit>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace speedtree;
|
||||
void require(bool value,const char* message) { if(!value) throw std::runtime_error(message); }
|
||||
bool near(float a,float b,float eps=0.0001f) { return std::abs(a-b)<eps; }
|
||||
|
||||
int main() {
|
||||
try {
|
||||
BranchSpline curve;
|
||||
require(BranchSpline::Parse("BezierSpline 0 1 0 { 2 0 0 1 1 0.2 1 1 1 1 0.2 }",curve),"curve parse");
|
||||
require(curve.samples_ready && near(curve.samples[250],0.5f),"500-table resampling");
|
||||
require(near(curve.Evaluate(0.5f),0.499f),"legacy 500/499 lookup behavior");
|
||||
require(near(curve.Evaluate(0),0) && near(curve.Evaluate(1),1),"curve endpoint handling");
|
||||
LeafDefinition leaf;leaf.dimensions={8,12,0};leaf.pivot={0.25f,0.75f,0};
|
||||
auto corners=BuildLeafCorners(leaf,false),mirrored=BuildLeafCorners(leaf,true);
|
||||
require(near(corners[0][2],2) && near(corners[1][2],-6)
|
||||
&& near(corners[0][1],3) && near(corners[2][1],-9),"authored leaf dimensions/pivot");
|
||||
require(near(mirrored[0][2],6) && near(mirrored[1][2],-2),"mirrored leaf pivot");
|
||||
auto offset=OrientLeafOffset({0,2,3},90,0,0);
|
||||
require(near(offset[0],-3) && near(offset[1],2) && near(offset[2],0),"leaf camera azimuth");
|
||||
offset=OrientLeafOffset({0,2,3},0,90,0);
|
||||
require(near(offset[0],2) && near(offset[1],0) && near(offset[2],3),"leaf camera pitch");
|
||||
offset=OrientLeafOffset({0,2,3},0,0,90);
|
||||
require(near(offset[0],0) && near(offset[1],3) && near(offset[2],-2),"leaf local rocking axis");
|
||||
// Values from an independent integer Park-Miller/shuffle reference,
|
||||
// with the DLL's float table storage and indexed child reseeding.
|
||||
require(near(SampleBranchAttachment(17,0,0.3f,1),std::bit_cast<float>(0x3f6c5c7fu),0.000001f)
|
||||
&& near(SampleBranchAttachment(17,1,0.3f,1),std::bit_cast<float>(0x3f38b5d0u),0.000001f)
|
||||
&& near(SampleBranchAttachment(17,2,0.3f,1),std::bit_cast<float>(0x3eb03402u),0.000001f),"indexed random reference values");
|
||||
LegacyWindController controller;
|
||||
controller.Update(0,0.2f);
|
||||
require(controller.GetMatrices().size()==4,"missing wind groups");
|
||||
auto matrix=controller.GetMatrices()[0];
|
||||
float angle=7.0f/57.2957795f;
|
||||
require(near(matrix[0],std::cos(angle)) && near(matrix[4],std::sin(angle)),"original time-zero compound rotation");
|
||||
controller.Update(1,0.2f);
|
||||
float oldPhase=controller.GetLeafPhase();
|
||||
float oldX=std::asin(-controller.GetMatrices()[0][6]);
|
||||
controller.Update(1,0.4f);
|
||||
require(near(oldPhase,controller.GetLeafPhase()),"leaf phase jumped on strength change");
|
||||
require(near(std::asin(-controller.GetMatrices()[0][6]),2*oldX),"matrix phase jumped on strength change");
|
||||
for(const auto& m:controller.GetMatrices()) {
|
||||
for(int column=0;column<3;++column) {
|
||||
float length=0;for(int row=0;row<3;++row) length+=m[column*4+row]*m[column*4+row];
|
||||
require(near(length,1),"non-orthogonal wind matrix");
|
||||
}
|
||||
}
|
||||
LegacyWindController independent;independent.Update(1,0.2f);
|
||||
controller.Update(2,0);
|
||||
for(const auto& m:controller.GetMatrices()) for(int c=0;c<4;++c) for(int r=0;r<4;++r)
|
||||
require(near(m[c*4+r],c==r?1.0f:0.0f),"zero-strength controller not identity");
|
||||
require(near(independent.GetLeafPhase(),1.6f),"controller phase shared globally");
|
||||
require(SelectDiscreteLod(1,4)==0 && SelectDiscreteLod(0.5f,4)==2
|
||||
&& SelectDiscreteLod(0,4)==3 && SelectDiscreteLod(0,0)==-1,"original discrete LOD boundaries");
|
||||
auto transition=SelectLodTransition(0.5f,2,0.1f,0.5f,2,84);
|
||||
require(transition.first==0 && transition.second==1 && near(transition.first_alpha,84)
|
||||
&& near(transition.second_alpha,84),"LOD transition center");
|
||||
transition=SelectLodTransition(0.59f,2,0.1f,0.5f,2,84);
|
||||
require(transition.first==0 && transition.second==1 && near(transition.first_alpha,84)
|
||||
&& near(transition.second_alpha,222.51f,0.01f),"LOD threshold exponent");
|
||||
transition=SelectLodTransition(0,2,0.1f,0.5f,2);
|
||||
require(transition.first==1 && transition.second==-1,"LOD last-level clamp");
|
||||
require(SelectLodTransition(0.5f,0,0.1f,0.5f,2).first==-1,"empty LOD set");
|
||||
SpeedTreeSptInfo atlas;atlas.billboard_360=true;atlas.billboard_uv_quads.resize(8);
|
||||
for(int angle=-720;angle<=720;++angle) {
|
||||
auto views=SelectBillboardViews(atlas,float(angle),150);
|
||||
require(!views.empty() && views.size()<=2,"360 billboard view count");
|
||||
for(const auto& view:views) require(view.texture_index>=0 && view.texture_index<8
|
||||
&& view.alpha_ref>=150 && view.alpha_ref<255,"360 billboard texture/alpha range");
|
||||
}
|
||||
auto a=SelectBillboardViews(atlas,0,84),b=SelectBillboardViews(atlas,360,84);
|
||||
require(a.size()==b.size() && a[0].texture_index==b[0].texture_index
|
||||
&& near(a[0].alpha_ref,b[0].alpha_ref),"billboard wrap discontinuity");
|
||||
require(SelectBillboardViews(atlas,45,255).empty(),"invisible atlas views retained");
|
||||
atlas.billboard_360=false;
|
||||
require(SelectBillboardViews(atlas,90,120)[0].texture_index==0,"simple billboard atlas index");
|
||||
SpeedTreeForest forest;forest.Update(0.25f);
|
||||
require(forest.GetWindParams().matrices.size()==4 && forest.GetWindParams().legacy_leaf_rocking,
|
||||
"native controller not integrated into forest");
|
||||
std::cout<<"Legacy LUT, wind phase and LOD regressions passed\n";
|
||||
}catch(const std::exception& e) { std::cerr<<e.what()<<'\n';return 1; }
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
|
||||
void TestProceduralTree() {
|
||||
std::cout << "[Test] Procedural Tree Generation..." << std::endl;
|
||||
@@ -63,20 +64,29 @@ void TestSptTokenSniffing() {
|
||||
buffer.insert(buffer.end(), b, b + 4);
|
||||
};
|
||||
|
||||
push_i32(1000);
|
||||
std::string signature = "__IdvSpt_02_";
|
||||
push_i32(static_cast<int32_t>(signature.size()));
|
||||
buffer.insert(buffer.end(), signature.begin(), signature.end());
|
||||
push_i32(1002);
|
||||
|
||||
// Token 2000: bark name "custom_bark.dds"
|
||||
std::string bark_str = "custom_bark.dds";
|
||||
push_i32(2000);
|
||||
push_i32(static_cast<int32_t>(bark_str.size()));
|
||||
buffer.insert(buffer.end(), bark_str.begin(), bark_str.end());
|
||||
|
||||
// Token 2001: size 850.0f
|
||||
push_i32(2001);
|
||||
// Token 2006: size 850.0f
|
||||
push_i32(2006);
|
||||
push_f32(850.0f);
|
||||
|
||||
// Token 2002: variance 50.0f
|
||||
push_i32(2002);
|
||||
// Token 2007: variance 50.0f
|
||||
push_i32(2007);
|
||||
push_f32(50.0f);
|
||||
|
||||
push_i32(1003);
|
||||
push_i32(1001);
|
||||
|
||||
speedtree::SpeedTreeSptInfo info;
|
||||
bool ok = speedtree::SpeedTreeSptInfo::SniffMemory(buffer.data(), buffer.size(), info);
|
||||
assert(ok);
|
||||
@@ -92,8 +102,8 @@ void TestForestManagement() {
|
||||
speedtree::SpeedTreeForest forest;
|
||||
assert(forest.GetInstanceCount() == 0);
|
||||
|
||||
forest.RegisterPropertyData(speedtree::SpeedTreeProperty{1, "Pine", "pine.spt", 1000.0f, 0.0f});
|
||||
assert(forest.HasMainTree(1));
|
||||
assert(!forest.RegisterPropertyData(speedtree::SpeedTreeProperty{1, "Pine", "missing_test_pine.spt", 1000.0f, 0.0f}));
|
||||
assert(!forest.HasMainTree(1));
|
||||
|
||||
auto* inst1 = forest.CreateInstance(100.0f, 0.0f, 200.0f, 1, 45.0f, 1.2f, "ForestPine1");
|
||||
auto* inst2 = forest.CreateInstance(300.0f, 0.0f, 400.0f, 1, 90.0f, 0.9f, "ForestPine2");
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace speedtree;
|
||||
|
||||
void require(bool value, const char* message) { if (!value) throw std::runtime_error(message); }
|
||||
struct Buffer {
|
||||
std::vector<uint8_t> bytes;
|
||||
void i(uint32_t v) { for (int n = 0; n < 4; ++n) bytes.push_back(uint8_t(v >> (n * 8))); }
|
||||
void f(float v) { i(std::bit_cast<uint32_t>(v)); }
|
||||
void s(const std::string& v) { i(uint32_t(v.size())); bytes.insert(bytes.end(), v.begin(), v.end()); }
|
||||
void field(uint32_t t, float v) { i(t); f(v); }
|
||||
};
|
||||
|
||||
Buffer tree() {
|
||||
Buffer b;
|
||||
b.i(1000); b.s("__IdvSpt_02_"); b.i(1002);
|
||||
b.i(2000); b.s("D:\\Trees\\custom_bark.TGA");
|
||||
b.field(2001, 3000); b.i(2002); b.bytes.push_back(0);
|
||||
b.field(2003, 1000); b.i(2005); b.i(42);
|
||||
b.field(2006, 850); b.field(2007, 50);
|
||||
b.i(1003); b.i(1001);
|
||||
return b;
|
||||
}
|
||||
|
||||
void formatTests() {
|
||||
auto b = tree();
|
||||
SpeedTreeSptInfo out;
|
||||
require(SpeedTreeSptInfo::SniffMemory(b.bytes.data(), b.bytes.size(), out), "valid header rejected");
|
||||
require(out.metadata_complete && out.parsed_bytes == b.bytes.size(), "header not fully consumed");
|
||||
require(out.size == 850 && out.variance == 50 && out.seed == 42, "wrong size/seed tokens");
|
||||
require(out.lod_near == 1000 && out.lod_far == 3000, "LOD mistaken for tree size");
|
||||
require(out.bark_texture == "custom_bark.dds", "texture path conversion failed");
|
||||
require(out.EvaluateLod(0) == 1 && out.EvaluateLod(2000) == 0.5f && out.EvaluateLod(4000) == 0,
|
||||
"LOD response failed");
|
||||
require(SpeedTreeModel::CreateFromMemory(b.bytes.data(), b.bytes.size())->GetHeight() == 850,
|
||||
"authored height ignored");
|
||||
require(SpeedTreeModel::CreateFromMemory(b.bytes.data(), b.bytes.size(), "tree", 1200)->GetHeight() == 1200,
|
||||
"property size override ignored");
|
||||
require(!SpeedTreeModel::CreateFromMemory(nullptr, 10), "invalid SPT became a procedural model");
|
||||
|
||||
auto legacy = tree(); legacy.bytes.resize(legacy.bytes.size()-4);
|
||||
legacy.i(1011);legacy.i(5004);legacy.f(0.04f);legacy.f(0.2f);legacy.f(0);
|
||||
legacy.i(5006);legacy.bytes.push_back(0);legacy.i(1012);legacy.i(1001);
|
||||
legacy.i(9000);legacy.i(9002);legacy.i(1);
|
||||
legacy.field(9003,0.1f);legacy.field(9004,2);
|
||||
legacy.i(9005);legacy.i(9007);legacy.i(3);legacy.i(9011);legacy.i(4);
|
||||
legacy.i(9006);legacy.i(9001);legacy.field(16014,0.3f);
|
||||
require(SpeedTreeSptInfo::SniffMemory(legacy.bytes.data(),legacy.bytes.size(),out),"legacy wind/LOD parse");
|
||||
require(out.leaf_rocking_range==0.04f && out.leaf_rocking_frequency==0.2f
|
||||
&& out.leaf_rocking_enabled,"rocking fields/deprecated flag semantics");
|
||||
require(out.branch_lod_levels==3 && out.leaf_lod_levels==4 && out.lod_transition_width==0.1f
|
||||
&& out.lod_alpha_exponent==2 && out.lod_transition_overlap==0.3f,"LOD settings discarded");
|
||||
|
||||
// A zero-count group must not prevent later groups from being parsed. Group
|
||||
// 10003 is billboard geometry; 10004 is frond geometry (original storage offsets).
|
||||
UVQuad uv{0.1f,0.2f, 0.8f,0.1f, 0.9f,0.7f, 0.2f,0.8f};
|
||||
b.i(10000); b.i(10004); b.i(1); for (float v : uv) b.f(v);
|
||||
b.i(10003); b.i(0); b.i(10002); b.i(1); for (float v : uv) b.f(v);
|
||||
b.i(10005); b.s("D:/tree/CompositeMap_custom.tga"); b.i(10001);
|
||||
b.i(11000); b.i(11002); b.i(4); b.i(11001);
|
||||
b.i(12000); b.i(12002); b.f(1); b.f(2); b.f(3); b.f(5); b.i(12001);
|
||||
require(SpeedTreeSptInfo::SniffMemory(b.bytes.data(), b.bytes.size(), out), "extension parse failed");
|
||||
require(out.metadata_complete && out.leaf_uv_quads[0] == uv && out.frond_uv_quads[0] == uv
|
||||
&& out.billboard_uv_quads.empty(), "atlas groups/order/corners corrupted");
|
||||
require(out.leaf_texture == "CompositeMap_custom.dds" && out.wind_level == 4, "extension fields lost");
|
||||
require(out.collision_objects.size() == 1 && out.collision_objects[0].dimensions[0] == 5,
|
||||
"collision geometry lost");
|
||||
auto model = SpeedTreeModel::CreateFromMemory(b.bytes.data(), b.bytes.size());
|
||||
for (size_t i = 0; i < 4; ++i) {
|
||||
const auto& vertex = model->GetLeafMesh().vertices[i];
|
||||
require(vertex.uv[0] == uv[i*2] && vertex.uv[1] == uv[i*2+1], "rotated UV quad flattened/flipped");
|
||||
}
|
||||
|
||||
auto billboard=tree();
|
||||
billboard.i(10000);billboard.i(10003);billboard.i(4);
|
||||
for(int i=0;i<4;++i) for(float value:uv) billboard.f(value);
|
||||
billboard.i(10006);billboard.bytes.push_back(1);
|
||||
billboard.i(10007);billboard.bytes.push_back(1);billboard.i(10001);
|
||||
require(SpeedTreeSptInfo::SniffMemory(billboard.bytes.data(),billboard.bytes.size(),out)
|
||||
&& out.horizontal_billboard && out.billboard_360,"billboard flags discarded");
|
||||
auto billboardModel=SpeedTreeModel::CreateFromMemory(billboard.bytes.data(),billboard.bytes.size());
|
||||
auto meshes=billboardModel->BuildBillboardMeshes({0,2000,3000});
|
||||
require(meshes.size()>=2 && meshes.back().name=="horizontal_billboard","missing billboard geometry");
|
||||
const auto& horizontal=meshes.back();
|
||||
for(const auto& vertex:horizontal.vertices)
|
||||
require(vertex.position[1]==horizontal.vertices[0].position[1],"horizontal quad is not planar");
|
||||
for(const auto& mesh:meshes) {
|
||||
require(mesh.vertices.size()==4 && mesh.indices.size()==6,"billboard topology");
|
||||
for(size_t i=0;i<4;++i) require(mesh.vertices[i].uv[0]==uv[i*2]
|
||||
&& mesh.vertices[i].uv[1]==uv[i*2+1],"billboard UV corners changed");
|
||||
}
|
||||
require(billboardModel->BuildBillboardMeshes({0,0,0},255).empty(),"invisible billboard submitted");
|
||||
billboard.i(20000);billboard.i(20003);billboard.bytes.push_back(0);
|
||||
billboard.i(20004);billboard.bytes.push_back(0);billboard.i(20005);
|
||||
for(float value:uv) billboard.f(value);billboard.i(20001);
|
||||
require(SpeedTreeSptInfo::SniffMemory(billboard.bytes.data(),billboard.bytes.size(),out)
|
||||
&& !out.horizontal_billboard && !out.billboard_360 && out.supplemental_uv==uv,
|
||||
"supplementary flags must override legacy flags");
|
||||
|
||||
auto supplement=tree();supplement.field(21000,1);supplement.field(21001,0.4f);
|
||||
require(SpeedTreeSptInfo::SniffMemory(supplement.bytes.data(),supplement.bytes.size(),out)
|
||||
&& out.metadata_complete && out.has_extension_21000
|
||||
&& out.extension_21000[0]==1 && out.extension_21000[1]==0.4f,"21000 payload lost");
|
||||
supplement.i(22000);supplement.bytes.push_back(0);
|
||||
require(SpeedTreeSptInfo::SniffMemory(supplement.bytes.data(),supplement.bytes.size(),out)
|
||||
&& !out.metadata_complete && out.unsupported_token==22000,"newer extension hidden");
|
||||
auto truncated=tree();truncated.field(21000,1);truncated.i(21001);
|
||||
require(!SpeedTreeSptInfo::SniffMemory(truncated.bytes.data(),truncated.bytes.size(),out),"truncated 21000 accepted");
|
||||
|
||||
// Every strict prefix ends inside a required section, marker or payload.
|
||||
for (size_t size = 0; size < tree().bytes.size(); ++size) {
|
||||
auto plain = tree();
|
||||
require(!SpeedTreeSptInfo::SniffMemory(plain.bytes.data(), size, out) && !out.ok,
|
||||
"truncated base accepted or stale result retained");
|
||||
}
|
||||
auto invalid = tree(); invalid.bytes[0] = 0;
|
||||
require(!SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out), "invalid magic accepted");
|
||||
invalid = tree(); invalid.i(10000); invalid.i(10002); invalid.i(0xffffffff);
|
||||
require(!SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out), "invalid count accepted");
|
||||
invalid = tree(); invalid.i(98765);
|
||||
require(SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out)
|
||||
&& !out.metadata_complete && out.unsupported_token == 98765, "unsupported extension hidden");
|
||||
|
||||
invalid = tree(); invalid.i(10000); invalid.i(10002); invalid.i(1); invalid.f(0);
|
||||
require(!SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out), "truncated UV array accepted");
|
||||
invalid = tree(); invalid.i(10000); invalid.i(10002); invalid.i(1);
|
||||
invalid.i(0x7fc00000); for (int i = 0; i < 7; ++i) invalid.f(0);
|
||||
invalid.i(10001);
|
||||
require(!SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out), "non-finite UV accepted");
|
||||
// The legacy sniffer arbitrarily discarded atlases with more than 64 entries.
|
||||
invalid = tree(); invalid.i(10000); invalid.i(10002); invalid.i(65);
|
||||
for (int i = 0; i < 65; ++i) for (float v : uv) invalid.f(v);
|
||||
invalid.i(10001);
|
||||
require(SpeedTreeSptInfo::SniffMemory(invalid.bytes.data(), invalid.bytes.size(), out)
|
||||
&& out.leaf_uv_quads.size() == 65, "valid large atlas rejected");
|
||||
|
||||
// A token-shaped byte sequence inside a counted texture string is data.
|
||||
Buffer embedded;
|
||||
embedded.i(1000); embedded.s("__IdvSpt_02_"); embedded.i(1002);
|
||||
embedded.i(2000); embedded.s(std::string("bark") + std::string("\xd6\x07\0\0",4) + "leaf.tga");
|
||||
embedded.field(2006, 100); embedded.field(2007, 0); embedded.i(1003); embedded.i(1001);
|
||||
require(SpeedTreeSptInfo::SniffMemory(embedded.bytes.data(), embedded.bytes.size(), out) && out.size == 100,
|
||||
"token bytes inside string changed size");
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
formatTests();
|
||||
if (argc == 2) {
|
||||
size_t total = 0, complete = 0, failed = 0;
|
||||
for (const auto& entry : std::filesystem::recursive_directory_iterator(argv[1])) {
|
||||
if (entry.path().extension() != ".spt") continue;
|
||||
SpeedTreeSptInfo info; ++total;
|
||||
bool ok = SpeedTreeSptInfo::SniffFile(entry.path().string(), info);
|
||||
if (!ok) ++failed;
|
||||
if (info.metadata_complete) ++complete;
|
||||
if (!ok || !info.metadata_complete) std::cout << entry.path() << " at " << info.parsed_bytes
|
||||
<< ": " << info.error << '\n';
|
||||
}
|
||||
std::cout << "Corpus: " << total << ", complete: " << complete << ", failed: " << failed << '\n';
|
||||
require(total > 0 && failed == 0, "corpus metadata rejected");
|
||||
}
|
||||
std::cout << "SPT format regression tests passed\n";
|
||||
} catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare generation_baseline JSONL snapshots by relative asset path."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def read(path):
|
||||
rows = [json.loads(line) for line in Path(path).read_text().splitlines()]
|
||||
result = {row["path"]: row for row in rows}
|
||||
if len(rows) != len(result):
|
||||
raise ValueError(f"duplicate paths in {path}")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("before")
|
||||
parser.add_argument("after")
|
||||
args = parser.parse_args()
|
||||
before, after = read(args.before), read(args.after)
|
||||
if before.keys() != after.keys():
|
||||
raise ValueError("sample inventories differ; compare the same corpus root")
|
||||
report = {
|
||||
"samples": len(before),
|
||||
"truncated_before": sum(row["truncated"] for row in before.values()),
|
||||
"truncated_after": sum(row["truncated"] for row in after.values()),
|
||||
"remaining_truncated": [path for path, row in after.items() if row["truncated"]],
|
||||
"new_truncation": [path for path, row in after.items()
|
||||
if row["truncated"] and not before[path]["truncated"]],
|
||||
"geometry_changed": [path for path, row in after.items()
|
||||
if any(row[key] != before[path][key]
|
||||
for key in ("branch_lods", "leaf_lods", "frond_lods"))],
|
||||
"bounds_changed": [path for path, row in after.items()
|
||||
if row["bounds"] != before[path]["bounds"]],
|
||||
}
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
// JSONL snapshots deliberately hash fields, never ABI padding or native structs.
|
||||
static void word(uint64_t& hash,uint32_t value) {
|
||||
for(int i=0;i<4;++i) {hash^=(value>>(8*i))&255;hash*=1099511628211ull;}
|
||||
}
|
||||
static void mesh(const speedtree::SpeedTreeMesh& m) {
|
||||
uint64_t hash=14695981039346656037ull,pivots=hash;
|
||||
for(const auto& v:m.vertices) {
|
||||
for(float x:v.position) {
|
||||
if(!std::isfinite(x)) throw std::runtime_error("nonfinite position");
|
||||
word(hash,std::bit_cast<uint32_t>(x));
|
||||
}
|
||||
for(float x:v.normal) word(hash,std::bit_cast<uint32_t>(x));
|
||||
for(float x:v.uv) word(hash,std::bit_cast<uint32_t>(x));
|
||||
for(float x:v.leaf_pivot_offset) word(pivots,std::bit_cast<uint32_t>(x));
|
||||
}
|
||||
for(auto i:m.indices) {if(i>=m.vertices.size()) throw std::runtime_error("invalid index");word(hash,i);}
|
||||
std::cout<<"{\"vertices\":"<<m.vertices.size()<<",\"triangles\":"<<m.indices.size()/3
|
||||
<<",\"grids\":"<<m.grids.size()<<",\"geometry_hash\":"<<std::quoted(std::to_string(hash))
|
||||
<<",\"pivot_hash\":"<<std::quoted(std::to_string(pivots))<<'}';
|
||||
}
|
||||
int main(int argc,char** argv) {
|
||||
if(argc!=2) {std::cerr<<"usage: generation_baseline SPT_DIRECTORY\n";return 2;}
|
||||
try {
|
||||
const std::filesystem::path root=argv[1];std::vector<std::filesystem::path> paths;
|
||||
for(const auto& f:std::filesystem::recursive_directory_iterator(root))
|
||||
if(f.path().extension()==".spt") paths.push_back(f.path());
|
||||
std::sort(paths.begin(),paths.end());
|
||||
if(paths.empty()) throw std::runtime_error("empty corpus");
|
||||
std::cout<<std::setprecision(9);
|
||||
for(const auto& path:paths) {
|
||||
auto m=speedtree::SpeedTreeModel::CreateFromSpt(path.string());
|
||||
if(!m) throw std::runtime_error("load failed: "+path.string());
|
||||
std::cout<<"{\"path\":"<<std::quoted(std::filesystem::relative(path,root).generic_string())
|
||||
<<",\"seed\":"<<m->GetSptInfo().seed<<",\"levels\":"<<m->GetSptInfo().branch_levels.size()
|
||||
<<",\"truncated\":"<<(m->WasGenerationTruncated()?"true":"false")
|
||||
<<",\"metadata_complete\":"<<(m->GetSptInfo().metadata_complete?"true":"false")
|
||||
<<",\"bounds\":[";
|
||||
bool comma=false;
|
||||
for(const auto& bounds:{m->GetBoundsMin(),m->GetBoundsMax()}) for(float x:bounds) {
|
||||
if(!std::isfinite(x)) throw std::runtime_error("nonfinite bounds: "+path.string());
|
||||
if(comma) std::cout<<',';comma=true;std::cout<<x;
|
||||
}
|
||||
const auto& stats=m->GetGenerationStats();
|
||||
std::cout<<"],\"nodes_by_level\":[";
|
||||
for(size_t i=0;i<stats.nodes_by_level.size();++i) {if(i)std::cout<<',';std::cout<<stats.nodes_by_level[i];}
|
||||
std::cout<<"],\"terminal_leaf_calls\":"<<stats.terminal_leaf_calls
|
||||
<<",\"special_leaf_cards\":"<<stats.special_leaf_cards
|
||||
<<",\"limits\":{\"nodes\":"<<stats.node_limit<<",\"vertices\":"<<stats.vertex_limit
|
||||
<<",\"density\":"<<stats.density_limit<<",\"tessellation\":"<<stats.tessellation_limit
|
||||
<<"},\"branch_lods\":[";
|
||||
for(uint32_t l=0;l<m->GetBranchLodCount();++l) {if(l)std::cout<<',';mesh(m->GetTrunkMesh(l));}
|
||||
std::cout<<"],\"leaf_lods\":[";
|
||||
for(uint32_t l=0;l<m->GetLeafLodCount();++l) {if(l)std::cout<<',';mesh(m->GetLeafMesh(l));}
|
||||
std::cout<<"],\"frond_lods\":[";
|
||||
for(uint32_t l=0;l<m->GetFrondLodCount();++l) {
|
||||
if(l)std::cout<<',';std::cout<<'[';bool first=true;
|
||||
for(const auto& f:m->GetFrondMeshes(l)) {if(!first)std::cout<<',';first=false;mesh(f);}std::cout<<']';
|
||||
}
|
||||
std::cout<<"]}\n";
|
||||
}
|
||||
} catch(const std::exception& e) {std::cerr<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"corpus_root": "AVA2/1. Client DEV/pack_maker",
|
||||
"samples": [
|
||||
{
|
||||
"path": "Tree/ymir work/tree/n2_cinnamonfern_rt_01.spt",
|
||||
"seed": 392987,
|
||||
"sha256": "93ded82028c0f2e97d0403ec045b89bbc1ac859ad8b84a2e1930e0503907b354"
|
||||
},
|
||||
{
|
||||
"path": "Tree/ymir work/tree/wom/ot/treeenglishoakunique01su.spt",
|
||||
"seed": 645082,
|
||||
"sha256": "60c9f3957f8abbf2c38f7b996f5e60e6acdff2693724da86f69968c722a6b3cf"
|
||||
},
|
||||
{
|
||||
"path": "Tree/ymir work/tree/wom/ot/treewhitepinefree.spt",
|
||||
"seed": 777362,
|
||||
"sha256": "e1b2d68db476935cb95e45ba74ae7838d31c9ede6b88d70135365a35c5b383b8"
|
||||
},
|
||||
{
|
||||
"path": "Tree/ymir work/tree/b3_umbrellathorn_rt_flowers4.spt",
|
||||
"seed": 724878,
|
||||
"sha256": "44ec99e53b3158a6619ec7a5cb4110bfb67ff9943224b068a8bc99fa1d92c0d0"
|
||||
}
|
||||
],
|
||||
"synthetic_seeds": [
|
||||
17,
|
||||
18,
|
||||
20
|
||||
],
|
||||
"note": "Fixed source assets and seed-variation fixtures; snapshots are SDK baselines, not original DLL outputs."
|
||||
}
|
||||
Reference in New Issue
Block a user