| 1 |
{ |
| 2 |
Copyright 2018-2024 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Load models in the glTF 2.0 format, converting them to an X3D nodes graph. |
| 17 |
This routine is internally used by the @link(LoadNode) to load an Gltf file. } |
| 18 |
unit X3DLoadInternalGltf; |
| 19 |
|
| 20 |
{$I castleconf.inc} |
| 21 |
|
| 22 |
interface |
| 23 |
|
| 24 |
implementation |
| 25 |
|
| 26 |
uses |
| 27 |
// standard units |
| 28 |
Classes,SysUtils, TypInfo, Math, Generics.Collections, |
| 29 |
// PasGLTF units |
| 30 |
CastlePasGLTF, CastlePasJSON, |
| 31 |
// CGE units |
| 32 |
CastleUtils, CastleVectors, X3DNodes, X3DLoad, X3DFields, |
| 33 |
CastleClassUtils, CastleDownload, CastleUriUtils, CastleLog, |
| 34 |
CastleStringUtils, CastleTextureImages, CastleQuaternions, |
| 35 |
CastleImages, CastleVideos, CastleTimeUtils, CastleTransform, |
| 36 |
CastleLoadGltf, X3DLoadInternalUtils, CastleBoxes, CastleColors, |
| 37 |
CastleRenderOptions; |
| 38 |
|
| 39 |
{ This unit implements reading glTF into X3D. |
| 40 |
We're using PasGLTF from Bero: https://github.com/BeRo1985/pasgltf/ |
| 41 |
|
| 42 |
Docs: |
| 43 |
|
| 44 |
- To understand glTF, and PasGLTF API, see the glTF specification: |
| 45 |
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0 |
| 46 |
|
| 47 |
- This unit converts glTF to an X3D scene graph, |
| 48 |
so you should be familiar with X3D as well: |
| 49 |
https://castle-engine.io/vrml_x3d.php . |
| 50 |
|
| 51 |
- See https://castle-engine.io/creating_data_model_formats.php . |
| 52 |
|
| 53 |
TODOs: |
| 54 |
|
| 55 |
- In the future, we would like to avoid using |
| 56 |
Accessor.DecodeAsXxx. Instead we should load binary data straight to GPU, |
| 57 |
looking at buffers, already exposed by PasGLTF. |
| 58 |
New X3D node, like BufferGeometry (same as X3DOM) will need to be |
| 59 |
invented for this, and CastleInternalGeometryArrays will need to be rearranged. |
| 60 |
|
| 61 |
- Morph targets, or their animations, are not supported yet. |
| 62 |
|
| 63 |
- Skin animation is done by calculating CoordinateInterpolator at loading. |
| 64 |
At runtime we merely animate using CoordinateInterpolator. |
| 65 |
While this is simple, it has disadvantages: |
| 66 |
|
| 67 |
- Loading time is longer, as we need to calculate CoordinateInterpolator. |
| 68 |
- At runtime, interpolation and animation blending can only interpolate |
| 69 |
sets of positions (not bones) so: |
| 70 |
- They are not as accurate, |
| 71 |
- CoordinateInterpolator interpolation is done on CPU, |
| 72 |
it processes all mesh positions each frame. |
| 73 |
This is unoptimal, as glTF skinning can be done on GPU, with much smaller runtime cost. |
| 74 |
|
| 75 |
- See https://castle-engine.io/roadmap . |
| 76 |
} |
| 77 |
|
| 78 |
{ Convert simple types ------------------------------------------------------- } |
| 79 |
|
| 80 |
function Vector3FromGltf(const V: TPasGLTF.TVector3): TVector3; |
| 81 |
begin |
| 82 |
// as it happens, both structures have the same memory layout, so copy by a fast Move |
| 83 |
Assert(SizeOf(V) = SizeOf(Result)); |
| 84 |
Move(V, Result, SizeOf(Result)); |
| 85 |
end; |
| 86 |
|
| 87 |
function Vector4FromGltf(const V: TPasGLTF.TVector4): TVector4; |
| 88 |
begin |
| 89 |
// as it happens, both structures have the same memory layout, so copy by a fast Move |
| 90 |
Assert(SizeOf(V) = SizeOf(Result)); |
| 91 |
Move(V, Result, SizeOf(Result)); |
| 92 |
end; |
| 93 |
|
| 94 |
function Matrix4FromGltf(const M: TPasGLTF.TMatrix4x4): TMatrix4; |
| 95 |
begin |
| 96 |
// as it happens, both structures have the same memory layout, so copy by a fast Move |
| 97 |
Assert(SizeOf(M) = SizeOf(Result)); |
| 98 |
Move(M, Result, SizeOf(Result)); |
| 99 |
end; |
| 100 |
|
| 101 |
{ Convert glTF rotation (quaternion) to X3D (axis-angle). } |
| 102 |
function RotationFromGltf(const V: TPasGLTF.TVector4): TVector4; |
| 103 |
var |
| 104 |
RotationQuaternion: TQuaternion; |
| 105 |
begin |
| 106 |
RotationQuaternion.Data.Vector4 := Vector4FromGltf(V); |
| 107 |
Result := RotationQuaternion.ToAxisAngle; |
| 108 |
end; |
| 109 |
|
| 110 |
{ TMyGltfDocument ------------------------------------------------------------ } |
| 111 |
|
| 112 |
type |
| 113 |
{ Descendant of TPasGLTF.TDocument that changes URI loading, |
| 114 |
to load URI using our CastleDownload, thus supporting all our URLs. } |
| 115 |
TMyGltfDocument = class(TPasGLTF.TDocument) |
| 116 |
strict private |
| 117 |
function CastleGetUri(const aUri: TPasGLTFUTF8String): TStream; |
| 118 |
public |
| 119 |
constructor Create(const Stream: TStream; const BaseUrl: String); reintroduce; |
| 120 |
end; |
| 121 |
|
| 122 |
constructor TMyGltfDocument.Create(const Stream: TStream; const BaseUrl: String); |
| 123 |
begin |
| 124 |
inherited Create; |
| 125 |
|
| 126 |
{ The interpretation of RootPath lies on our side, in GetUri implementation. |
| 127 |
Just use it to store BaseUrl then. } |
| 128 |
RootPath := BaseUrl; |
| 129 |
GetUri := {$ifdef FPC}@{$endif}CastleGetUri; |
| 130 |
|
| 131 |
LoadFromStream(Stream); |
| 132 |
end; |
| 133 |
|
| 134 |
function TMyGltfDocument.CastleGetUri(const aUri: TPasGLTFUTF8String): TStream; |
| 135 |
begin |
| 136 |
{ Resolve and open URI using our CGE functions. |
| 137 |
Without this, TPasGLTF.TDocument.DefaultGetUri would always use TFileStream.Create, |
| 138 |
and not work e.g. with Android assets. } |
| 139 |
Result := Download(CombineUri(RootPath, aUri)); |
| 140 |
end; |
| 141 |
|
| 142 |
{ TGltfAppearanceNode -------------------------------------------------------- } |
| 143 |
|
| 144 |
type |
| 145 |
{ X3D Appearance node extended to carry some additional information specified |
| 146 |
in glTF materials. } |
| 147 |
TGltfAppearanceNode = class(TAppearanceNode) |
| 148 |
public |
| 149 |
DoubleSided: Boolean; |
| 150 |
{ Some glTF geometry is using this. |
| 151 |
Deliberately defined such that default @false is OK, |
| 152 |
and during import it may be set to @true. } |
| 153 |
Used: Boolean; |
| 154 |
{ Some glTF geometry that is possibly lit is using this. |
| 155 |
All geometries are "lit" except lines and points without normals, |
| 156 |
see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#point-and-line-materials . |
| 157 |
Deliberately defined such that default @false is OK, |
| 158 |
and during import it may be set to @true. } |
| 159 |
UsedAsLit: Boolean; |
| 160 |
end; |
| 161 |
|
| 162 |
{ TSkinToInitialize ---------------------------------------------------------- } |
| 163 |
|
| 164 |
type |
| 165 |
{ Information about skin, to be used later. } |
| 166 |
TSkinToInitialize = class |
| 167 |
Skin: TPasGLTF.TSkin; |
| 168 |
{ Direct children of this grouping node that are TShapeNode should have skinning applied. } |
| 169 |
Shapes: TAbstractGroupingNode; |
| 170 |
{ Immediate parent of the Shapes node (it always has only one parent). } |
| 171 |
ShapesParent: TAbstractGroupingNode; |
| 172 |
end; |
| 173 |
|
| 174 |
TSkinToInitializeList = {$ifdef FPC}specialize{$endif} TObjectList<TSkinToInitialize>; |
| 175 |
|
| 176 |
{ TAnimation ----------------------------------------------------------------- } |
| 177 |
|
| 178 |
type |
| 179 |
// Which TTransformNode field is animated |
| 180 |
TGltfSamplerPath = ( |
| 181 |
gsTranslation, |
| 182 |
gsRotation, |
| 183 |
gsScale |
| 184 |
); |
| 185 |
|
| 186 |
TInterpolator = record |
| 187 |
Node: TAbstractInterpolatorNode; |
| 188 |
Target: TTransformNode; |
| 189 |
Path: TGltfSamplerPath; |
| 190 |
end; |
| 191 |
|
| 192 |
TInterpolatorList = {$ifdef FPC}specialize{$endif} TList<TInterpolator>; |
| 193 |
|
| 194 |
{ Information about created animation. } |
| 195 |
TAnimation = class |
| 196 |
TimeSensor: TTimeSensorNode; |
| 197 |
Interpolators: TInterpolatorList; //< Only TTransformNode instances |
| 198 |
constructor Create; |
| 199 |
destructor Destroy; override; |
| 200 |
end; |
| 201 |
|
| 202 |
TAnimationList = {$ifdef FPC}specialize{$endif} TObjectList<TAnimation>; |
| 203 |
|
| 204 |
constructor TAnimation.Create; |
| 205 |
begin |
| 206 |
inherited; |
| 207 |
Interpolators := TInterpolatorList.Create; |
| 208 |
end; |
| 209 |
|
| 210 |
destructor TAnimation.Destroy; |
| 211 |
begin |
| 212 |
FreeAndNil(Interpolators); |
| 213 |
inherited; |
| 214 |
end; |
| 215 |
|
| 216 |
{ TAnimationSampler --------------------------------------------------------------- } |
| 217 |
|
| 218 |
type |
| 219 |
TAnimationSampler = class |
| 220 |
strict private |
| 221 |
{ Internal in SetTime. } |
| 222 |
CurrentTranslation: TVector3List; |
| 223 |
CurrentRotation: TVector4List; |
| 224 |
CurrentScale: TVector3List; |
| 225 |
public |
| 226 |
{ Set this before @link(SetTime). |
| 227 |
List of TTransformNode nodes, ordered just list glTF nodes. |
| 228 |
Only initialized (non-nil and enough Count) for nodes that we created in ReadNode. } |
| 229 |
TransformNodes: TX3DNodeList; |
| 230 |
{ Set this before @link(SetTime). |
| 231 |
Current animation applied by @link(SetTime). } |
| 232 |
Animation: TAnimation; |
| 233 |
{ Owned by this object, calculated by @link(SetTime). |
| 234 |
Has the same size as TransformNodes, contains accumulated transformation matrix |
| 235 |
for each node. |
| 236 |
Contains undefined value for nodes that are @nil. } |
| 237 |
Transformations: TTransformationList; |
| 238 |
TransformNodesRoots: TPasGLTF.TScene.TNodes; |
| 239 |
TransformNodesGltf: TPasGLTF.TNodes; |
| 240 |
constructor Create; |
| 241 |
destructor Destroy; override; |
| 242 |
procedure SetTime(const Time: TFloatTime); |
| 243 |
end; |
| 244 |
|
| 245 |
constructor TAnimationSampler.Create; |
| 246 |
begin |
| 247 |
inherited; |
| 248 |
Transformations := TTransformationList.Create; |
| 249 |
CurrentTranslation := TVector3List.Create; |
| 250 |
CurrentRotation := TVector4List.Create; |
| 251 |
CurrentScale := TVector3List.Create; |
| 252 |
end; |
| 253 |
|
| 254 |
destructor TAnimationSampler.Destroy; |
| 255 |
begin |
| 256 |
FreeAndNil(Transformations); |
| 257 |
FreeAndNil(CurrentTranslation); |
| 258 |
FreeAndNil(CurrentRotation); |
| 259 |
FreeAndNil(CurrentScale); |
| 260 |
inherited; |
| 261 |
end; |
| 262 |
|
| 263 |
procedure TAnimationSampler.SetTime(const Time: TFloatTime); |
| 264 |
|
| 265 |
{ The implementation of this somewhat duplicates the logic |
| 266 |
of the animation and transformation at runtime, |
| 267 |
done by TTransformNode in CastleShapes, CastleSceneCore units. |
| 268 |
At one point I considered just using TTimeSensor.FakeTime |
| 269 |
or even TCastleSceneCore.ForceAnimationPose to set scene |
| 270 |
to given state in each SetTime, and then read resulting transformations |
| 271 |
from Scene.Shapes. |
| 272 |
|
| 273 |
However, this causes new complications: |
| 274 |
It would modify the nodes hierarchy, which means we should save/restore it. |
| 275 |
|
| 276 |
And it's not really much simpler, since the transformation hierarchy is quite simple. |
| 277 |
} |
| 278 |
|
| 279 |
{ Set all CurrentXxx values to reflect initial transformations of TransformNodes } |
| 280 |
procedure ResetCurrentTransformation; |
| 281 |
var |
| 282 |
I: Integer; |
| 283 |
Transform: TTransformNode; |
| 284 |
begin |
| 285 |
// initialize CurrentXxx lists |
| 286 |
for I := 0 to TransformNodes.Count - 1 do |
| 287 |
if TransformNodes[I] <> nil then |
| 288 |
begin |
| 289 |
Transform := TransformNodes[I] as TTransformNode; |
| 290 |
CurrentTranslation[I] := Transform.FdTranslation.Value; |
| 291 |
CurrentRotation [I] := Transform.FdRotation .Value; |
| 292 |
CurrentScale [I] := Transform.FdScale .Value; |
| 293 |
end; |
| 294 |
end; |
| 295 |
|
| 296 |
{ Update all CurrentXxx values affected by this animation. } |
| 297 |
procedure UpdateCurrentTransformation; |
| 298 |
var |
| 299 |
Interpolator: TInterpolator; |
| 300 |
TargetIndex: Integer; |
| 301 |
begin |
| 302 |
for Interpolator in Animation.Interpolators do |
| 303 |
begin |
| 304 |
TargetIndex := TransformNodes.IndexOf(Interpolator.Target); |
| 305 |
if TargetIndex = -1 then |
| 306 |
raise EInternalError.Create('Interpolator.Target not on Nodes list'); |
| 307 |
|
| 308 |
{ Below we process Time, |
| 309 |
similar to TAbstractSingleInterpolatorNode.EventSet_FractionReceive. } |
| 310 |
|
| 311 |
case Interpolator.Path of |
| 312 |
gsTranslation: |
| 313 |
CurrentTranslation[TargetIndex] := |
| 314 |
(Interpolator.Node as TPositionInterpolatorNode).Interpolate(Time); |
| 315 |
gsRotation: |
| 316 |
CurrentRotation[TargetIndex] := |
| 317 |
(Interpolator.Node as TOrientationInterpolatorNode).Interpolate(Time); |
| 318 |
gsScale: |
| 319 |
CurrentScale[TargetIndex] := |
| 320 |
(Interpolator.Node as TPositionInterpolatorNode).Interpolate(Time); |
| 321 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 322 |
else raise EInternalError.Create('Unexpected glTF Interpolator.Path value'); |
| 323 |
{$endif} |
| 324 |
end; |
| 325 |
end; |
| 326 |
end; |
| 327 |
|
| 328 |
{ Calculate contents of Transformations, based on CurrentXxx and parent-child relationships. } |
| 329 |
procedure UpdateMatrix; |
| 330 |
|
| 331 |
procedure UpdateChildMatrix(const NodeIndex: Integer; |
| 332 |
const ParentT: TTransformation); |
| 333 |
var |
| 334 |
T: PTransformation; |
| 335 |
ChildNodeIndex: Integer; |
| 336 |
begin |
| 337 |
if not Between(NodeIndex, 0, Transformations.Count - 1) then |
| 338 |
Exit; // warning about it was already done by ReadNodes |
| 339 |
|
| 340 |
T := PTransformation(Transformations.Ptr(NodeIndex)); |
| 341 |
T^ := ParentT; |
| 342 |
T^.Multiply( |
| 343 |
CurrentRotation[NodeIndex], |
| 344 |
CurrentScale[NodeIndex], |
| 345 |
CurrentTranslation[NodeIndex]); |
| 346 |
|
| 347 |
for ChildNodeIndex in TransformNodesGltf[NodeIndex].Children do |
| 348 |
UpdateChildMatrix(ChildNodeIndex, T^); |
| 349 |
end; |
| 350 |
|
| 351 |
var |
| 352 |
T: PTransformation; |
| 353 |
RootNodeIndex, ChildNodeIndex: Integer; |
| 354 |
begin |
| 355 |
for RootNodeIndex in TransformNodesRoots do |
| 356 |
begin |
| 357 |
if not Between(RootNodeIndex, 0, Transformations.Count - 1) then |
| 358 |
Continue; // warning about it was already done by ReadScene |
| 359 |
|
| 360 |
T := PTransformation(Transformations.Ptr(RootNodeIndex)); |
| 361 |
T^.Init; |
| 362 |
T^.Multiply( |
| 363 |
CurrentRotation[RootNodeIndex], |
| 364 |
CurrentScale[RootNodeIndex], |
| 365 |
CurrentTranslation[RootNodeIndex]); |
| 366 |
|
| 367 |
for ChildNodeIndex in TransformNodesGltf[RootNodeIndex].Children do |
| 368 |
UpdateChildMatrix(ChildNodeIndex, T^); |
| 369 |
end; |
| 370 |
end; |
| 371 |
|
| 372 |
begin |
| 373 |
{ Since in practice TransformNodes.Count is constant during glTF file reading, |
| 374 |
this sets the size only at first SetTime call (for this glTF model). } |
| 375 |
Transformations.Count := TransformNodes.Count; |
| 376 |
CurrentTranslation.Count := TransformNodes.Count; |
| 377 |
CurrentRotation.Count := TransformNodes.Count; |
| 378 |
CurrentScale.Count := TransformNodes.Count; |
| 379 |
|
| 380 |
ResetCurrentTransformation; |
| 381 |
UpdateCurrentTransformation; |
| 382 |
UpdateMatrix; |
| 383 |
end; |
| 384 |
|
| 385 |
{ TTexture ------------------------------------------------------------------- } |
| 386 |
|
| 387 |
type |
| 388 |
{ Texture from glTF information. |
| 389 |
Simpler to initialize than TPasGLTF.TMaterial.TTexture. |
| 390 |
( https://github.com/BeRo1985/pasgltf/blob/master/src/viewer/UnitGLTFOpenGL.pas |
| 391 |
also does it like this, with TTexture record to handle PBRSpecularGlossiness. ) } |
| 392 |
TTexture = record |
| 393 |
Index: TPasGLTFSizeInt; |
| 394 |
TexCoord: TPasGLTFSizeInt; |
| 395 |
TextureTransform: TPasJSONItem; |
| 396 |
procedure Init; |
| 397 |
function Empty: Boolean; |
| 398 |
end; |
| 399 |
|
| 400 |
procedure TTexture.Init; |
| 401 |
begin |
| 402 |
Index := -1; |
| 403 |
TexCoord := 0; |
| 404 |
TextureTransform := nil; |
| 405 |
end; |
| 406 |
|
| 407 |
function TTexture.Empty: Boolean; |
| 408 |
begin |
| 409 |
Result := Index < 0; |
| 410 |
end; |
| 411 |
|
| 412 |
{ TPbrMetallicRoughness ------------------------------------------------------ } |
| 413 |
|
| 414 |
type |
| 415 |
TPbrMetallicRoughness = record |
| 416 |
BaseColorFactor: TVector4; |
| 417 |
BaseColorTexture: TTexture; |
| 418 |
MetallicFactor, RoughnessFactor: Single; |
| 419 |
MetallicRoughnessTexture: TTexture; |
| 420 |
{ Read glTF material parameters into PBR metallic-roughness model. |
| 421 |
|
| 422 |
This internally handles PBR specular-glossiness model, converting |
| 423 |
it into metallic-roughness. See |
| 424 |
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness |
| 425 |
https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows/js/three.pbrUtilities.js |
| 426 |
} |
| 427 |
procedure Read(const Material: TPasGLTF.TMaterial); |
| 428 |
end; |
| 429 |
|
| 430 |
procedure TPbrMetallicRoughness.Read(const Material: TPasGLTF.TMaterial); |
| 431 |
const |
| 432 |
{ Dielectric specular is RGB color with (0.04,0.04,0.04) defined by glTF spec. } |
| 433 |
DielectricSpecular = 0.04; |
| 434 |
|
| 435 |
{ Equations to convert from specular-glossiness to metallic-roughness from |
| 436 |
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows/js |
| 437 |
} |
| 438 |
|
| 439 |
function SolveMetallic(const Diffuse, Specular, OneMinusSpecularStrength: Single): Single; |
| 440 |
var |
| 441 |
A, B, C, D: Single; |
| 442 |
begin |
| 443 |
if Specular < DielectricSpecular then |
| 444 |
Exit(0); |
| 445 |
|
| 446 |
A := DielectricSpecular; |
| 447 |
B := Diffuse * OneMinusSpecularStrength / (1 - DielectricSpecular) + Specular - 2 * DielectricSpecular; |
| 448 |
C := DielectricSpecular - Specular; |
| 449 |
D := Max(B * B - 4 * A * C, 0); |
| 450 |
Result := Clamped((-B + Sqrt(D)) / (2 * A), 0, 1); |
| 451 |
end; |
| 452 |
|
| 453 |
function GetPerceivedBrightness(const C: TCastleColorRGB): Single; |
| 454 |
begin |
| 455 |
Result := Sqrt(0.299 * Sqr(C.X) + 0.587 * Sqr(C.Y) + 0.114 * Sqr(C.Z)); |
| 456 |
end; |
| 457 |
|
| 458 |
procedure ConvertSpecularGlossinessToMetallicRoughness( |
| 459 |
const Diffuse: TVector4; const Specular: TVector3; |
| 460 |
const Glossiness: Single; const HasSpecularGlossinessTexture: Boolean); |
| 461 |
var |
| 462 |
Diffuse3: TVector3; |
| 463 |
OneMinusSpecularStrength: Single; |
| 464 |
BaseColorFromDiffuse, BaseColorFromSpecular: TVector3; |
| 465 |
begin |
| 466 |
OneMinusSpecularStrength := 1 - Specular.Max; |
| 467 |
Diffuse3 := Diffuse.XYZ; |
| 468 |
MetallicFactor := SolveMetallic(GetPerceivedBrightness(Diffuse3), GetPerceivedBrightness(Specular), |
| 469 |
OneMinusSpecularStrength); |
| 470 |
BaseColorFromDiffuse := Diffuse3 * (OneMinusSpecularStrength / (1 - DielectricSpecular) / Max(1 - MetallicFactor, SingleEpsilon)); |
| 471 |
BaseColorFromSpecular := (Specular - |
| 472 |
(Vector3(DielectricSpecular, DielectricSpecular, DielectricSpecular) * (1 - MetallicFactor))) * |
| 473 |
(1 / Max(MetallicFactor, SingleEpsilon)); |
| 474 |
BaseColorFactor := Vector4( |
| 475 |
TVector3.Lerp(Sqr(MetallicFactor), BaseColorFromDiffuse, BaseColorFromSpecular), |
| 476 |
Diffuse.W { BaseColor.alpha is just copied from Diffuse.alpha } |
| 477 |
); |
| 478 |
RoughnessFactor := 1 - Glossiness; |
| 479 |
|
| 480 |
if HasSpecularGlossinessTexture then |
| 481 |
begin |
| 482 |
{ This whole conversion isn't really correct if material has SpecularGlossinessTexture, |
| 483 |
since this changes specular/glossiness per-pixel, |
| 484 |
and we cannot account for that without shader. |
| 485 |
|
| 486 |
In particular glossiness may be left as 1 (default), |
| 487 |
causing roughness 0, which results in black material, |
| 488 |
for Bee from https://github.com/castle-engine/castle-model-viewer/issues/27 . |
| 489 |
|
| 490 |
For now just avoid having RoughnessFactor ridiculously low. } |
| 491 |
RoughnessFactor := Max(RoughnessFactor, 0.05); |
| 492 |
end; |
| 493 |
|
| 494 |
(* |
| 495 |
Writeln('PBR specular-glossiness to metallic-roughness:' + NL + |
| 496 |
' Input Diffuse ' + Diffuse.ToString + NL + |
| 497 |
' Input Specular ' + Specular.ToString + NL + |
| 498 |
' Input Glossiness ', Glossiness:1:2, NL + |
| 499 |
' ->' + NL + |
| 500 |
' Output Base ' + BaseColorFactor.ToString + NL + |
| 501 |
' Output Metallic ', MetallicFactor:1:2, NL + |
| 502 |
' Output Roughness ', RoughnessFactor:1:2 |
| 503 |
); *) |
| 504 |
end; |
| 505 |
|
| 506 |
procedure ReadSpecularGlossiness(const JsonSpecGloss: TPasJSONItemObject); |
| 507 |
var |
| 508 |
JSONItem, Exts: TPasJSONItem; |
| 509 |
DiffuseFactor: TVector4; |
| 510 |
SpecularFactor: TVector3; |
| 511 |
GlossinessFactor: Single; |
| 512 |
DiffuseTexture, SpecularGlossinessTexture: TTexture; |
| 513 |
DiffuseJson, SpecularGlossinessJson: TPasJSONItemObject; |
| 514 |
begin |
| 515 |
{ Read PBR specular-glossiness subset. |
| 516 |
As we only read subset, we use it only when |
| 517 |
Material.PBRMetallicRoughness is empty, despite |
| 518 |
https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness |
| 519 |
advising to use specular-glossiness if you can. |
| 520 |
|
| 521 |
Code below, to read specular-glossiness from JSON, is based on PasGLTF UnitGLTFOpenGL. } |
| 522 |
|
| 523 |
DiffuseFactor := Vector4(1, 1, 1, 1); // default |
| 524 |
JSONItem := JsonSpecGloss.Properties['diffuseFactor']; |
| 525 |
if Assigned(JSONItem) and |
| 526 |
(JSONItem is TPasJSONItemArray) and |
| 527 |
(TPasJSONItemArray(JSONItem).Count = 4) then |
| 528 |
begin |
| 529 |
DiffuseFactor.X := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[0], 1); |
| 530 |
DiffuseFactor.Y := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[1], 1); |
| 531 |
DiffuseFactor.Z := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[2], 1); |
| 532 |
DiffuseFactor.W := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[3], 1); |
| 533 |
end; |
| 534 |
|
| 535 |
DiffuseTexture.Init; |
| 536 |
JSONItem := JsonSpecGloss.Properties['diffuseTexture']; |
| 537 |
if Assigned(JSONItem) and |
| 538 |
(JSONItem is TPasJSONItemObject) then |
| 539 |
begin |
| 540 |
DiffuseJson := TPasJSONItemObject(JSONItem); |
| 541 |
DiffuseTexture.Index := TPasJSON.GetInt64(DiffuseJson.Properties['index'], -1); |
| 542 |
DiffuseTexture.TexCoord := TPasJSON.GetInt64(DiffuseJson.Properties['texCoord'], 0); |
| 543 |
Exts := DiffuseJson.Properties['extensions']; |
| 544 |
if Exts is TPasJSONItemObject then // also checks Exts <> nil |
| 545 |
DiffuseTexture.TextureTransform := TPasJSONItemObject(Exts).Properties['KHR_texture_transform']; |
| 546 |
end; |
| 547 |
|
| 548 |
GlossinessFactor := TPasJSON.GetNumber(JsonSpecGloss.Properties['glossinessFactor'], 1); |
| 549 |
|
| 550 |
SpecularFactor := Vector3(1, 1, 1); // default |
| 551 |
JSONItem := JsonSpecGloss.Properties['specularFactor']; |
| 552 |
if Assigned(JSONItem) and |
| 553 |
(JSONItem is TPasJSONItemArray) and |
| 554 |
(TPasJSONItemArray(JSONItem).Count = 3) then |
| 555 |
begin |
| 556 |
SpecularFactor.X := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[0], 1); |
| 557 |
SpecularFactor.Y := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[1], 1); |
| 558 |
SpecularFactor.Z := TPasJSON.GetNumber(TPasJSONItemArray(JSONItem).Items[2], 1); |
| 559 |
end; |
| 560 |
|
| 561 |
SpecularGlossinessTexture.Init; |
| 562 |
JSONItem := JsonSpecGloss.Properties['specularGlossinessTexture']; |
| 563 |
if Assigned(JSONItem) and |
| 564 |
(JSONItem is TPasJSONItemObject) then |
| 565 |
begin |
| 566 |
SpecularGlossinessJson := TPasJSONItemObject(JSONItem); |
| 567 |
SpecularGlossinessTexture.Index := TPasJSON.GetInt64(SpecularGlossinessJson.Properties['index'], -1); |
| 568 |
SpecularGlossinessTexture.TexCoord := TPasJSON.GetInt64(SpecularGlossinessJson.Properties['texCoord'], 0); |
| 569 |
Exts := SpecularGlossinessJson.Properties['extensions']; |
| 570 |
if Exts is TPasJSONItemObject then // also checks Exts <> nil |
| 571 |
SpecularGlossinessTexture.TextureTransform := TPasJSONItemObject(Exts).Properties['KHR_texture_transform']; |
| 572 |
end; |
| 573 |
|
| 574 |
// convert to metallic-roughness |
| 575 |
ConvertSpecularGlossinessToMetallicRoughness( |
| 576 |
DiffuseFactor, SpecularFactor, GlossinessFactor, |
| 577 |
not SpecularGlossinessTexture.Empty); |
| 578 |
BaseColorTexture := DiffuseTexture; |
| 579 |
// ignore SpecularSpecularGlossinessTexture |
| 580 |
end; |
| 581 |
|
| 582 |
var |
| 583 |
JsonSpecGlossItem: TPasJSONItem; |
| 584 |
begin |
| 585 |
BaseColorFactor := Vector4FromGltf(Material.PBRMetallicRoughness.BaseColorFactor); |
| 586 |
|
| 587 |
BaseColorTexture.Init; |
| 588 |
BaseColorTexture.Index := Material.PBRMetallicRoughness.BaseColorTexture.Index; |
| 589 |
BaseColorTexture.TexCoord := Material.PBRMetallicRoughness.BaseColorTexture.TexCoord; |
| 590 |
BaseColorTexture.TextureTransform := Material.PBRMetallicRoughness.BaseColorTexture.Extensions.Properties['KHR_texture_transform']; |
| 591 |
|
| 592 |
MetallicFactor := Material.PBRMetallicRoughness.MetallicFactor; |
| 593 |
RoughnessFactor := Material.PBRMetallicRoughness.RoughnessFactor; |
| 594 |
|
| 595 |
MetallicRoughnessTexture.Init; |
| 596 |
MetallicRoughnessTexture.Index := Material.PBRMetallicRoughness.MetallicRoughnessTexture.Index; |
| 597 |
MetallicRoughnessTexture.TexCoord := Material.PBRMetallicRoughness.MetallicRoughnessTexture.TexCoord; |
| 598 |
MetallicRoughnessTexture.TextureTransform := Material.PBRMetallicRoughness.MetallicRoughnessTexture.Extensions.Properties['KHR_texture_transform']; |
| 599 |
|
| 600 |
{ Read PBR specular-glossiness } |
| 601 |
|
| 602 |
JsonSpecGlossItem := Material.Extensions.Properties['KHR_materials_pbrSpecularGlossiness']; |
| 603 |
if Material.PBRMetallicRoughness.Empty and |
| 604 |
(JsonSpecGlossItem is TPasJSONItemObject) then |
| 605 |
begin |
| 606 |
WritelnWarning('Material "%s" has only PBR specular-glossiness parameters. We support it only partially (in particular specularGlossinessTexture is ignored). Better use metallic-roughness model.', [ |
| 607 |
Material.Name |
| 608 |
]); |
| 609 |
ReadSpecularGlossiness(TPasJSONItemObject(JsonSpecGlossItem)); |
| 610 |
end; |
| 611 |
end; |
| 612 |
|
| 613 |
{ TPunctualLights ------------------------------------------------------------------ } |
| 614 |
|
| 615 |
type |
| 616 |
{ Load glTF punctual lights. |
| 617 |
Following glTF https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual |
| 618 |
extension. |
| 619 |
Code was reworked from PasGLTF LoadLights in |
| 620 |
https://github.com/BeRo1985/pasgltf/blob/master/src/viewer/UnitGLTFOpenGL.pas } |
| 621 |
TPunctualLights = class |
| 622 |
strict private |
| 623 |
{ Only instances of TAbstractLightNode here. } |
| 624 |
Lights: TX3DNodeList; |
| 625 |
procedure ReadLight(const LightObject: TPasJSONItemObject); |
| 626 |
public |
| 627 |
destructor Destroy; override; |
| 628 |
{ Read document header. } |
| 629 |
procedure ReadHeader(const Document: TPasGLTF.TDocument); |
| 630 |
{ Read glTF node, and optionally add stuff to given TTransformNode for this node. } |
| 631 |
procedure ReadNode(const Node: TPasGLTF.TNode; const Transform: TTransformNode); |
| 632 |
end; |
| 633 |
|
| 634 |
destructor TPunctualLights.Destroy; |
| 635 |
var |
| 636 |
I: Integer; |
| 637 |
begin |
| 638 |
if Lights <> nil then |
| 639 |
begin |
| 640 |
for I := 0 to Lights.Count - 1 do |
| 641 |
Lights[I].FreeIfUnused; |
| 642 |
FreeAndNil(Lights); |
| 643 |
end; |
| 644 |
inherited; |
| 645 |
end; |
| 646 |
|
| 647 |
procedure TPunctualLights.ReadHeader(const Document: TPasGLTF.TDocument); |
| 648 |
var |
| 649 |
KHRLightsPunctualItem, LightsItem, LightItem: TPasJSONItem; |
| 650 |
KHRLightsPunctualObject: TPasJSONItemObject; |
| 651 |
LightsArray: TPasJSONItemArray; |
| 652 |
LightIndex: Integer; |
| 653 |
begin |
| 654 |
if Assigned(Document.Extensions) then |
| 655 |
begin |
| 656 |
KHRLightsPunctualItem := Document.Extensions.Properties['KHR_lights_punctual']; |
| 657 |
if Assigned(KHRLightsPunctualItem) and |
| 658 |
(KHRLightsPunctualItem is TPasJSONItemObject) then |
| 659 |
begin |
| 660 |
KHRLightsPunctualObject := TPasJSONItemObject(KHRLightsPunctualItem); |
| 661 |
LightsItem := KHRLightsPunctualObject.Properties['lights']; |
| 662 |
if Assigned(LightsItem) and |
| 663 |
(LightsItem is TPasJSONItemArray) then |
| 664 |
begin |
| 665 |
Lights := TX3DNodeList.Create(false); |
| 666 |
LightsArray := TPasJSONItemArray(LightsItem); |
| 667 |
for LightIndex := 0 to LightsArray.Count - 1 do |
| 668 |
begin |
| 669 |
LightItem := LightsArray.Items[LightIndex]; |
| 670 |
if Assigned(LightItem) and |
| 671 |
(LightItem is TPasJSONItemObject) then |
| 672 |
begin |
| 673 |
ReadLight(TPasJSONItemObject(LightItem)); |
| 674 |
end; |
| 675 |
end; |
| 676 |
end; |
| 677 |
end; |
| 678 |
end; |
| 679 |
end; |
| 680 |
|
| 681 |
procedure TPunctualLights.ReadLight(const LightObject: TPasJSONItemObject); |
| 682 |
|
| 683 |
{ Read color from JSON, specified like light's color spec on |
| 684 |
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual |
| 685 |
dictates. } |
| 686 |
function ReadColor(const Item: TPasJSONItem; const DefaultColor: TCastleColorRGB): TCastleColorRGB; |
| 687 |
var |
| 688 |
ColorArray: TPasJSONItemArray; |
| 689 |
I: Integer; |
| 690 |
begin |
| 691 |
Result := DefaultColor; |
| 692 |
if Assigned(Item) and |
| 693 |
(Item is TPasJSONItemArray) then |
| 694 |
begin |
| 695 |
ColorArray := TPasJSONItemArray(Item); |
| 696 |
for I := 0 to Min(2, ColorArray.Count - 1) do |
| 697 |
Result.Data[I] := TPasJSON.GetNumber(ColorArray.Items[I], DefaultColor[I]); |
| 698 |
end; |
| 699 |
end; |
| 700 |
|
| 701 |
const |
| 702 |
DefaultBeamWidth = 0.0; |
| 703 |
DefaultCutOffAngle = Pi * 0.25; |
| 704 |
var |
| 705 |
SpotItem: TPasJSONItem; |
| 706 |
SpotObject: TPasJSONItemObject; |
| 707 |
TypeString: String; |
| 708 |
Light: TAbstractLightNode; |
| 709 |
begin |
| 710 |
TypeString := TPasJSON.GetString(LightObject.Properties['type'], ''); |
| 711 |
|
| 712 |
if TypeString = 'directional' then |
| 713 |
begin |
| 714 |
Light := TDirectionalLightNode.Create; |
| 715 |
TDirectionalLightNode(Light).Direction := Vector3(0, 0, -1); |
| 716 |
end else |
| 717 |
if TypeString = 'point' then |
| 718 |
Light := TPointLightNode.Create |
| 719 |
else |
| 720 |
if TypeString = 'spot' then |
| 721 |
begin |
| 722 |
Light := TSpotLightNode.Create; |
| 723 |
TSpotLightNode(Light).Direction := Vector3(0, 0, -1); |
| 724 |
|
| 725 |
SpotItem := LightObject.Properties['spot']; |
| 726 |
if Assigned(SpotItem) and |
| 727 |
(SpotItem is TPasJSONItemObject) then |
| 728 |
begin |
| 729 |
SpotObject := TPasJSONItemObject(SpotItem); |
| 730 |
TSpotLightNode(Light).BeamWidth := TPasJSON.GetNumber(SpotObject.Properties['innerConeAngle'], DefaultBeamWidth); |
| 731 |
TSpotLightNode(Light).CutOffAngle := TPasJSON.GetNumber(SpotObject.Properties['outerConeAngle'], DefaultCutOffAngle); |
| 732 |
end else |
| 733 |
begin |
| 734 |
TSpotLightNode(Light).BeamWidth := DefaultBeamWidth; |
| 735 |
TSpotLightNode(Light).CutOffAngle := DefaultCutOffAngle; |
| 736 |
end; |
| 737 |
end else |
| 738 |
begin |
| 739 |
WritelnWarning('Invalid glTF light type "%s"', [TypeString]); |
| 740 |
Exit; |
| 741 |
end; |
| 742 |
|
| 743 |
Light.Global := true; |
| 744 |
Light.X3DName := TPasJSON.GetString(LightObject.Properties['name'], ''); |
| 745 |
{ Note that glTF intensity may be very large according to KHR_lights_punctual |
| 746 |
(there is no upper limit, since in physics it has no upper limit). |
| 747 |
And Blender can indeed set it to a very large value, like 1000, |
| 748 |
see castle-engine/examples/fps_game/data/example_level/ . |
| 749 |
This is not a problem for CGE, |
| 750 |
and X3D >= 4.0 also allows any large intensity. |
| 751 |
(only X3D 3 and VRML limited it to [0..1] range). } |
| 752 |
Light.Intensity := TPasJSON.GetNumber(LightObject.Properties['intensity'], 1); |
| 753 |
Light.Color := ReadColor(LightObject.Properties['color'], WhiteRGB); |
| 754 |
|
| 755 |
if Light is TAbstractPositionalLightNode then |
| 756 |
begin |
| 757 |
// TODO: falloff to this range will not be as specified by glTF |
| 758 |
TAbstractPositionalLightNode(Light).Radius := TPasJSON.GetNumber(LightObject.Properties['range'], 0); |
| 759 |
// glTF expresses "no range" as 0, we express it as -1 in X3D |
| 760 |
if TAbstractPositionalLightNode(Light).Radius = 0 then |
| 761 |
TAbstractPositionalLightNode(Light).Radius := -1; |
| 762 |
|
| 763 |
{ Following KHR_lights_punctual: """When undefined, range is assumed |
| 764 |
to be infinite and the light should attenuate according to inverse square law.""" |
| 765 |
Simply using this attenuation makes us correct, e.g. rendering matches |
| 766 |
https://gltf-viewer.donmccurdy.com/ (testcase: fps_game level, |
| 767 |
demo-models/gltf/punctual_lights/ ). |
| 768 |
|
| 769 |
Note that without this, X3D by default makes no attenuation, |
| 770 |
which would be bad with large intensity of lights (the scene would be incredibly bright). |
| 771 |
|
| 772 |
TODO: When range is defined, we should make a different falloff according to |
| 773 |
KHR_lights_punctual. } |
| 774 |
TAbstractPositionalLightNode(Light).Attenuation := Vector3(0, 0, 1); |
| 775 |
end; |
| 776 |
|
| 777 |
Lights.Add(Light); |
| 778 |
end; |
| 779 |
|
| 780 |
procedure TPunctualLights.ReadNode(const Node: TPasGLTF.TNode; const Transform: TTransformNode); |
| 781 |
var |
| 782 |
LightIndex: Int64; |
| 783 |
KHRLightsPunctualItem: TPasJSONItem; |
| 784 |
KHRLightsPunctualObject: TPasJSONItemObject; |
| 785 |
begin |
| 786 |
if (Lights <> nil) and Assigned(Node.Extensions) then |
| 787 |
begin |
| 788 |
KHRLightsPunctualItem := Node.Extensions.Properties['KHR_lights_punctual']; |
| 789 |
if Assigned(KHRLightsPunctualItem) and |
| 790 |
(KHRLightsPunctualItem is TPasJSONItemObject) then |
| 791 |
begin |
| 792 |
KHRLightsPunctualObject := TPasJSONItemObject(KHRLightsPunctualItem); |
| 793 |
LightIndex := TPasJSON.GetInt64(KHRLightsPunctualObject.Properties['light'], -1); |
| 794 |
if Between(LightIndex, 0, Lights.Count - 1) then |
| 795 |
Transform.AddChildren(Lights[LightIndex] as TAbstractLightNode) |
| 796 |
else |
| 797 |
WritelnWarning('Invalid light index %d', [LightIndex]); |
| 798 |
end; |
| 799 |
end; |
| 800 |
end; |
| 801 |
|
| 802 |
{ TTextureTransforms --------------------------------------------------------- } |
| 803 |
|
| 804 |
type |
| 805 |
{ To connect glTF idea of texture transformations (each textureInfo can |
| 806 |
have texture transformation) with X3D 4 (each mapping can have texture transformation), |
| 807 |
this collects current texture transformation requirements. |
| 808 |
|
| 809 |
TODO: We could support more even without extending X3D: |
| 810 |
different tex coords could have different transformations. } |
| 811 |
TTextureTransforms = class |
| 812 |
strict private |
| 813 |
HasAny: Boolean; |
| 814 |
public |
| 815 |
SingleTextureTransform: TTextureTransformNode; |
| 816 |
|
| 817 |
{ Mark that given TexCoords have to be transformed with given TTextureTransformNode |
| 818 |
(which may be @nil). |
| 819 |
|
| 820 |
Ignored when TexCoords = '' (this means we don't have a texture, ReadTexture returns |
| 821 |
mapping = '' then). |
| 822 |
|
| 823 |
When TextureTransform = nil means that these tex coords should not be transformed. |
| 824 |
(This is still valuable information that you should pass for each texture.) } |
| 825 |
procedure TransformCoords(const TexCoord: String; const TextureTransform: TTextureTransformNode); |
| 826 |
end; |
| 827 |
|
| 828 |
procedure TTextureTransforms.TransformCoords(const TexCoord: String; const TextureTransform: TTextureTransformNode); |
| 829 |
begin |
| 830 |
if HasAny then |
| 831 |
begin |
| 832 |
if SingleTextureTransform <> TextureTransform then |
| 833 |
begin |
| 834 |
if (SingleTextureTransform <> nil) and |
| 835 |
(TextureTransform <> nil) and |
| 836 |
TVector2.PerfectlyEquals(SingleTextureTransform.FdTranslation.Value, TextureTransform.FdTranslation.Value) and |
| 837 |
TVector2.PerfectlyEquals(SingleTextureTransform.FdScale.Value, TextureTransform.FdScale.Value) and |
| 838 |
(SingleTextureTransform.FdRotation.Value = TextureTransform.FdRotation.Value) then |
| 839 |
{ Ignore the difference, contents of TTextureTransformNode are equal. } |
| 840 |
Exit; |
| 841 |
WritelnWarning('TODO: Textures within material have different texture transformation, not supported now'); |
| 842 |
FreeIfUnusedAndNil(SingleTextureTransform); |
| 843 |
end; |
| 844 |
end; |
| 845 |
|
| 846 |
HasAny := true; |
| 847 |
SingleTextureTransform := TextureTransform; |
| 848 |
end; |
| 849 |
|
| 850 |
{ LoadGltf ------------------------------------------------------------------- } |
| 851 |
|
| 852 |
{ Main routine that converts glTF -> X3D nodes, doing most of the work. } |
| 853 |
function LoadGltf(const Stream: TStream; const BaseUrl: String): TX3DRootNode; |
| 854 |
var |
| 855 |
Document: TPasGLTF.TDocument; |
| 856 |
// List of TGltfAppearanceNode nodes, ordered just list glTF materials |
| 857 |
Appearances: TX3DNodeList; |
| 858 |
{ List of TTransformNode nodes, ordered just list glTF nodes. |
| 859 |
Only initialized (non-nil and enough Count) for nodes that we created in ReadNode. } |
| 860 |
Nodes: TX3DNodeList; |
| 861 |
{ List of X3D nodes to be EXPORTed from the glTF scene, |
| 862 |
so that outer X3D can IMPORT them and use. |
| 863 |
Nodes with X3DName = '' on this list are ignored. |
| 864 |
Everything on Appearances, Nodes, Animations is already EXPORTed too. } |
| 865 |
ExportNodes: TX3DNodeList; |
| 866 |
DefaultAppearance: TGltfAppearanceNode; |
| 867 |
SkinsToInitialize: TSkinToInitializeList; |
| 868 |
Animations: TAnimationList; |
| 869 |
AnimationSampler: TAnimationSampler; |
| 870 |
JointMatrix: TMatrix4List; //< local for SampleSkinAnimation, but created once to avoid wasting time on allocation |
| 871 |
Lights: TPunctualLights; |
| 872 |
|
| 873 |
procedure ReadHeader; |
| 874 |
const |
| 875 |
SupportedExtensions: array [0..3] of String = ( |
| 876 |
'KHR_materials_pbrSpecularGlossiness', |
| 877 |
'KHR_texture_transform', |
| 878 |
'KHR_lights_punctual', |
| 879 |
'KHR_materials_unlit' |
| 880 |
); |
| 881 |
var |
| 882 |
ExtRequired: String; |
| 883 |
begin |
| 884 |
// too verbose to be done by default |
| 885 |
(* |
| 886 |
WritelnLogMultiline('glTF', Format( |
| 887 |
'Asset.Copyright: %s' + NL + |
| 888 |
'Asset.Generator: %s' + NL + |
| 889 |
'Asset.MinVersion: %s' + NL + |
| 890 |
'Asset.Version: %s' + NL + |
| 891 |
'Asset.Empty: %s' + NL + |
| 892 |
'Accessors: %d' + NL + |
| 893 |
'Animations: %d' + NL + |
| 894 |
'Buffers: %d' + NL + |
| 895 |
'BufferViews: %d' + NL + |
| 896 |
'Cameras: %d' + NL + |
| 897 |
'Images: %d' + NL + |
| 898 |
'Materials: %d' + NL + |
| 899 |
'Meshes: %d' + NL + |
| 900 |
'Nodes: %d' + NL + |
| 901 |
'Samplers: %d' + NL + |
| 902 |
'Scenes: %d' + NL + |
| 903 |
'Skins: %d' + NL + |
| 904 |
'Textures: %d' + NL + |
| 905 |
'ExtensionsUsed: %s' + NL + |
| 906 |
'ExtensionsRequired: %s' + NL + |
| 907 |
'', [ |
| 908 |
Document.Asset.Copyright, |
| 909 |
Document.Asset.Generator, |
| 910 |
Document.Asset.MinVersion, |
| 911 |
Document.Asset.Version, |
| 912 |
BoolToStr(Document.Asset.Empty, true), |
| 913 |
|
| 914 |
Document.Accessors.Count, |
| 915 |
Document.Animations.Count, |
| 916 |
Document.Buffers.Count, |
| 917 |
Document.BufferViews.Count, |
| 918 |
Document.Cameras.Count, |
| 919 |
Document.Images.Count, |
| 920 |
Document.Materials.Count, |
| 921 |
Document.Meshes.Count, |
| 922 |
Document.Nodes.Count, |
| 923 |
Document.Samplers.Count, |
| 924 |
Document.Scenes.Count, |
| 925 |
Document.Skins.Count, |
| 926 |
Document.Textures.Count, |
| 927 |
Document.ExtensionsUsed.Text, |
| 928 |
Document.ExtensionsRequired.Text |
| 929 |
]) |
| 930 |
); |
| 931 |
*) |
| 932 |
for ExtRequired in Document.ExtensionsRequired do |
| 933 |
if ArrayPosStr(ExtRequired, SupportedExtensions) = -1 then |
| 934 |
WritelnWarning('Required extension "%s" not supported by glTF reader', [ExtRequired]); |
| 935 |
end; |
| 936 |
|
| 937 |
{ Read glTF "extras" item, with given key and value (JSON array), into X3D "metadata" information. } |
| 938 |
procedure ReadMetadataKeyValueFromArray(const Key: String; const JsonArray: TPasJSONItemArray; const Node: TAbstractNode); |
| 939 |
var |
| 940 |
J: Integer; |
| 941 |
begin |
| 942 |
if JsonArray.Count > 0 then // we ignore empty arrays, as their metadata type is unknown |
| 943 |
begin |
| 944 |
if JsonArray[0] is TPasJSONItemString then |
| 945 |
begin |
| 946 |
Node.MetadataStringArray[Key, JsonArray.Count - 1] := ''; // set array size |
| 947 |
for J := 0 to JsonArray.Count - 1 do |
| 948 |
begin |
| 949 |
if not (JsonArray[J] is TPasJSONItemString) then |
| 950 |
begin |
| 951 |
WritelnWarning('Cannot read glTF extra "%s" index %d, different type than 1st array item', [ |
| 952 |
Key, |
| 953 |
J |
| 954 |
]); |
| 955 |
Continue; |
| 956 |
end; |
| 957 |
Node.MetadataStringArray[Key, J] := (JsonArray[J] as TPasJSONItemString).Value; |
| 958 |
end; |
| 959 |
end else |
| 960 |
if JsonArray[0] is TPasJSONItemBoolean then |
| 961 |
begin |
| 962 |
Node.MetadataBooleanArray[Key, JsonArray.Count - 1] := false; // set array size |
| 963 |
for J := 0 to JsonArray.Count - 1 do |
| 964 |
begin |
| 965 |
if not (JsonArray[J] is TPasJSONItemBoolean) then |
| 966 |
begin |
| 967 |
WritelnWarning('Cannot read glTF extra "%s" index %d, different type than 1st array item', [ |
| 968 |
Key, |
| 969 |
J |
| 970 |
]); |
| 971 |
Continue; |
| 972 |
end; |
| 973 |
Node.MetadataBooleanArray[Key, J] := (JsonArray[J] as TPasJSONItemBoolean).Value; |
| 974 |
end; |
| 975 |
end else |
| 976 |
if JsonArray[0] is TPasJSONItemNumber then |
| 977 |
begin |
| 978 |
Node.MetadataDoubleArray[Key, JsonArray.Count - 1] := 0; ; // set array size |
| 979 |
for J := 0 to JsonArray.Count - 1 do |
| 980 |
begin |
| 981 |
if not (JsonArray[J] is TPasJSONItemNumber) then |
| 982 |
begin |
| 983 |
WritelnWarning('Cannot read glTF extra "%s" index %d, different type than 1st array item', [ |
| 984 |
Key, |
| 985 |
J |
| 986 |
]); |
| 987 |
Continue; |
| 988 |
end; |
| 989 |
Node.MetadataDoubleArray[Key, J] := (JsonArray[J] as TPasJSONItemNumber).Value; |
| 990 |
end; |
| 991 |
end else |
| 992 |
begin |
| 993 |
WritelnWarning('Cannot read glTF extra "%s", unexpected type inside array %s', [ |
| 994 |
Key, |
| 995 |
JsonArray[0].ClassName |
| 996 |
]); |
| 997 |
end; |
| 998 |
end; |
| 999 |
end; |
| 1000 |
|
| 1001 |
{ Read glTF "extras" item, with given key and value (JSON object), into X3D "metadata" information. |
| 1002 |
Testcase: https://github.com/KhronosGroup/3DC-Certification/tree/main/models/AnalyticalCubes } |
| 1003 |
procedure ReadMetadataKeyValueFromObject(const Key: String; const JsonObject: TPasJSONItemObject; const Node: TAbstractNode); |
| 1004 |
var |
| 1005 |
MetadataSet: TMetadataSetNode; |
| 1006 |
StrNode: TMetadataStringNode; |
| 1007 |
BoolNode: TMetadataBooleanNode; |
| 1008 |
DoubleNode: TMetadataDoubleNode; |
| 1009 |
I: Integer; |
| 1010 |
begin |
| 1011 |
{ TODO: It would be better to use recursion here to do read metadata. } |
| 1012 |
MetadataSet := TMetadataSetNode.Create; |
| 1013 |
MetadataSet.NameField := Key; |
| 1014 |
Node.InternalInsertMetadata(MetadataSet); |
| 1015 |
|
| 1016 |
for I := 0 to JsonObject.Count - 1 do |
| 1017 |
begin |
| 1018 |
if JsonObject.Values[I] is TPasJSONItemString then |
| 1019 |
begin |
| 1020 |
StrNode := TMetadataStringNode.Create; |
| 1021 |
StrNode.NameField := JsonObject.Keys[I]; |
| 1022 |
StrNode.SetValue([TPasJSONItemString(JsonObject.Values[I]).Value]); |
| 1023 |
MetadataSet.FdValue.Add(StrNode); |
| 1024 |
end else |
| 1025 |
if JsonObject.Values[I] is TPasJSONItemBoolean then |
| 1026 |
begin |
| 1027 |
BoolNode := TMetadataBooleanNode.Create; |
| 1028 |
BoolNode.NameField := JsonObject.Keys[I]; |
| 1029 |
BoolNode.SetValue([TPasJSONItemBoolean(JsonObject.Values[I]).Value]); |
| 1030 |
MetadataSet.FdValue.Add(BoolNode); |
| 1031 |
end else |
| 1032 |
if JsonObject.Values[I] is TPasJSONItemNumber then |
| 1033 |
begin |
| 1034 |
DoubleNode := TMetadataDoubleNode.Create; |
| 1035 |
DoubleNode.NameField := JsonObject.Keys[I]; |
| 1036 |
DoubleNode.SetValue([TPasJSONItemNumber(JsonObject.Values[I]).Value]); |
| 1037 |
MetadataSet.FdValue.Add(DoubleNode); |
| 1038 |
end else |
| 1039 |
begin |
| 1040 |
WritelnWarning('Cannot read glTF object "%s" inside extra metadata, field "%s", unhandled type %s', [ |
| 1041 |
Key, |
| 1042 |
JsonObject.Keys[I], |
| 1043 |
JsonObject.Values[I].ClassName |
| 1044 |
]); |
| 1045 |
end; |
| 1046 |
end; |
| 1047 |
end; |
| 1048 |
|
| 1049 |
{ Read glTF "extras" into X3D "metadata" information. } |
| 1050 |
procedure ReadMetadata(const Extras: TPasJSONItemObject; const Node: TAbstractNode); |
| 1051 |
var |
| 1052 |
I: Integer; |
| 1053 |
Key: String; |
| 1054 |
begin |
| 1055 |
for I := 0 to Extras.Count - 1 do |
| 1056 |
begin |
| 1057 |
Key := Extras.Keys[I]; |
| 1058 |
if Extras.Values[I] is TPasJSONItemString then |
| 1059 |
Node.MetadataString[Key] := TPasJSONItemString(Extras.Values[I]).Value |
| 1060 |
else |
| 1061 |
if Extras.Values[I] is TPasJSONItemBoolean then |
| 1062 |
Node.MetadataBoolean[Key] := TPasJSONItemBoolean(Extras.Values[I]).Value |
| 1063 |
else |
| 1064 |
if Extras.Values[I] is TPasJSONItemNumber then |
| 1065 |
Node.MetadataDouble[Key] := TPasJSONItemNumber(Extras.Values[I]).Value |
| 1066 |
else |
| 1067 |
if Extras.Values[I] is TPasJSONItemArray then |
| 1068 |
ReadMetadataKeyValueFromArray(Key, TPasJSONItemArray(Extras.Values[I]), Node) |
| 1069 |
else |
| 1070 |
if Extras.Values[I] is TPasJSONItemObject then |
| 1071 |
ReadMetadataKeyValueFromObject(Key, TPasJSONItemObject(Extras.Values[I]), Node) |
| 1072 |
else |
| 1073 |
begin |
| 1074 |
WritelnWarning('Cannot read glTF extra "%s", unexpected type %s', [ |
| 1075 |
Key, |
| 1076 |
Extras.Values[I].ClassName |
| 1077 |
]); |
| 1078 |
end; |
| 1079 |
end; |
| 1080 |
end; |
| 1081 |
|
| 1082 |
function ReadTextureWrap(const Wrap: TPasGLTF.TSampler.TWrappingMode): TBoundaryMode; |
| 1083 |
begin |
| 1084 |
case Wrap of |
| 1085 |
TPasGLTF.TSampler.TWrappingMode.Repeat_ : Result := bmRepeat; |
| 1086 |
TPasGLTF.TSampler.TWrappingMode.ClampToEdge : Result := bmClampToEdge; |
| 1087 |
TPasGLTF.TSampler.TWrappingMode.MirroredRepeat: Result := bmMirroredRepeat; |
| 1088 |
else raise EInternalError.Create('Unexpected glTF wrap'); |
| 1089 |
end; |
| 1090 |
end; |
| 1091 |
|
| 1092 |
function ReadMinificationFilter(const Filter: TPasGLTF.TSampler.TMinFilter): TAutoMinificationFilter; |
| 1093 |
begin |
| 1094 |
case Filter of |
| 1095 |
TPasGLTF.TSampler.TMinFilter.None : Result := minDefault; |
| 1096 |
TPasGLTF.TSampler.TMinFilter.Nearest : Result := minNearest; |
| 1097 |
TPasGLTF.TSampler.TMinFilter.Linear : Result := minLinear; |
| 1098 |
TPasGLTF.TSampler.TMinFilter.NearestMipMapNearest: Result := minNearestMipmapNearest; |
| 1099 |
TPasGLTF.TSampler.TMinFilter.LinearMipMapNearest : Result := minLinearMipmapNearest; |
| 1100 |
TPasGLTF.TSampler.TMinFilter.NearestMipMapLinear : Result := minNearestMipmapLinear; |
| 1101 |
TPasGLTF.TSampler.TMinFilter.LinearMipMapLinear : Result := minLinearMipmapLinear; |
| 1102 |
else raise EInternalError.Create('Unexpected glTF minification filter'); |
| 1103 |
end; |
| 1104 |
end; |
| 1105 |
|
| 1106 |
function ReadMagnificationFilter(const Filter: TPasGLTF.TSampler.TMagFilter): TAutoMagnificationFilter; |
| 1107 |
begin |
| 1108 |
case Filter of |
| 1109 |
TPasGLTF.TSampler.TMagFilter.None : Result := magDefault; |
| 1110 |
TPasGLTF.TSampler.TMagFilter.Nearest: Result := magNearest; |
| 1111 |
TPasGLTF.TSampler.TMagFilter.Linear : Result := magLinear; |
| 1112 |
else raise EInternalError.Create('Unexpected glTF magnification filter'); |
| 1113 |
end; |
| 1114 |
end; |
| 1115 |
|
| 1116 |
function FixTextureUrl(const Url: String): String; |
| 1117 |
begin |
| 1118 |
Result := Url; |
| 1119 |
|
| 1120 |
{ Workaround https://github.com/castle-engine/castle-engine/issues/339 } |
| 1121 |
if Pos('\', Result) <> 0 then |
| 1122 |
begin |
| 1123 |
WritelnWarning('URL in glTF contains a backslash "\", assuming that slash was meant "/": "%s"', [ |
| 1124 |
Result |
| 1125 |
]); |
| 1126 |
StringReplaceAllVar(Result, '\', '/'); |
| 1127 |
end; |
| 1128 |
end; |
| 1129 |
|
| 1130 |
{ Read glTF texture transform from KHR_texture_transform JSON item following |
| 1131 |
https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_texture_transform . |
| 1132 |
Input GltfTextureTransform may be @nil or not even TPasJSONItemObject. |
| 1133 |
May return @nil if no texture transformation. |
| 1134 |
|
| 1135 |
Note: glTF texture V coordinates go down, not up, as in CGE and X3D. |
| 1136 |
But we don't need to do anything about it here, because we are flipping the textures, |
| 1137 |
so there's no need to e.g. flip offset.y in KHR_texture_transform . |
| 1138 |
} |
| 1139 |
function ReadTextureTransform(const GltfTextureTransform: TPasJSONItem): TTextureTransformNode; |
| 1140 |
var |
| 1141 |
TextureTransformJson: TPasJSONItemObject; |
| 1142 |
Offset, Scale: TPasJSONItem; |
| 1143 |
begin |
| 1144 |
Result := nil; |
| 1145 |
if GltfTextureTransform is TPasJSONItemObject then |
| 1146 |
begin |
| 1147 |
TextureTransformJson := TPasJSONItemObject(GltfTextureTransform); |
| 1148 |
Result := TTextureTransformNode.Create; |
| 1149 |
|
| 1150 |
Offset := TextureTransformJson.Properties['offset']; |
| 1151 |
if (Offset is TPasJSONItemArray) and (TPasJSONItemArray(Offset).Count = 2) then |
| 1152 |
Result.FdTranslation.Value := Vector2( |
| 1153 |
TPasJSON.GetNumber(TPasJSONItemArray(Offset).Items[0], 0.0), |
| 1154 |
TPasJSON.GetNumber(TPasJSONItemArray(Offset).Items[1], 0.0) |
| 1155 |
); |
| 1156 |
|
| 1157 |
Result.FdRotation.Value := -TPasJSON.GetNumber(TextureTransformJson.Properties['rotation'], 0); |
| 1158 |
|
| 1159 |
Scale := TextureTransformJson.Properties['scale']; |
| 1160 |
if (Scale is TPasJSONItemArray) and (TPasJSONItemArray(Scale).Count = 2) then |
| 1161 |
Result.FdScale.Value := Vector2( |
| 1162 |
TPasJSON.GetNumber(TPasJSONItemArray(Scale).Items[0], 1.0), |
| 1163 |
TPasJSON.GetNumber(TPasJSONItemArray(Scale).Items[1], 1.0) |
| 1164 |
); |
| 1165 |
end; |
| 1166 |
end; |
| 1167 |
|
| 1168 |
procedure ReadTexture(const GltfTextureAtMaterial: TTexture; |
| 1169 |
out Texture: TAbstractTexture2DNode; out TexMapping: String; |
| 1170 |
const TextureTransforms: TTextureTransforms); overload; |
| 1171 |
var |
| 1172 |
GltfTexture: TPasGLTF.TTexture; |
| 1173 |
GltfImage: TPasGLTF.TImage; |
| 1174 |
GltfSampler: TPasGLTF.TSampler; |
| 1175 |
TextureProperties: TTexturePropertiesNode; |
| 1176 |
Stream: TMemoryStream; |
| 1177 |
TexCoord, OverrideTexCoord: TPasGLTFSizeInt; |
| 1178 |
TextureTransform: TTextureTransformNode; |
| 1179 |
begin |
| 1180 |
Texture := nil; |
| 1181 |
TextureTransform := nil; |
| 1182 |
GltfImage := nil; |
| 1183 |
TexMapping := ''; // for no texture, use empty mapping, to keep output X3D simple |
| 1184 |
|
| 1185 |
if not GltfTextureAtMaterial.Empty then |
| 1186 |
begin |
| 1187 |
if GltfTextureAtMaterial.Index < Document.Textures.Count then |
| 1188 |
begin |
| 1189 |
GltfTexture := Document.Textures[GltfTextureAtMaterial.Index]; |
| 1190 |
|
| 1191 |
if Between(GltfTexture.Source, 0, Document.Images.Count - 1) then |
| 1192 |
begin |
| 1193 |
GltfImage := Document.Images[GltfTexture.Source]; |
| 1194 |
if GltfImage.Uri <> '' then |
| 1195 |
begin |
| 1196 |
if FfmpegVideoMimeType(UriMimeType(GltfImage.Uri), false) then |
| 1197 |
begin |
| 1198 |
Texture := TMovieTextureNode.Create('', BaseUrl); |
| 1199 |
TMovieTextureNode(Texture).SetUrl([FixTextureUrl(GltfImage.Uri)]); |
| 1200 |
if CastleX3dExtensions then |
| 1201 |
TMovieTextureNode(Texture).FlipVertically := true; |
| 1202 |
TMovieTextureNode(Texture).Loop := true; |
| 1203 |
end else |
| 1204 |
begin |
| 1205 |
Texture := TImageTextureNode.Create('', BaseUrl); |
| 1206 |
TImageTextureNode(Texture).SetUrl([FixTextureUrl(GltfImage.Uri)]); |
| 1207 |
|
| 1208 |
{ glTF specification defines (0,0) texture coord to be |
| 1209 |
at top-left corner, while X3D and OpenGL and OpenGLES expect it be |
| 1210 |
at bottom-left corner. |
| 1211 |
See |
| 1212 |
https://castle-engine.io/x3d_implementation_texturing_extensions.php#section_flip_vertically |
| 1213 |
for a detailed discussion. |
| 1214 |
|
| 1215 |
So we flip the textures. |
| 1216 |
This way we can use original texture coordinates from glTF |
| 1217 |
file (no need to process them, by doing "y := 1 - y"). } |
| 1218 |
if CastleX3dExtensions then |
| 1219 |
TImageTextureNode(Texture).FlipVertically := true; |
| 1220 |
end; |
| 1221 |
end else |
| 1222 |
if GltfImage.BufferView >= 0 then |
| 1223 |
begin |
| 1224 |
{ Use GltfImage.GetResourceData to load from buffer |
| 1225 |
(instead of an external file). In particular, this is necessary to |
| 1226 |
support GLB format with textures. |
| 1227 |
|
| 1228 |
Note that we use GltfImage.GetResourceData only when |
| 1229 |
GltfImage.BufferView was set. Otherwise, we want to interpret URI |
| 1230 |
by CGE code, thus allowing to read files using our Download() |
| 1231 |
that understands also http/https, castle-data, castle-android-assets etc. |
| 1232 |
} |
| 1233 |
Stream := TMemoryStream.Create; |
| 1234 |
try |
| 1235 |
GltfImage.GetResourceData(Stream); |
| 1236 |
Stream.Position := 0; |
| 1237 |
|
| 1238 |
{ TODO: In case this is a DDS/KTX file, by using LoadImage |
| 1239 |
we lose information about additional mipmaps, |
| 1240 |
cubemap faces etc. } |
| 1241 |
|
| 1242 |
Texture := TPixelTextureNode.Create; |
| 1243 |
try |
| 1244 |
TPixelTextureNode(Texture).FdImage.Value := |
| 1245 |
LoadImage(Stream, GltfImage.MimeType, []); |
| 1246 |
except |
| 1247 |
on E: Exception do |
| 1248 |
WritelnWarning('glTF', 'Cannot load the texture from glTF binary buffer with mime type %s: %s', |
| 1249 |
[GltfImage.MimeType, ExceptMessage(E)]); |
| 1250 |
end; |
| 1251 |
|
| 1252 |
{ Same reason as for TImageTextureNode.FlipVertically above: |
| 1253 |
glTF specification defines (0,0) texture coord to be |
| 1254 |
at top-left corner. } |
| 1255 |
if CastleX3dExtensions then |
| 1256 |
TPixelTextureNode(Texture).FdImage.Value.FlipVertical; |
| 1257 |
finally FreeAndNil(Stream) end; |
| 1258 |
end; |
| 1259 |
end; |
| 1260 |
|
| 1261 |
if Texture <> nil then // above clause succeded in reading Texture |
| 1262 |
begin |
| 1263 |
{ Use glTF name for X3D node name. } |
| 1264 |
if GltfImage <> nil then |
| 1265 |
Texture.X3DName := GltfImage.Name; |
| 1266 |
|
| 1267 |
TexCoord := GltfTextureAtMaterial.TexCoord; |
| 1268 |
|
| 1269 |
{ Allow KHR_texture_transform to override texture coordinates, |
| 1270 |
if it specifies texCoord. } |
| 1271 |
if GltfTextureAtMaterial.TextureTransform is TPasJSONItemObject then |
| 1272 |
begin |
| 1273 |
OverrideTexCoord := TPasJSON.GetInt64(TPasJSONItemObject(GltfTextureAtMaterial.TextureTransform).Properties['texCoord'], -1); |
| 1274 |
if OverrideTexCoord <> -1 then |
| 1275 |
TexCoord := OverrideTexCoord; |
| 1276 |
end; |
| 1277 |
|
| 1278 |
TexMapping := 'TEXCOORD_' + IntToStr(TexCoord); |
| 1279 |
|
| 1280 |
// read wrap and filtering options |
| 1281 |
if Between(GltfTexture.Sampler, 0, Document.Samplers.Count - 1) then |
| 1282 |
begin |
| 1283 |
GltfSampler := Document.Samplers[GltfTexture.Sampler]; |
| 1284 |
|
| 1285 |
if (GltfSampler.WrapS <> TPasGLTF.TSampler.TWrappingMode.Repeat_) or |
| 1286 |
(GltfSampler.WrapT <> TPasGLTF.TSampler.TWrappingMode.Repeat_) or |
| 1287 |
(GltfSampler.MinFilter <> TPasGLTF.TSampler.TMinFilter.None) or |
| 1288 |
(GltfSampler.MagFilter <> TPasGLTF.TSampler.TMagFilter.None) then |
| 1289 |
begin |
| 1290 |
TextureProperties := TTexturePropertiesNode.Create; |
| 1291 |
TextureProperties.MinificationFilter := ReadMinificationFilter(GltfSampler.MinFilter); |
| 1292 |
TextureProperties.MagnificationFilter := ReadMagnificationFilter(GltfSampler.MagFilter); |
| 1293 |
TextureProperties.BoundaryModeS := ReadTextureWrap(GltfSampler.WrapS); |
| 1294 |
TextureProperties.BoundaryModeT := ReadTextureWrap(GltfSampler.WrapT); |
| 1295 |
Texture.TextureProperties := TextureProperties; |
| 1296 |
end; |
| 1297 |
end; |
| 1298 |
|
| 1299 |
TextureTransform := ReadTextureTransform(GltfTextureAtMaterial.TextureTransform); |
| 1300 |
TextureTransforms.TransformCoords(TexMapping, TextureTransform); |
| 1301 |
end; |
| 1302 |
end; |
| 1303 |
end; |
| 1304 |
end; |
| 1305 |
|
| 1306 |
procedure ReadTexture(const GltfTextureAtMaterial: TPasGLTF.TMaterial.TTexture; |
| 1307 |
out Texture: TAbstractTexture2DNode; out TexMapping: String; |
| 1308 |
const TextureTransforms: TTextureTransforms); overload; |
| 1309 |
var |
| 1310 |
TextureRec: TTexture; |
| 1311 |
begin |
| 1312 |
TextureRec.Init; |
| 1313 |
TextureRec.Index := GltfTextureAtMaterial.Index; |
| 1314 |
TextureRec.TexCoord := GltfTextureAtMaterial.TexCoord; |
| 1315 |
TextureRec.TextureTransform := GltfTextureAtMaterial.Extensions.Properties['KHR_texture_transform']; |
| 1316 |
ReadTexture(TextureRec, Texture, TexMapping, TextureTransforms); |
| 1317 |
end; |
| 1318 |
|
| 1319 |
function ReadPhongMaterial(const Material: TPasGLTF.TMaterial; |
| 1320 |
const TexTransforms: TTextureTransforms): TMaterialNode; |
| 1321 |
var |
| 1322 |
PbrMetallicRoughness: TPbrMetallicRoughness; |
| 1323 |
BaseColorTexture, NormalTexture, EmissiveTexture: TAbstractTexture2DNode; |
| 1324 |
BaseColorTextureMapping, NormalTextureMapping, EmissiveTextureMapping: String; |
| 1325 |
// MetallicFactor, RoughnessFactor: Single; |
| 1326 |
begin |
| 1327 |
PbrMetallicRoughness.Read(Material); |
| 1328 |
|
| 1329 |
Result := TMaterialNode.Create; |
| 1330 |
Result.DiffuseColor := PbrMetallicRoughness.BaseColorFactor.XYZ; |
| 1331 |
Result.Transparency := 1 - PbrMetallicRoughness.BaseColorFactor.W; |
| 1332 |
Result.EmissiveColor := Vector3FromGltf(Material.EmissiveFactor); |
| 1333 |
|
| 1334 |
// Metallic/roughness conversion idea from X3DOM. |
| 1335 |
// Gives weird artifacts on some samples (Duck, FlightHelmet) so not used now. |
| 1336 |
(* |
| 1337 |
MetallicFactor := PbrMetallicRoughness.MetallicFactor; |
| 1338 |
RoughnessFactor := PbrMetallicRoughness.RoughnessFactor; |
| 1339 |
Result.SpecularColor := Vector3( |
| 1340 |
Lerp(MetallicFactor, 0.04, BaseColorFactor.X), |
| 1341 |
Lerp(MetallicFactor, 0.04, BaseColorFactor.Y), |
| 1342 |
Lerp(MetallicFactor, 0.04, BaseColorFactor.Z) |
| 1343 |
); |
| 1344 |
Result.Shininess := 1 - RoughnessFactor; |
| 1345 |
*) |
| 1346 |
|
| 1347 |
ReadTexture(PbrMetallicRoughness.BaseColorTexture, BaseColorTexture, BaseColorTextureMapping, TexTransforms); |
| 1348 |
Result.DiffuseTexture := BaseColorTexture; |
| 1349 |
Result.DiffuseTextureMapping := BaseColorTextureMapping; |
| 1350 |
|
| 1351 |
ReadTexture(Material.NormalTexture, |
| 1352 |
NormalTexture, NormalTextureMapping, TexTransforms); |
| 1353 |
Result.NormalTexture := NormalTexture; |
| 1354 |
Result.NormalTextureMapping := NormalTextureMapping; |
| 1355 |
|
| 1356 |
if not Material.NormalTexture.Empty then |
| 1357 |
Result.NormalScale := Material.NormalTexture.Scale; |
| 1358 |
|
| 1359 |
ReadTexture(Material.EmissiveTexture, |
| 1360 |
EmissiveTexture, EmissiveTextureMapping, TexTransforms); |
| 1361 |
Result.EmissiveTexture := EmissiveTexture; |
| 1362 |
Result.EmissiveTextureMapping := EmissiveTextureMapping; |
| 1363 |
end; |
| 1364 |
|
| 1365 |
function ReadPhysicalMaterial(const Material: TPasGLTF.TMaterial; |
| 1366 |
const TexTransforms: TTextureTransforms): TPhysicalMaterialNode; |
| 1367 |
var |
| 1368 |
PbrMetallicRoughness: TPbrMetallicRoughness; |
| 1369 |
BaseColorTexture, NormalTexture, EmissiveTexture, MetallicRoughnessTexture, OcclusionTexture: TAbstractTexture2DNode; |
| 1370 |
BaseColorTextureMapping, NormalTextureMapping, EmissiveTextureMapping, MetallicRoughnessTextureMapping, OcclusionTextureMapping: String; |
| 1371 |
begin |
| 1372 |
PbrMetallicRoughness.Read(Material); |
| 1373 |
|
| 1374 |
Result := TPhysicalMaterialNode.Create; |
| 1375 |
Result.BaseColor := PbrMetallicRoughness.BaseColorFactor.XYZ; |
| 1376 |
Result.Transparency := 1 - PbrMetallicRoughness.BaseColorFactor.W; |
| 1377 |
Result.Metallic := PbrMetallicRoughness.MetallicFactor; |
| 1378 |
Result.Roughness := PbrMetallicRoughness.RoughnessFactor; |
| 1379 |
Result.EmissiveColor := Vector3FromGltf(Material.EmissiveFactor); |
| 1380 |
|
| 1381 |
ReadTexture(PbrMetallicRoughness.BaseColorTexture, |
| 1382 |
BaseColorTexture, BaseColorTextureMapping, TexTransforms); |
| 1383 |
Result.BaseTexture := BaseColorTexture; |
| 1384 |
Result.BaseTextureMapping := BaseColorTextureMapping; |
| 1385 |
|
| 1386 |
ReadTexture(Material.NormalTexture, |
| 1387 |
NormalTexture, NormalTextureMapping, TexTransforms); |
| 1388 |
Result.NormalTexture := NormalTexture; |
| 1389 |
Result.NormalTextureMapping := NormalTextureMapping; |
| 1390 |
|
| 1391 |
ReadTexture(Material.EmissiveTexture, |
| 1392 |
EmissiveTexture, EmissiveTextureMapping, TexTransforms); |
| 1393 |
Result.EmissiveTexture := EmissiveTexture; |
| 1394 |
Result.EmissiveTextureMapping := EmissiveTextureMapping; |
| 1395 |
|
| 1396 |
ReadTexture(PbrMetallicRoughness.MetallicRoughnessTexture, |
| 1397 |
MetallicRoughnessTexture, MetallicRoughnessTextureMapping, TexTransforms); |
| 1398 |
Result.MetallicRoughnessTexture := MetallicRoughnessTexture; |
| 1399 |
Result.MetallicRoughnessTextureMapping := MetallicRoughnessTextureMapping; |
| 1400 |
|
| 1401 |
ReadTexture(Material.OcclusionTexture, |
| 1402 |
OcclusionTexture, OcclusionTextureMapping, TexTransforms); |
| 1403 |
Result.OcclusionTexture := OcclusionTexture; |
| 1404 |
Result.OcclusionTextureMapping := OcclusionTextureMapping; |
| 1405 |
Result.OcclusionStrength := Material.OcclusionTexture.Strength; |
| 1406 |
end; |
| 1407 |
|
| 1408 |
{ Read glTF unlit material, see |
| 1409 |
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit . |
| 1410 |
Note that baseColor/Texture is converted to X3D emissiveColor/Texture. } |
| 1411 |
function ReadUnlitMaterial(const Material: TPasGLTF.TMaterial; |
| 1412 |
const TexTransforms: TTextureTransforms): TUnlitMaterialNode; |
| 1413 |
var |
| 1414 |
BaseColorFactor: TVector4; |
| 1415 |
BaseColorTexture, NormalTexture: TAbstractTexture2DNode; |
| 1416 |
BaseColorTextureMapping, NormalTextureMapping: String; |
| 1417 |
begin |
| 1418 |
BaseColorFactor := Vector4FromGltf(Material.PBRMetallicRoughness.BaseColorFactor); |
| 1419 |
|
| 1420 |
Result := TUnlitMaterialNode.Create; |
| 1421 |
Result.EmissiveColor := BaseColorFactor.XYZ; |
| 1422 |
Result.Transparency := 1 - BaseColorFactor.W; |
| 1423 |
|
| 1424 |
ReadTexture(Material.PBRMetallicRoughness.BaseColorTexture, |
| 1425 |
BaseColorTexture, BaseColorTextureMapping, TexTransforms); |
| 1426 |
Result.EmissiveTexture := BaseColorTexture; |
| 1427 |
Result.EmissiveTextureMapping := BaseColorTextureMapping; |
| 1428 |
|
| 1429 |
{ We read normal texture, even though it isn't *usually* useful for UnlitMaterial. |
| 1430 |
But it makes sense when geometry has TextureCoordinateGenerator |
| 1431 |
that depends on normal info. |
| 1432 |
And both glTF and X3Dv4 allow normal texture even in case of unlit materials. } |
| 1433 |
ReadTexture(Material.NormalTexture, |
| 1434 |
NormalTexture, NormalTextureMapping, TexTransforms); |
| 1435 |
Result.NormalTexture := NormalTexture; |
| 1436 |
Result.NormalTextureMapping := NormalTextureMapping; |
| 1437 |
end; |
| 1438 |
|
| 1439 |
function ReadAppearance(const Material: TPasGLTF.TMaterial): TGltfAppearanceNode; |
| 1440 |
var |
| 1441 |
AlphaMode: TAlphaMode; |
| 1442 |
TexTransforms: TTextureTransforms; |
| 1443 |
begin |
| 1444 |
Result := TGltfAppearanceNode.Create(Material.Name); |
| 1445 |
|
| 1446 |
TexTransforms := TTextureTransforms.Create; |
| 1447 |
try |
| 1448 |
if Material.Extensions.Properties['KHR_materials_unlit'] <> nil then |
| 1449 |
Result.Material := ReadUnlitMaterial(Material, TexTransforms) |
| 1450 |
else |
| 1451 |
if GltfForcePhongMaterials then |
| 1452 |
Result.Material := ReadPhongMaterial(Material, TexTransforms) |
| 1453 |
else |
| 1454 |
Result.Material := ReadPhysicalMaterial(Material, TexTransforms); |
| 1455 |
ReadMetadata(Material.Extras, Result.Material); |
| 1456 |
|
| 1457 |
// read common material properties, that make sense in case of all material type |
| 1458 |
Result.DoubleSided := Material.DoubleSided; |
| 1459 |
|
| 1460 |
// read alpha channel treatment |
| 1461 |
case Material.AlphaMode of |
| 1462 |
TPasGLTF.TMaterial.TAlphaMode.Opaque: AlphaMode := amOpaque; |
| 1463 |
TPasGLTF.TMaterial.TAlphaMode.Blend : AlphaMode := amBlend; |
| 1464 |
TPasGLTF.TMaterial.TAlphaMode.Mask : AlphaMode := amMask; |
| 1465 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1466 |
else raise EInternalError.Create('Unexpected glTF Material.AlphaMode value'); |
| 1467 |
{$endif} |
| 1468 |
end; |
| 1469 |
Result.AlphaMode := AlphaMode; |
| 1470 |
Result.AlphaCutOff := Material.AlphaCutOff; |
| 1471 |
|
| 1472 |
Result.TextureTransform := TexTransforms.SingleTextureTransform; |
| 1473 |
finally FreeAndNil(TexTransforms) end; |
| 1474 |
end; |
| 1475 |
|
| 1476 |
procedure FixAppearances; |
| 1477 |
var |
| 1478 |
I: Integer; |
| 1479 |
App: TGltfAppearanceNode; |
| 1480 |
Mat: TPhysicalMaterialNode; |
| 1481 |
begin |
| 1482 |
for I := 0 to Appearances.Count - 1 do |
| 1483 |
begin |
| 1484 |
App := Appearances[I] as TGltfAppearanceNode; |
| 1485 |
{ When rendering unlit points and lines, glTF says to sum base and emissive color, |
| 1486 |
see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#point-and-line-materials . |
| 1487 |
X3D doesn't do this, as it is a bit weird (we also don't always have "base", our |
| 1488 |
UnlitMaterial just has emissive). |
| 1489 |
As a crude fix, we correct materials that we know are only used by unlit things, |
| 1490 |
to have better emissiveColor. } |
| 1491 |
if App.Used and (not App.UsedAsLit) and (App.Material is TPhysicalMaterialNode) then |
| 1492 |
begin |
| 1493 |
Mat := TPhysicalMaterialNode(App.Material); |
| 1494 |
Mat.EmissiveColor := Mat.EmissiveColor + Mat.BaseColor; |
| 1495 |
end; |
| 1496 |
end; |
| 1497 |
end; |
| 1498 |
|
| 1499 |
function AccessorTypeToStr(const AccessorType: TPasGLTF.TAccessor.TType): String; |
| 1500 |
begin |
| 1501 |
Result := GetEnumName(TypeInfo(TPasGLTF.TAccessor.TType), Ord(AccessorType)); |
| 1502 |
end; |
| 1503 |
|
| 1504 |
function PrimitiveModeToStr(const Mode: TPasGLTF.TMesh.TPrimitive.TMode): String; |
| 1505 |
begin |
| 1506 |
Result := GetEnumName(TypeInfo(TPasGLTF.TMesh.TPrimitive.TMode), Ord(Mode)); |
| 1507 |
end; |
| 1508 |
|
| 1509 |
function GetAccessor(const AccessorIndex: Integer): TPasGLTF.TAccessor; |
| 1510 |
begin |
| 1511 |
if AccessorIndex < Document.Accessors.Count then |
| 1512 |
Result := Document.Accessors[AccessorIndex] |
| 1513 |
else |
| 1514 |
begin |
| 1515 |
Result := nil; |
| 1516 |
WritelnWarning('glTF', 'Missing glTF accessor (index %d, but we only have %d accessors)', |
| 1517 |
[AccessorIndex, Document.Accessors.Count]); |
| 1518 |
end; |
| 1519 |
end; |
| 1520 |
|
| 1521 |
{ The argument ForVertex addresses this statement of the glTF spec: |
| 1522 |
""" |
| 1523 |
For performance and compatibility reasons, each element of |
| 1524 |
a vertex attribute must be aligned to 4-byte boundaries |
| 1525 |
inside bufferView |
| 1526 |
""" } |
| 1527 |
|
| 1528 |
procedure AccessorToInt32(const AccessorIndex: Integer; const Field: TMFLong; const ForVertex: Boolean); |
| 1529 |
var |
| 1530 |
Accessor: TPasGLTF.TAccessor; |
| 1531 |
A: TPasGLTFInt32DynamicArray; |
| 1532 |
Len: Integer; |
| 1533 |
begin |
| 1534 |
Accessor := GetAccessor(AccessorIndex); |
| 1535 |
if Accessor <> nil then |
| 1536 |
begin |
| 1537 |
A := Accessor.DecodeAsInt32Array(ForVertex); |
| 1538 |
Len := Length(A); |
| 1539 |
Field.Count := Len; |
| 1540 |
if Len <> 0 then |
| 1541 |
Move(A[0], Field.Items.L[0], SizeOf(Int32) * Len); |
| 1542 |
end; |
| 1543 |
end; |
| 1544 |
|
| 1545 |
procedure AccessorToFloat(const AccessorIndex: Integer; const Field: TMFFloat; const ForVertex: Boolean); |
| 1546 |
var |
| 1547 |
Accessor: TPasGLTF.TAccessor; |
| 1548 |
A: TPasGLTFFloatDynamicArray; |
| 1549 |
Len: Integer; |
| 1550 |
begin |
| 1551 |
Accessor := GetAccessor(AccessorIndex); |
| 1552 |
if Accessor <> nil then |
| 1553 |
begin |
| 1554 |
A := Accessor.DecodeAsFloatArray(ForVertex); |
| 1555 |
Len := Length(A); |
| 1556 |
Field.Count := Len; |
| 1557 |
if Len <> 0 then |
| 1558 |
// Both glTF and X3D call it "Float", it is "Single" in Pascal |
| 1559 |
Move(A[0], Field.Items.L[0], SizeOf(Single) * Len); |
| 1560 |
end; |
| 1561 |
end; |
| 1562 |
|
| 1563 |
procedure AccessorToVector2(const AccessorIndex: Integer; const Field: TMFVec2f; const ForVertex: Boolean); |
| 1564 |
var |
| 1565 |
Accessor: TPasGLTF.TAccessor; |
| 1566 |
A: TPasGLTF.TVector2DynamicArray; |
| 1567 |
Len: Integer; |
| 1568 |
begin |
| 1569 |
Accessor := GetAccessor(AccessorIndex); |
| 1570 |
if Accessor <> nil then |
| 1571 |
begin |
| 1572 |
A := Accessor.DecodeAsVector2Array(ForVertex); |
| 1573 |
Len := Length(A); |
| 1574 |
Field.Count := Len; |
| 1575 |
if Len <> 0 then |
| 1576 |
Move(A[0], Field.Items.L[0], SizeOf(TVector2) * Len); |
| 1577 |
end; |
| 1578 |
end; |
| 1579 |
|
| 1580 |
procedure AccessorToVector3(const AccessorIndex: Integer; const Field: TMFVec3f; const ForVertex: Boolean); |
| 1581 |
var |
| 1582 |
Accessor: TPasGLTF.TAccessor; |
| 1583 |
A: TPasGLTF.TVector3DynamicArray; |
| 1584 |
Len: Integer; |
| 1585 |
begin |
| 1586 |
Accessor := GetAccessor(AccessorIndex); |
| 1587 |
if Accessor <> nil then |
| 1588 |
begin |
| 1589 |
A := Accessor.DecodeAsVector3Array(ForVertex); |
| 1590 |
Len := Length(A); |
| 1591 |
Field.Count := Len; |
| 1592 |
if Len <> 0 then |
| 1593 |
Move(A[0], Field.Items.L[0], SizeOf(TVector3) * Len); |
| 1594 |
end; |
| 1595 |
end; |
| 1596 |
|
| 1597 |
procedure AccessorToVector4(const AccessorIndex: Integer; const Field: TVector4List; |
| 1598 |
const ForVertex: Boolean); overload; |
| 1599 |
var |
| 1600 |
Accessor: TPasGLTF.TAccessor; |
| 1601 |
A: TPasGLTF.TVector4DynamicArray; |
| 1602 |
Len: Integer; |
| 1603 |
begin |
| 1604 |
Accessor := GetAccessor(AccessorIndex); |
| 1605 |
if Accessor <> nil then |
| 1606 |
begin |
| 1607 |
A := Accessor.DecodeAsVector4Array(ForVertex); |
| 1608 |
Len := Length(A); |
| 1609 |
Field.Count := Len; |
| 1610 |
if Len <> 0 then |
| 1611 |
Move(A[0], Field.L[0], SizeOf(TVector4) * Len); |
| 1612 |
end; |
| 1613 |
end; |
| 1614 |
|
| 1615 |
procedure AccessorToVector4(const AccessorIndex: Integer; const Field: TMFVec4f; |
| 1616 |
const ForVertex: Boolean); overload; |
| 1617 |
begin |
| 1618 |
AccessorToVector4(AccessorIndex, Field.Items, ForVertex); |
| 1619 |
end; |
| 1620 |
|
| 1621 |
procedure AccessorToVector4Integer(const AccessorIndex: Integer; const Field: TVector4IntegerList; const ForVertex: Boolean); |
| 1622 |
var |
| 1623 |
Accessor: TPasGLTF.TAccessor; |
| 1624 |
A: TPasGLTF.TInt32Vector4DynamicArray; |
| 1625 |
Len: Integer; |
| 1626 |
begin |
| 1627 |
Accessor := GetAccessor(AccessorIndex); |
| 1628 |
if Accessor <> nil then |
| 1629 |
begin |
| 1630 |
A := Accessor.DecodeAsInt32Vector4Array(ForVertex); |
| 1631 |
Len := Length(A); |
| 1632 |
Field.Count := Len; |
| 1633 |
if Len <> 0 then |
| 1634 |
Move(A[0], Field.L[0], SizeOf(TVector4Integer) * Len); |
| 1635 |
end; |
| 1636 |
end; |
| 1637 |
|
| 1638 |
procedure AccessorToMatrix4(const AccessorIndex: Integer; const List: TMatrix4List; const ForVertex: Boolean); |
| 1639 |
var |
| 1640 |
Accessor: TPasGLTF.TAccessor; |
| 1641 |
A: TPasGLTF.TMatrix4x4DynamicArray; |
| 1642 |
Len: Integer; |
| 1643 |
begin |
| 1644 |
Accessor := GetAccessor(AccessorIndex); |
| 1645 |
if Accessor <> nil then |
| 1646 |
begin |
| 1647 |
A := Accessor.DecodeAsMatrix4x4Array(ForVertex); |
| 1648 |
Len := Length(A); |
| 1649 |
List.Count := Len; |
| 1650 |
if Len <> 0 then |
| 1651 |
Move(A[0], List.L[0], SizeOf(TMatrix4) * Len); |
| 1652 |
end; |
| 1653 |
end; |
| 1654 |
|
| 1655 |
procedure AccessorToRotation(const AccessorIndex: Integer; const Field: TMFRotation; const ForVertex: Boolean; |
| 1656 |
const ReturnQuaternions: Boolean); |
| 1657 |
var |
| 1658 |
Accessor: TPasGLTF.TAccessor; |
| 1659 |
A: TPasGLTF.TVector4DynamicArray; |
| 1660 |
Len, I: Integer; |
| 1661 |
begin |
| 1662 |
Accessor := GetAccessor(AccessorIndex); |
| 1663 |
if Accessor <> nil then |
| 1664 |
begin |
| 1665 |
A := Accessor.DecodeAsVector4Array(ForVertex); |
| 1666 |
Len := Length(A); |
| 1667 |
Field.Count := Len; |
| 1668 |
if ReturnQuaternions then |
| 1669 |
begin |
| 1670 |
{ Return exact quaternions, without converting to axis-angle. |
| 1671 |
This will cooperate with TOrientationInterpolatorNode.KeyValueQuaternions. } |
| 1672 |
for I := 0 to Len - 1 do |
| 1673 |
Field.Items.L[I] := Vector4FromGltf(A[I]); |
| 1674 |
end else |
| 1675 |
begin |
| 1676 |
// convert glTF rotation to X3D |
| 1677 |
for I := 0 to Len - 1 do |
| 1678 |
Field.Items.L[I] := RotationFromGltf(A[I]); |
| 1679 |
end; |
| 1680 |
end; |
| 1681 |
end; |
| 1682 |
|
| 1683 |
{ Set SingleTexCoord as a texture coordinate. |
| 1684 |
Sets up TexCoordField as a TMultiTextureCoordinateNode instance, |
| 1685 |
in case we have multiple texture coordinates. } |
| 1686 |
procedure SetMultiTextureCoordinate(const Geometry: TAbstractGeometryNode; |
| 1687 |
const SingleTexCoord: TTextureCoordinateNode); |
| 1688 |
var |
| 1689 |
TexCoordField: TSFNode; |
| 1690 |
MultiTexCoord: TMultiTextureCoordinateNode; |
| 1691 |
begin |
| 1692 |
TexCoordField := Geometry.TexCoordField; |
| 1693 |
|
| 1694 |
if TexCoordField.Value <> nil then |
| 1695 |
{ only this procedure modifies this field, |
| 1696 |
so it has to be TMultiTextureCoordinateNode if assigned. } |
| 1697 |
MultiTexCoord := TexCoordField.Value as TMultiTextureCoordinateNode |
| 1698 |
else |
| 1699 |
begin |
| 1700 |
MultiTexCoord := TMultiTextureCoordinateNode.Create; |
| 1701 |
TexCoordField.Value := MultiTexCoord; |
| 1702 |
end; |
| 1703 |
|
| 1704 |
if Geometry.FindTextureMapping(SingleTexCoord.Mapping, false) <> nil then |
| 1705 |
WritelnWarning('Texture coordinate "%s" specified multiple times for the same glTF mesh', [ |
| 1706 |
SingleTexCoord.Mapping |
| 1707 |
]); |
| 1708 |
|
| 1709 |
MultiTexCoord.FdTexCoord.Add(SingleTexCoord); |
| 1710 |
end; |
| 1711 |
|
| 1712 |
procedure FlipTextureCoordinates(const TexCoord: TVector2SingleList); |
| 1713 |
var |
| 1714 |
I: Integer; |
| 1715 |
begin |
| 1716 |
for I := 0 to TexCoord.Count - 1 do |
| 1717 |
TexCoord.L[I].Y := 1 - TexCoord.L[I].Y; |
| 1718 |
end; |
| 1719 |
|
| 1720 |
function PossiblyLitGeometry(const Geometry: TAbstractGeometryNode): Boolean; |
| 1721 |
begin |
| 1722 |
Result := not ( |
| 1723 |
(Geometry is TPointSetNode) or |
| 1724 |
(Geometry is TIndexedLineSetNode) or |
| 1725 |
(Geometry is TLineSetNode) |
| 1726 |
); |
| 1727 |
end; |
| 1728 |
|
| 1729 |
procedure ReadPrimitive(const Primitive: TPasGLTF.TMesh.TPrimitive; |
| 1730 |
const ParentGroup: TGroupNode); |
| 1731 |
var |
| 1732 |
AttributeName: TPasGLTFUTF8String; |
| 1733 |
Shape: TShapeNode; |
| 1734 |
Geometry: TAbstractGeometryNode; |
| 1735 |
Coord: TCoordinateNode; |
| 1736 |
TexCoord: TTextureCoordinateNode; |
| 1737 |
Normal: TNormalNode; |
| 1738 |
Tangent: TTangentNode; |
| 1739 |
Color: TColorNode; |
| 1740 |
ColorRGBA: TColorRGBANode; |
| 1741 |
ColorAccessor: TPasGLTF.TAccessor; |
| 1742 |
IndexField: TMFLong; |
| 1743 |
Appearance: TGltfAppearanceNode; |
| 1744 |
Tangent4D: TVector4List; |
| 1745 |
MetadataCollision: String; |
| 1746 |
begin |
| 1747 |
// create X3D geometry and shape nodes |
| 1748 |
if Primitive.Indices <> -1 then |
| 1749 |
begin |
| 1750 |
case Primitive.Mode of |
| 1751 |
// TODO: We don't have indexed points in X3D. |
| 1752 |
TPasGLTF.TMesh.TPrimitive.TMode.Points : Geometry := TPointSetNode.CreateWithShape(Shape); |
| 1753 |
TPasGLTF.TMesh.TPrimitive.TMode.Lines : |
| 1754 |
begin |
| 1755 |
Geometry := TIndexedLineSetNode.CreateWithShape(Shape); |
| 1756 |
TIndexedLineSetNode(Geometry).Mode := lmPair; |
| 1757 |
end; |
| 1758 |
TPasGLTF.TMesh.TPrimitive.TMode.LineLoop : |
| 1759 |
begin |
| 1760 |
Geometry := TIndexedLineSetNode.CreateWithShape(Shape); |
| 1761 |
TIndexedLineSetNode(Geometry).Mode := lmLoop; |
| 1762 |
end; |
| 1763 |
TPasGLTF.TMesh.TPrimitive.TMode.LineStrip : Geometry := TIndexedLineSetNode.CreateWithShape(Shape); |
| 1764 |
TPasGLTF.TMesh.TPrimitive.TMode.Triangles : Geometry := TIndexedTriangleSetNode.CreateWithShape(Shape); |
| 1765 |
TPasGLTF.TMesh.TPrimitive.TMode.TriangleStrip: Geometry := TIndexedTriangleStripSetNode.CreateWithShape(Shape); |
| 1766 |
TPasGLTF.TMesh.TPrimitive.TMode.TriangleFan : Geometry := TIndexedTriangleFanSetNode.CreateWithShape(Shape); |
| 1767 |
else |
| 1768 |
begin |
| 1769 |
WritelnWarning('glTF', 'Primitive mode not implemented (in indexed mode): ' + PrimitiveModeToStr(Primitive.Mode)); |
| 1770 |
Exit; |
| 1771 |
end; |
| 1772 |
end; |
| 1773 |
end else |
| 1774 |
begin |
| 1775 |
case Primitive.Mode of |
| 1776 |
TPasGLTF.TMesh.TPrimitive.TMode.Points : Geometry := TPointSetNode.CreateWithShape(Shape); |
| 1777 |
TPasGLTF.TMesh.TPrimitive.TMode.Lines : |
| 1778 |
begin |
| 1779 |
Geometry := TLineSetNode.CreateWithShape(Shape); |
| 1780 |
TLineSetNode(Geometry).Mode := lmPair; |
| 1781 |
end; |
| 1782 |
TPasGLTF.TMesh.TPrimitive.TMode.LineLoop : |
| 1783 |
begin |
| 1784 |
Geometry := TLineSetNode.CreateWithShape(Shape); |
| 1785 |
TLineSetNode(Geometry).Mode := lmLoop; |
| 1786 |
end; |
| 1787 |
TPasGLTF.TMesh.TPrimitive.TMode.LineStrip : Geometry := TLineSetNode.CreateWithShape(Shape); |
| 1788 |
TPasGLTF.TMesh.TPrimitive.TMode.Triangles : Geometry := TTriangleSetNode.CreateWithShape(Shape); |
| 1789 |
TPasGLTF.TMesh.TPrimitive.TMode.TriangleStrip: Geometry := TTriangleStripSetNode.CreateWithShape(Shape); |
| 1790 |
TPasGLTF.TMesh.TPrimitive.TMode.TriangleFan : Geometry := TTriangleFanSetNode.CreateWithShape(Shape); |
| 1791 |
else |
| 1792 |
begin |
| 1793 |
WritelnWarning('glTF', 'Primitive mode not implemented (in non-indexed) mode: ' + PrimitiveModeToStr(Primitive.Mode)); |
| 1794 |
Exit; |
| 1795 |
end; |
| 1796 |
end; |
| 1797 |
end; |
| 1798 |
|
| 1799 |
Appearance := nil; // may be used in "except" clause, so make sure it is defined |
| 1800 |
|
| 1801 |
try |
| 1802 |
{ We need to name shape nodes, to later have unique names for interpolators. } |
| 1803 |
Shape.X3DName := |
| 1804 |
{ mesh name } ParentGroup.X3DName + |
| 1805 |
{ primitive index } '_Primitive' + IntToStr(ParentGroup.FdChildren.Count); |
| 1806 |
|
| 1807 |
// read indexes |
| 1808 |
IndexField := Geometry.CoordIndexField; |
| 1809 |
if IndexField <> nil then |
| 1810 |
begin |
| 1811 |
Assert(Primitive.Indices <> -1); |
| 1812 |
AccessorToInt32(Primitive.Indices, IndexField, false); |
| 1813 |
end; |
| 1814 |
|
| 1815 |
// parse attributes (initializing Coord, TexCoord and other such nodes) |
| 1816 |
// TODO: ForVertex true for all, or just for POSITION? |
| 1817 |
for AttributeName in Primitive.Attributes.Keys do |
| 1818 |
begin |
| 1819 |
if (AttributeName = 'POSITION') and (Geometry.CoordField <> nil) then |
| 1820 |
begin |
| 1821 |
Coord := TCoordinateNode.Create; |
| 1822 |
AccessorToVector3(Primitive.Attributes[AttributeName], Coord.FdPoint, true); |
| 1823 |
Geometry.CoordField.Value := Coord; |
| 1824 |
Shape.BBox := TBox3D.FromPoints(Coord.FdPoint.Items); |
| 1825 |
{ Do special fix for line strip and line loop: glTF specifies just one strip/loop, |
| 1826 |
put it in VertexCount. } |
| 1827 |
if (Geometry is TLineSetNode) and |
| 1828 |
(TLineSetNode(Geometry).Mode in [lmStrip, lmLoop]) then |
| 1829 |
TLineSetNode(Geometry).SetVertexCount([Coord.FdPoint.Count]); |
| 1830 |
end else |
| 1831 |
if IsPrefix('TEXCOORD_', AttributeName, false) and (Geometry.TexCoordField <> nil) then |
| 1832 |
begin |
| 1833 |
TexCoord := TTextureCoordinateNode.Create; |
| 1834 |
TexCoord.Mapping := AttributeName; |
| 1835 |
AccessorToVector2(Primitive.Attributes[AttributeName], TexCoord.FdPoint, false); |
| 1836 |
{ We prefer to flip the texture, using TImageTextureNode.FlipVertically, |
| 1837 |
and not make a (slower) flipping of texture coordinates. |
| 1838 |
But when CastleX3dExtensions = false, we have no other choice right now but to flip them. } |
| 1839 |
if not CastleX3dExtensions then |
| 1840 |
FlipTextureCoordinates(TexCoord.FdPoint.Items); |
| 1841 |
SetMultiTextureCoordinate(Geometry, TexCoord); |
| 1842 |
end else |
| 1843 |
if (AttributeName = 'NORMAL') and (Geometry is TAbstractComposedGeometryNode) then |
| 1844 |
begin |
| 1845 |
Normal := TNormalNode.Create; |
| 1846 |
AccessorToVector3(Primitive.Attributes[AttributeName], Normal.FdVector, false); |
| 1847 |
TAbstractComposedGeometryNode(Geometry).FdNormal.Value := Normal; |
| 1848 |
end else |
| 1849 |
if (AttributeName = 'COLOR_0') and (Geometry.ColorField <> nil) then |
| 1850 |
begin |
| 1851 |
ColorAccessor := GetAccessor(Primitive.Attributes[AttributeName]); |
| 1852 |
if ColorAccessor.Type_ = TPasGLTF.TAccessor.TType.Vec4 then |
| 1853 |
begin |
| 1854 |
ColorRGBA := TColorRGBANode.Create; |
| 1855 |
ColorRGBA.Mode := cmModulate; |
| 1856 |
AccessorToVector4(Primitive.Attributes[AttributeName], ColorRGBA.FdColor, false); |
| 1857 |
Geometry.ColorField.Value := ColorRGBA; |
| 1858 |
end else |
| 1859 |
begin |
| 1860 |
Color := TColorNode.Create; |
| 1861 |
Color.Mode := cmModulate; |
| 1862 |
AccessorToVector3(Primitive.Attributes[AttributeName], Color.FdColor, false); |
| 1863 |
Geometry.ColorField.Value := Color; |
| 1864 |
end; |
| 1865 |
end else |
| 1866 |
if (AttributeName = 'TANGENT') and (Geometry is TAbstractComposedGeometryNode) then |
| 1867 |
begin |
| 1868 |
if CastleX3dExtensions then |
| 1869 |
begin |
| 1870 |
Tangent := TTangentNode.Create; |
| 1871 |
Tangent4D := TVector4List.Create; |
| 1872 |
try |
| 1873 |
AccessorToVector4(Primitive.Attributes[AttributeName], Tangent4D, false); |
| 1874 |
Tangent.SetVector4D(Tangent4D); |
| 1875 |
finally FreeAndNil(Tangent4D) end; |
| 1876 |
TAbstractComposedGeometryNode(Geometry).FdTangent.Value := Tangent; |
| 1877 |
end; |
| 1878 |
end else |
| 1879 |
if (AttributeName = 'JOINTS_0') then |
| 1880 |
begin |
| 1881 |
Geometry.InternalSkinJoints := TVector4IntegerList.Create; |
| 1882 |
AccessorToVector4Integer(Primitive.Attributes[AttributeName], Geometry.InternalSkinJoints, false); |
| 1883 |
end else |
| 1884 |
if (AttributeName = 'WEIGHTS_0') then |
| 1885 |
begin |
| 1886 |
Geometry.InternalSkinWeights := TVector4List.Create; |
| 1887 |
AccessorToVector4(Primitive.Attributes[AttributeName], Geometry.InternalSkinWeights, false); |
| 1888 |
end else |
| 1889 |
WritelnLog('glTF', 'Ignoring vertex attribute ' + AttributeName + ', not implemented (for this primitive mode)'); |
| 1890 |
end; |
| 1891 |
|
| 1892 |
// determine Appearance |
| 1893 |
if Between(Primitive.Material, 0, Appearances.Count - 1) then |
| 1894 |
Appearance := Appearances[Primitive.Material] as TGltfAppearanceNode |
| 1895 |
else |
| 1896 |
begin |
| 1897 |
Appearance := DefaultAppearance; |
| 1898 |
if Primitive.Material <> -1 then |
| 1899 |
WritelnWarning('glTF', 'Primitive specifies invalid material index %d', |
| 1900 |
[Primitive.Material]); |
| 1901 |
end; |
| 1902 |
Appearance.Used := true; |
| 1903 |
Appearance.UsedAsLit := Appearance.UsedAsLit or PossiblyLitGeometry(Geometry); |
| 1904 |
Shape.Appearance := Appearance; |
| 1905 |
|
| 1906 |
// apply additional TGltfAppearanceNode parameters, specified in X3D at geometry |
| 1907 |
Geometry.Solid := not Appearance.DoubleSided; |
| 1908 |
|
| 1909 |
if CastleX3dExtensions then |
| 1910 |
Shape.GenerateTangents; |
| 1911 |
|
| 1912 |
MetadataCollision := ParentGroup.MetadataString['CastleCollision']; |
| 1913 |
if MetadataCollision = 'none' then |
| 1914 |
Shape.Collision := scNone |
| 1915 |
else |
| 1916 |
if MetadataCollision = 'box' then |
| 1917 |
Shape.Collision := scBox |
| 1918 |
else |
| 1919 |
if (MetadataCollision = '') or (MetadataCollision = 'default') then |
| 1920 |
Shape.Collision := scDefault |
| 1921 |
else |
| 1922 |
WritelnWarning('Invalid value for "CastleCollision" custom property, ignoring: %s', [MetadataCollision]); |
| 1923 |
|
| 1924 |
except |
| 1925 |
{ Free Shape, to not leak memory in case e.g. GenerateTangents |
| 1926 |
raises exception. |
| 1927 |
Protect Shape.Appearance from being freed, as it's shared in Appearances |
| 1928 |
array. } |
| 1929 |
if Appearance <> nil then |
| 1930 |
Appearance.KeepExistingBegin; |
| 1931 |
FreeAndNil(Shape); |
| 1932 |
if Appearance <> nil then |
| 1933 |
Appearance.KeepExistingEnd; |
| 1934 |
raise; |
| 1935 |
end; |
| 1936 |
|
| 1937 |
// add to X3D |
| 1938 |
ParentGroup.AddChildren(Shape); |
| 1939 |
ReadMetadata(Primitive.Extras, Shape); |
| 1940 |
end; |
| 1941 |
|
| 1942 |
procedure ReadMesh(const Mesh: TPasGLTF.TMesh; |
| 1943 |
const ParentGroup: TAbstractGroupingNode); overload; |
| 1944 |
var |
| 1945 |
Primitive: TPasGLTF.TMesh.TPrimitive; |
| 1946 |
Group: TGroupNode; |
| 1947 |
I: Integer; |
| 1948 |
begin |
| 1949 |
Group := TGroupNode.Create; |
| 1950 |
Group.X3DName := Mesh.Name; |
| 1951 |
{ Assign name to more easily recognize this in X3D output, |
| 1952 |
and to have unique names for TShapeNode, |
| 1953 |
which implies unique names for animations. |
| 1954 |
Testcase: Quaternius monster glTF models, |
| 1955 |
https://quaternius.com/packs/ultimatemonsters.html , |
| 1956 |
convert Bunny.gltf to X3D. |
| 1957 |
Should not make any warning. } |
| 1958 |
if Group.X3DName = '' then |
| 1959 |
Group.X3DName := 'Mesh' + IntToStr(ParentGroup.FdChildren.Count); |
| 1960 |
|
| 1961 |
ParentGroup.AddChildren(Group); |
| 1962 |
ExportNodes.Add(Group); |
| 1963 |
|
| 1964 |
ReadMetadata(Mesh.Extras, Group); |
| 1965 |
|
| 1966 |
for I := 0 to Mesh.Primitives.Count - 1 do |
| 1967 |
begin |
| 1968 |
Primitive := Mesh.Primitives[I]; |
| 1969 |
ReadPrimitive(Primitive, Group); |
| 1970 |
end; |
| 1971 |
end; |
| 1972 |
|
| 1973 |
procedure ReadMesh(const MeshIndex: Integer; |
| 1974 |
const ParentGroup: TAbstractGroupingNode); overload; |
| 1975 |
begin |
| 1976 |
if Between(MeshIndex, 0, Document.Meshes.Count - 1) then |
| 1977 |
ReadMesh(Document.Meshes[MeshIndex], ParentGroup) |
| 1978 |
else |
| 1979 |
WritelnWarning('glTF', 'Mesh index invalid: %d', [MeshIndex]); |
| 1980 |
end; |
| 1981 |
|
| 1982 |
procedure ReadCamera(const Camera: TPasGLTF.TCamera; |
| 1983 |
const ParentGroup: TAbstractGroupingNode); overload; |
| 1984 |
var |
| 1985 |
OrthoViewpoint: TOrthoViewpointNode; |
| 1986 |
Viewpoint: TViewpointNode; |
| 1987 |
begin |
| 1988 |
if Camera.Type_ = TPasGLTF.TCamera.TCameraType.Orthographic then |
| 1989 |
begin |
| 1990 |
OrthoViewpoint := TOrthoViewpointNode.Create; |
| 1991 |
OrthoViewpoint.X3DName := Camera.Name; |
| 1992 |
OrthoViewpoint.Position := TVector3.Zero; |
| 1993 |
if CastleX3dExtensions then |
| 1994 |
begin |
| 1995 |
OrthoViewpoint.AutoCenterOfRotation := true; |
| 1996 |
OrthoViewpoint.GravityTransform := false; |
| 1997 |
end; |
| 1998 |
ParentGroup.AddChildren(OrthoViewpoint); |
| 1999 |
|
| 2000 |
ReadMetadata(Camera.Extras, OrthoViewpoint); |
| 2001 |
|
| 2002 |
ExportNodes.Add(OrthoViewpoint); |
| 2003 |
end else |
| 2004 |
begin |
| 2005 |
Viewpoint := TViewpointNode.Create; |
| 2006 |
Viewpoint.X3DName := Camera.Name; |
| 2007 |
Viewpoint.Position := TVector3.Zero; |
| 2008 |
if Camera.Perspective.YFov <> 0 then |
| 2009 |
Viewpoint.FieldOfView := Camera.Perspective.YFov; |
| 2010 |
if CastleX3dExtensions then |
| 2011 |
begin |
| 2012 |
Viewpoint.AutoCenterOfRotation := true; |
| 2013 |
Viewpoint.GravityTransform := false; |
| 2014 |
end; |
| 2015 |
ParentGroup.AddChildren(Viewpoint); |
| 2016 |
|
| 2017 |
ReadMetadata(Camera.Extras, Viewpoint); |
| 2018 |
|
| 2019 |
ExportNodes.Add(Viewpoint); |
| 2020 |
end; |
| 2021 |
end; |
| 2022 |
|
| 2023 |
procedure ReadCamera(const CameraIndex: Integer; |
| 2024 |
const ParentGroup: TAbstractGroupingNode); overload; |
| 2025 |
begin |
| 2026 |
if Between(CameraIndex, 0, Document.Cameras.Count - 1) then |
| 2027 |
ReadCamera(Document.Cameras[CameraIndex], ParentGroup) |
| 2028 |
else |
| 2029 |
WritelnWarning('glTF', 'Camera index invalid: %d', [CameraIndex]); |
| 2030 |
end; |
| 2031 |
|
| 2032 |
procedure ReadNode(const NodeIndex: Integer; const ParentGroup: TAbstractGroupingNode); |
| 2033 |
var |
| 2034 |
Transform: TTransformNode; |
| 2035 |
|
| 2036 |
{ Apply Node.Skin, adding a new item to SkinsToInitialize list |
| 2037 |
and making the node collide as a box (otherwise every frame we would recalculate octree). } |
| 2038 |
procedure ApplySkin(const Skin: TPasGLTF.TSkin); |
| 2039 |
var |
| 2040 |
SkinToInitialize: TSkinToInitialize; |
| 2041 |
Shapes: TAbstractGroupingNode; |
| 2042 |
I: Integer; |
| 2043 |
ShapeNode: TShapeNode; |
| 2044 |
begin |
| 2045 |
SkinToInitialize := TSkinToInitialize.Create; |
| 2046 |
SkinsToInitialize.Add(SkinToInitialize); |
| 2047 |
// Shapes is the group created inside ReadMesh |
| 2048 |
Shapes := Transform.FdChildren.InternalItems.Last as TAbstractGroupingNode; |
| 2049 |
SkinToInitialize.Shapes := Shapes; |
| 2050 |
SkinToInitialize.ShapesParent := Transform; |
| 2051 |
SkinToInitialize.Skin := Skin; |
| 2052 |
|
| 2053 |
{ Make shapes collide as simple boxes. |
| 2054 |
We don't want to recalculate octree of their triangles each frame, |
| 2055 |
and their boxes are easy, since we fill shape's bbox. } |
| 2056 |
for I := 0 to Shapes.FdChildren.Count - 1 do |
| 2057 |
if Shapes.FdChildren[I] is TShapeNode then |
| 2058 |
begin |
| 2059 |
ShapeNode := TShapeNode(Shapes.FdChildren[I]); |
| 2060 |
ShapeNode.Collision := scBox; |
| 2061 |
end; |
| 2062 |
end; |
| 2063 |
|
| 2064 |
var |
| 2065 |
Node: TPasGLTF.TNode; |
| 2066 |
NodeMatrix: TMatrix4; |
| 2067 |
Translation, Scale: TVector3; |
| 2068 |
Rotation: TVector4; |
| 2069 |
ChildNodeIndex: Integer; |
| 2070 |
begin |
| 2071 |
if Between(NodeIndex, 0, Document.Nodes.Count - 1) then |
| 2072 |
begin |
| 2073 |
Node := Document.Nodes[NodeIndex]; |
| 2074 |
NodeMatrix := Matrix4FromGltf(Node.Matrix); |
| 2075 |
|
| 2076 |
if not TMatrix4.PerfectlyEquals(NodeMatrix, TMatrix4.Identity) then |
| 2077 |
begin |
| 2078 |
MatrixDecompose(NodeMatrix, Translation, Rotation, Scale); |
| 2079 |
end else |
| 2080 |
begin |
| 2081 |
Translation := Vector3FromGltf(Node.Translation); |
| 2082 |
Rotation := RotationFromGltf(Node.Rotation); |
| 2083 |
Scale := Vector3FromGltf(Node.Scale); |
| 2084 |
end; |
| 2085 |
|
| 2086 |
Transform := TTransformNode.Create; |
| 2087 |
Transform.X3DName := Node.Name; |
| 2088 |
{ Assign name to more easily recognize this in X3D output. } |
| 2089 |
if Transform.X3DName = '' then |
| 2090 |
Transform.X3DName := 'Node' + IntToStr(NodeIndex); |
| 2091 |
Transform.Translation := Translation; |
| 2092 |
Transform.Rotation := Rotation; |
| 2093 |
Transform.Scale := Scale; |
| 2094 |
ParentGroup.AddChildren(Transform); |
| 2095 |
|
| 2096 |
ReadMetadata(Node.Extras, Transform); |
| 2097 |
|
| 2098 |
if Node.Mesh <> -1 then |
| 2099 |
begin |
| 2100 |
ReadMesh(Node.Mesh, Transform); |
| 2101 |
|
| 2102 |
if Node.Skin <> -1 then |
| 2103 |
begin |
| 2104 |
if Between(Node.Skin, 0, Document.Skins.Count - 1) then |
| 2105 |
ApplySkin(Document.Skins[Node.Skin]) |
| 2106 |
else |
| 2107 |
WritelnWarning('glTF', 'Skin index invalid: %d', [Node.Skin]); |
| 2108 |
end; |
| 2109 |
end; |
| 2110 |
|
| 2111 |
if Node.Camera <> -1 then |
| 2112 |
ReadCamera(Node.Camera, Transform); |
| 2113 |
|
| 2114 |
Lights.ReadNode(Node, Transform); |
| 2115 |
|
| 2116 |
for ChildNodeIndex in Node.Children do |
| 2117 |
ReadNode(ChildNodeIndex, Transform); |
| 2118 |
|
| 2119 |
// add to Nodes list |
| 2120 |
Nodes.Count := Max(Nodes.Count, NodeIndex + 1); |
| 2121 |
if Nodes[NodeIndex] <> nil then |
| 2122 |
WritelnWarning('glTF', 'Node %d read multiple times (impossible if glTF is a strict tree)', [NodeIndex]) |
| 2123 |
else |
| 2124 |
Nodes[NodeIndex] := Transform; |
| 2125 |
end else |
| 2126 |
WritelnWarning('glTF', 'Node index invalid: %d', [NodeIndex]); |
| 2127 |
end; |
| 2128 |
|
| 2129 |
procedure ReadScene(const SceneIndex: Integer; const ParentGroup: TAbstractGroupingNode); |
| 2130 |
var |
| 2131 |
Scene: TPasGLTF.TScene; |
| 2132 |
NodeIndex: Integer; |
| 2133 |
begin |
| 2134 |
if Between(SceneIndex, 0, Document.Scenes.Count - 1) then |
| 2135 |
begin |
| 2136 |
Scene := Document.Scenes[SceneIndex]; |
| 2137 |
for NodeIndex in Scene.Nodes do |
| 2138 |
ReadNode(NodeIndex, ParentGroup); |
| 2139 |
AnimationSampler.TransformNodesRoots := Scene.Nodes; |
| 2140 |
end else |
| 2141 |
WritelnWarning('glTF', 'Scene index invalid: %d', [SceneIndex]); |
| 2142 |
end; |
| 2143 |
|
| 2144 |
function ReadSampler(const Sampler: TPasGLTF.TAnimation.TSampler; |
| 2145 |
const Node: TTransformNode; |
| 2146 |
const Path: TGltfSamplerPath; |
| 2147 |
const TimeSensor: TTimeSensorNode; |
| 2148 |
const ParentGroup: TAbstractGroupingNode; |
| 2149 |
out Duration: TFloatTime): TAbstractInterpolatorNode; |
| 2150 |
var |
| 2151 |
InterpolatePosition: TPositionInterpolatorNode; |
| 2152 |
InterpolateOrientation: TOrientationInterpolatorNode; |
| 2153 |
Interpolator: TAbstractInterpolatorNode; |
| 2154 |
InterpolatorOutputEvent: TX3DEvent; |
| 2155 |
TargetField: TX3DField; |
| 2156 |
I: Integer; |
| 2157 |
begin |
| 2158 |
// silence Delphi warnings |
| 2159 |
InterpolatePosition := nil; |
| 2160 |
InterpolateOrientation := nil; |
| 2161 |
|
| 2162 |
case Path of |
| 2163 |
gsTranslation, gsScale: |
| 2164 |
begin |
| 2165 |
InterpolatePosition := TPositionInterpolatorNode.Create; |
| 2166 |
Interpolator := InterpolatePosition; |
| 2167 |
InterpolatorOutputEvent := InterpolatePosition.EventValue_changed; |
| 2168 |
AccessorToVector3(Sampler.Output, InterpolatePosition.FdKeyValue, false); |
| 2169 |
case Path of |
| 2170 |
gsTranslation: TargetField := Node.FdTranslation; |
| 2171 |
gsScale : TargetField := Node.FdScale; |
| 2172 |
else raise EInternalError.Create('ReadSampler vector3 - Path?'); |
| 2173 |
end; |
| 2174 |
end; |
| 2175 |
gsRotation: |
| 2176 |
begin |
| 2177 |
InterpolateOrientation := TOrientationInterpolatorNode.Create; |
| 2178 |
Interpolator := InterpolateOrientation; |
| 2179 |
InterpolatorOutputEvent := InterpolateOrientation.EventValue_changed; |
| 2180 |
AccessorToRotation(Sampler.Output, InterpolateOrientation.FdKeyValue, false, CastleX3dExtensions); |
| 2181 |
InterpolateOrientation.KeyValueQuaternions := CastleX3dExtensions; |
| 2182 |
TargetField := Node.FdRotation; |
| 2183 |
end; |
| 2184 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2185 |
else raise EInternalError.Create('ReadSampler - Path?'); |
| 2186 |
{$endif} |
| 2187 |
end; |
| 2188 |
|
| 2189 |
{ Put both Node.X3DName and TargetField.X3DName into Interpolator.X3DName. |
| 2190 |
We create new interpolator for each target node (Transform) and field |
| 2191 |
(like translation, rotation...) so we want to generate unique names for them |
| 2192 |
(if animation names in glTF were unique). } |
| 2193 |
Interpolator.X3DName := 'Animate_' + TimeSensor.X3DName + '_' + Node.X3DName + '_' + TargetField.X3DName; |
| 2194 |
|
| 2195 |
AccessorToFloat(Sampler.Input, Interpolator.FdKey, false); |
| 2196 |
if Interpolator.FdKey.Count <> 0 then |
| 2197 |
Duration := Interpolator.FdKey.Items.Last |
| 2198 |
else |
| 2199 |
Duration := 0; |
| 2200 |
|
| 2201 |
ParentGroup.AddChildren(Interpolator); |
| 2202 |
|
| 2203 |
ParentGroup.AddRoute(TimeSensor.EventFraction_changed, Interpolator.EventSet_fraction); |
| 2204 |
ParentGroup.AddRoute(InterpolatorOutputEvent, TargetField); |
| 2205 |
|
| 2206 |
Result := Interpolator; |
| 2207 |
|
| 2208 |
// take into account Interpolation |
| 2209 |
case Sampler.Interpolation of |
| 2210 |
TPasGLTF.TAnimation.TSampler.TSamplerType.Linear: ; // nothing to do |
| 2211 |
TPasGLTF.TAnimation.TSampler.TSamplerType.Step: |
| 2212 |
Interpolator.Interpolation := inStep; |
| 2213 |
TPasGLTF.TAnimation.TSampler.TSamplerType.CubicSpline: |
| 2214 |
begin |
| 2215 |
// May spam too much. Assume that our current approximation is good enough. |
| 2216 |
// WritelnWarning('Animation interpolation "CubicSpline" not supported yet, approximating by "Linear"'); |
| 2217 |
case Path of |
| 2218 |
gsTranslation, gsScale: |
| 2219 |
begin |
| 2220 |
if InterpolatePosition.FdKeyValue.Count <> |
| 2221 |
InterpolatePosition.FdKey.Count * 3 then |
| 2222 |
begin |
| 2223 |
WritelnWarning('For "CubicSpline", expected 3 output values for each input time, got %d for %d', [ |
| 2224 |
InterpolatePosition.FdKeyValue.Count, |
| 2225 |
InterpolatePosition.FdKey.Count |
| 2226 |
]); |
| 2227 |
Exit; |
| 2228 |
end; |
| 2229 |
for I := 0 to InterpolatePosition.FdKeyValue.Count div 3 - 1 do |
| 2230 |
InterpolatePosition.FdKeyValue.Items[I] := |
| 2231 |
InterpolatePosition.FdKeyValue.Items[3 * I + 1]; |
| 2232 |
InterpolatePosition.FdKeyValue.Count := InterpolatePosition.FdKeyValue.Count div 3; |
| 2233 |
end; |
| 2234 |
gsRotation: |
| 2235 |
begin |
| 2236 |
if InterpolateOrientation.FdKeyValue.Count <> |
| 2237 |
InterpolateOrientation.FdKey.Count * 3 then |
| 2238 |
begin |
| 2239 |
WritelnWarning('For "CubicSpline", expected 3 output values for each input time, got %d for %d', [ |
| 2240 |
InterpolateOrientation.FdKeyValue.Count, |
| 2241 |
InterpolateOrientation.FdKey.Count |
| 2242 |
]); |
| 2243 |
Exit; |
| 2244 |
end; |
| 2245 |
for I := 0 to InterpolateOrientation.FdKeyValue.Count div 3 - 1 do |
| 2246 |
InterpolateOrientation.FdKeyValue.Items[I] := |
| 2247 |
InterpolateOrientation.FdKeyValue.Items[3 * I + 1]; |
| 2248 |
InterpolateOrientation.FdKeyValue.Count := InterpolateOrientation.FdKeyValue.Count div 3; |
| 2249 |
end; |
| 2250 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2251 |
else raise EInternalError.Create('ReadSampler - Path?'); |
| 2252 |
{$endif} |
| 2253 |
end; |
| 2254 |
end; |
| 2255 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2256 |
else |
| 2257 |
begin |
| 2258 |
WritelnWarning('Given animation interpolation is not supported'); |
| 2259 |
end; |
| 2260 |
{$endif} |
| 2261 |
end; |
| 2262 |
end; |
| 2263 |
|
| 2264 |
procedure ReadAnimation(const Animation: TPasGLTF.TAnimation; const ParentGroup: TAbstractGroupingNode); |
| 2265 |
var |
| 2266 |
TimeSensor: TTimeSensorNode; |
| 2267 |
Channel: TPasGLTF.TAnimation.TChannel; |
| 2268 |
Sampler: TPasGLTF.TAnimation.TSampler; |
| 2269 |
Node: TTransformNode; |
| 2270 |
Duration, MaxDuration: TFloatTime; |
| 2271 |
Interpolator: TAbstractInterpolatorNode; |
| 2272 |
NodeIndex, I: Integer; |
| 2273 |
Anim: TAnimation; |
| 2274 |
InterpolatorRec: TInterpolator; |
| 2275 |
Path: TGltfSamplerPath; |
| 2276 |
begin |
| 2277 |
Anim := TAnimation.Create; |
| 2278 |
Animations.Add(Anim); |
| 2279 |
|
| 2280 |
TimeSensor := TTimeSensorNode.Create; |
| 2281 |
if Animation.Name = '' then |
| 2282 |
{ Needs a name, otherwise TCastleSceneCore.AnimationsList would ignore it. } |
| 2283 |
TimeSensor.X3DName := 'unnamed' |
| 2284 |
else |
| 2285 |
TimeSensor.X3DName := Animation.Name; |
| 2286 |
ParentGroup.AddChildren(TimeSensor); |
| 2287 |
Anim.TimeSensor := TimeSensor; |
| 2288 |
|
| 2289 |
MaxDuration := 0; |
| 2290 |
for Channel in Animation.Channels do |
| 2291 |
begin |
| 2292 |
NodeIndex := Channel.Target.Node; |
| 2293 |
|
| 2294 |
// glTF spec says "When node isn't defined, channel should be ignored" |
| 2295 |
if NodeIndex = -1 then |
| 2296 |
Continue; |
| 2297 |
|
| 2298 |
if not (Between(NodeIndex, 0, Nodes.Count - 1) and (Nodes[NodeIndex] <> nil)) then |
| 2299 |
begin |
| 2300 |
WritelnWarning('Node index %d indicated by animation %s was not imported', [ |
| 2301 |
NodeIndex, |
| 2302 |
TimeSensor.X3DName |
| 2303 |
]); |
| 2304 |
Continue; |
| 2305 |
end; |
| 2306 |
|
| 2307 |
Node := Nodes[NodeIndex] as TTransformNode; |
| 2308 |
|
| 2309 |
// read Sampler |
| 2310 |
if not Between(Channel.Sampler, 0, Animation.Samplers.Count - 1) then |
| 2311 |
begin |
| 2312 |
WritelnWarning('Invalid animation "%s" sampler index %d', [ |
| 2313 |
TimeSensor.X3DName, |
| 2314 |
Channel.Sampler |
| 2315 |
]); |
| 2316 |
Continue; |
| 2317 |
end; |
| 2318 |
|
| 2319 |
Sampler := Animation.Samplers[Channel.Sampler]; |
| 2320 |
|
| 2321 |
// read channel Path |
| 2322 |
if Channel.Target.Path = 'translation' then |
| 2323 |
Path := gsTranslation |
| 2324 |
else |
| 2325 |
if Channel.Target.Path = 'rotation' then |
| 2326 |
Path := gsRotation |
| 2327 |
else |
| 2328 |
if Channel.Target.Path = 'scale' then |
| 2329 |
Path := gsScale |
| 2330 |
else |
| 2331 |
begin |
| 2332 |
WritelnWarning('Animating "%s" not supported', [Channel.Target.Path]); |
| 2333 |
Continue; |
| 2334 |
end; |
| 2335 |
|
| 2336 |
// call ReadSampler with all information |
| 2337 |
Interpolator := ReadSampler(Sampler, Node, Path, TimeSensor, ParentGroup, Duration); |
| 2338 |
|
| 2339 |
// extend Anim.Interpolators list |
| 2340 |
InterpolatorRec.Node := Interpolator; |
| 2341 |
InterpolatorRec.Target := Node; |
| 2342 |
InterpolatorRec.Path := Path; |
| 2343 |
Anim.Interpolators.Add(InterpolatorRec); |
| 2344 |
|
| 2345 |
MaxDuration := Max(MaxDuration, Duration); |
| 2346 |
end; |
| 2347 |
|
| 2348 |
// adjust TimeSensor duration, scale the keys in all Interpolators to be in 0..1 range |
| 2349 |
if MaxDuration <> 0 then |
| 2350 |
begin |
| 2351 |
TimeSensor.CycleInterval := MaxDuration; |
| 2352 |
for I := 0 to Anim.Interpolators.Count - 1 do |
| 2353 |
begin |
| 2354 |
Interpolator := Anim.Interpolators[I].Node; |
| 2355 |
Interpolator.FdKey.Items.MultiplyAll(1 / MaxDuration); |
| 2356 |
end; |
| 2357 |
end; |
| 2358 |
end; |
| 2359 |
|
| 2360 |
{ Gather all key times (in 0..1 range) from Interpolators, place them in AllKeys. |
| 2361 |
If you have animation that uses multiple interpolators, |
| 2362 |
then this routine calculates *all* key points within this animation. } |
| 2363 |
procedure GatherAnimationKeysToSample(const AllKeys: TSingleList; |
| 2364 |
const Interpolators: TInterpolatorList); |
| 2365 |
var |
| 2366 |
I: Integer; |
| 2367 |
Interpolator: TAbstractInterpolatorNode; |
| 2368 |
begin |
| 2369 |
AllKeys.Clear; |
| 2370 |
for I := 0 to Interpolators.Count - 1 do |
| 2371 |
begin |
| 2372 |
Interpolator := Interpolators[I].Node; |
| 2373 |
AllKeys.AddRange(Interpolator.FdKey.Items); |
| 2374 |
end; |
| 2375 |
AllKeys.SortAndRemoveDuplicates; |
| 2376 |
end; |
| 2377 |
|
| 2378 |
{ Sample animation Anim at time TimeFraction (in 0..1 range) |
| 2379 |
to determine how does a skin look like at this moment of time. |
| 2380 |
OriginalCoords contains original (not animated) coords. |
| 2381 |
To the AnimatedCoords, we will add OriginalCoords.Count vertexes. |
| 2382 |
|
| 2383 |
We also add to AnimatedNormals if they are <> nil. |
| 2384 |
Both OriginalNormals and AnimatedNormals must be nil or both must be <> nil. |
| 2385 |
|
| 2386 |
Similarly, we also add AnimatedTangents if they are <> nil. |
| 2387 |
And both OriginalTangents and AnimatedTangents must be nil or both must be <> nil. |
| 2388 |
} |
| 2389 |
procedure SampleSkinAnimation(const Anim: TAnimation; const KeyIndex: Integer; |
| 2390 |
const TimeFraction: Single; |
| 2391 |
const OriginalCoords, AnimatedCoords: TVector3List; |
| 2392 |
const OriginalNormals, AnimatedNormals: TVector3List; |
| 2393 |
const OriginalTangents, AnimatedTangents: TVector3List; |
| 2394 |
const Joints: TX3DNodeList; const JointsGltf: TPasGLTF.TSkin.TJoints; |
| 2395 |
const InverseBindMatrices: TMatrix4List; |
| 2396 |
const SkeletonRootIndex: Integer; |
| 2397 |
const MeshJoints: TVector4IntegerList; |
| 2398 |
const MeshWeights: TVector4List); |
| 2399 |
var |
| 2400 |
I: Integer; |
| 2401 |
SkinMatrix, SkeletonRootInverse: TMatrix4; |
| 2402 |
VertexJoints: TVector4Integer; |
| 2403 |
VertexWeights: TVector4; |
| 2404 |
begin |
| 2405 |
Assert((AnimatedNormals = nil) = (OriginalNormals = nil)); |
| 2406 |
Assert((OriginalNormals = nil) or (OriginalNormals.Count = OriginalCoords.Count)); |
| 2407 |
Assert((AnimatedTangents = nil) = (OriginalTangents = nil)); |
| 2408 |
Assert((OriginalTangents = nil) or (OriginalTangents.Count = OriginalCoords.Count)); |
| 2409 |
|
| 2410 |
AnimationSampler.Animation := Anim; |
| 2411 |
AnimationSampler.SetTime(TimeFraction); |
| 2412 |
|
| 2413 |
if SkeletonRootIndex <> -1 then |
| 2414 |
SkeletonRootInverse := AnimationSampler.Transformations.L[SkeletonRootIndex].InverseTransform |
| 2415 |
else |
| 2416 |
SkeletonRootInverse := TMatrix4.Identity; |
| 2417 |
|
| 2418 |
{ For each Joint, we calculate JointMatrix following |
| 2419 |
https://www.slideshare.net/Khronos_Group/gltf-20-reference-guide } |
| 2420 |
for I := 0 to Joints.Count - 1 do |
| 2421 |
JointMatrix[I] := SkeletonRootInverse * |
| 2422 |
AnimationSampler.Transformations.L[JointsGltf[I]].Transform * |
| 2423 |
InverseBindMatrices[I]; |
| 2424 |
|
| 2425 |
{ For each vertex, calculate SkinMatrix as linear combination of JointMatrix[...] |
| 2426 |
for all joints indicated by MeshJoints values for this vertex. |
| 2427 |
TODO: Support JOINTS_1, WEIGHTS_1 etc. } |
| 2428 |
for I := 0 to OriginalCoords.Count - 1 do |
| 2429 |
begin |
| 2430 |
VertexWeights := MeshWeights[I]; |
| 2431 |
VertexJoints := MeshJoints[I]; |
| 2432 |
if VertexWeights.IsPerfectlyZero then |
| 2433 |
begin |
| 2434 |
{ Happens with glTF files generated by Blender. |
| 2435 |
This is not correct (glTF spec says that weights should sum to 1.0). |
| 2436 |
Solution that works: Transform it with weight 1 by the joint number 0 |
| 2437 |
(relying that Blender put root joint at this position). See |
| 2438 |
https://github.com/KhronosGroup/glTF/issues/1213 |
| 2439 |
https://github.com/KhronosGroup/glTF-Blender-IO/issues/308 |
| 2440 |
https://github.com/KhronosGroup/glTF-Blender-IO/issues/308#issuecomment-531355129 |
| 2441 |
"""it's not exactly a satisfying fix, but in practice using 1, 0, 0, 0 when the weights would otherwise be zero has avoided these issues in threejs.""" |
| 2442 |
https://github.com/KhronosGroup/glTF/pull/1352 |
| 2443 |
https://github.com/Franck-Dernoncourt/NeuroNER/issues/91 } |
| 2444 |
SkinMatrix := JointMatrix.L[0]; |
| 2445 |
end else |
| 2446 |
begin |
| 2447 |
SkinMatrix := |
| 2448 |
JointMatrix.L[VertexJoints.X] * VertexWeights.X + |
| 2449 |
JointMatrix.L[VertexJoints.Y] * VertexWeights.Y + |
| 2450 |
JointMatrix.L[VertexJoints.Z] * VertexWeights.Z + |
| 2451 |
JointMatrix.L[VertexJoints.W] * VertexWeights.W; |
| 2452 |
end; |
| 2453 |
{ Note: On Delphi, we *have to* use L[...] below and depend on $pointermath on, |
| 2454 |
instead of using List^[...]. |
| 2455 |
That's because on Delphi, List^[...] may have too small (declared) upper size |
| 2456 |
due to Delphi not supporting SizeOf(T) in generics. |
| 2457 |
See https://github.com/castle-engine/castle-engine/issues/474 . } |
| 2458 |
AnimatedCoords.L[KeyIndex * OriginalCoords.Count + I] := SkinMatrix.MultPoint(OriginalCoords[I]); |
| 2459 |
if AnimatedNormals <> nil then |
| 2460 |
AnimatedNormals.L[KeyIndex * OriginalNormals.Count + I] := SkinMatrix.MultDirection(OriginalNormals[I]); |
| 2461 |
if AnimatedTangents <> nil then |
| 2462 |
AnimatedTangents.L[KeyIndex * OriginalTangents.Count + I] := SkinMatrix.MultDirection(OriginalTangents[I]); |
| 2463 |
end; |
| 2464 |
end; |
| 2465 |
|
| 2466 |
{ When animation TimeSensor starts, set Shape.BBox using X3D routes. } |
| 2467 |
procedure SetBBoxWhenAnimationStarts(const TimeSensor: TTimeSensorNode; |
| 2468 |
const Shape: TShapeNode; const BBox: TBox3D; |
| 2469 |
const ParentGroup: TAbstractGroupingNode); |
| 2470 |
var |
| 2471 |
ValueTrigger: TValueTriggerNode; |
| 2472 |
Center, Size: TVector3; |
| 2473 |
F: TX3DField; |
| 2474 |
begin |
| 2475 |
BBox.ToCenterSize(Center, Size); |
| 2476 |
|
| 2477 |
ValueTrigger := TValueTriggerNode.Create; |
| 2478 |
ValueTrigger.X3DName := 'ValueTrigger_setBBox_' + |
| 2479 |
TimeSensor.X3DName + '_' + Shape.X3DName; |
| 2480 |
ParentGroup.AddChildren(ValueTrigger); |
| 2481 |
ParentGroup.AddRoute(TimeSensor.EventIsActive, ValueTrigger.EventTrigger); |
| 2482 |
|
| 2483 |
F := TSFVec3f.Create(nil, true, 'bboxCenter', Center); |
| 2484 |
ValueTrigger.AddCustomField(F); |
| 2485 |
ParentGroup.AddRoute(F, Shape.FdBboxCenter); |
| 2486 |
|
| 2487 |
F := TSFVec3f.Create(nil, true, 'bboxSize', Size); |
| 2488 |
ValueTrigger.AddCustomField(F); |
| 2489 |
ParentGroup.AddRoute(F, Shape.FdBboxSize); |
| 2490 |
end; |
| 2491 |
|
| 2492 |
function ShapeLit(const ShapeNode: TShapeNode): Boolean; |
| 2493 |
begin |
| 2494 |
Result := (ShapeNode.Appearance <> nil) and |
| 2495 |
( |
| 2496 |
(ShapeNode.Appearance.Material is TMaterialNode) or |
| 2497 |
(ShapeNode.Appearance.Material is TPhysicalMaterialNode) |
| 2498 |
); |
| 2499 |
end; |
| 2500 |
|
| 2501 |
{ Calculate skin interpolator nodes to deform this one shape. |
| 2502 |
|
| 2503 |
Note that ParentGroup can be really any grouping node, |
| 2504 |
we add there only interpolators and routes, it doesn't matter where this node is. } |
| 2505 |
procedure CalculateSkinInterpolators(const Shape: TShapeNode; |
| 2506 |
const Joints: TX3DNodeList; const JointsGltf: TPasGLTF.TSkin.TJoints; |
| 2507 |
const InverseBindMatrices: TMatrix4List; |
| 2508 |
const SkeletonRoot: TAbstractGroupingNode; const SkeletonRootIndex: Integer; |
| 2509 |
const ParentGroup: TAbstractGroupingNode); |
| 2510 |
var |
| 2511 |
CoordField: TSFNode; |
| 2512 |
Coord: TCoordinateNode; |
| 2513 |
Normal: TNormalNode; |
| 2514 |
Tangent: TTangentNode; |
| 2515 |
Anim: TAnimation; |
| 2516 |
CoordInterpolator: TCoordinateInterpolatorNode; |
| 2517 |
NormalInterpolator: TCoordinateInterpolatorNode; |
| 2518 |
TangentInterpolator: TCoordinateInterpolatorNode; |
| 2519 |
I: Integer; |
| 2520 |
OriginalNormals, AnimatedNormals: TVector3List; |
| 2521 |
OriginalTangents, AnimatedTangents: TVector3List; |
| 2522 |
MemoryTaken: Int64; |
| 2523 |
InterpolatorNameSuffix: String; |
| 2524 |
begin |
| 2525 |
CoordField := Shape.Geometry.CoordField; |
| 2526 |
if CoordField = nil then |
| 2527 |
begin |
| 2528 |
WritelnWarning('Cannot animate using skin geometry %s, it does not have coordinates', [ |
| 2529 |
Shape.Geometry.NiceName |
| 2530 |
]); |
| 2531 |
Exit; |
| 2532 |
end; |
| 2533 |
|
| 2534 |
if not (CoordField.Value is TCoordinateNode) then |
| 2535 |
begin |
| 2536 |
WritelnWarning('Cannot animate using skin geometry %s, the coordinates are not expressed as Coordinate node', [ |
| 2537 |
Shape.Geometry.NiceName |
| 2538 |
]); |
| 2539 |
Exit; |
| 2540 |
end; |
| 2541 |
Coord := CoordField.Value as TCoordinateNode; |
| 2542 |
|
| 2543 |
// calculate Normal |
| 2544 |
Normal := nil; |
| 2545 |
if (Shape.Geometry.NormalField <> nil) and |
| 2546 |
(Shape.Geometry.NormalField.Value is TNormalNode) then |
| 2547 |
begin |
| 2548 |
Normal := TNormalNode(Shape.Geometry.NormalField.Value); |
| 2549 |
// SampleSkinAnimation assumes that normals and coords counts are equal |
| 2550 |
if Normal.FdVector.Count <> Coord.FdPoint.Count then |
| 2551 |
begin |
| 2552 |
WritelnWarning('When animating using skin geometry %s, coords and normals counts different', [ |
| 2553 |
Shape.Geometry.NiceName |
| 2554 |
]); |
| 2555 |
Normal := nil; |
| 2556 |
end; |
| 2557 |
end else |
| 2558 |
begin |
| 2559 |
if ShapeLit(Shape) then |
| 2560 |
WritelnWarning('TODO: Normal vectors are not provided for a skinned geometry (using lit material), and in effect the resulting animation will be slow as we''ll recalculate normals more often than necessary. ' + 'For now it is adviced to generate glTF with normals included for skinned meshes.'); |
| 2561 |
end; |
| 2562 |
|
| 2563 |
// calculate Tangent |
| 2564 |
Tangent := nil; |
| 2565 |
if (Shape.Geometry.TangentField <> nil) and |
| 2566 |
(Shape.Geometry.TangentField.Value is TTangentNode) then |
| 2567 |
begin |
| 2568 |
Tangent := TTangentNode(Shape.Geometry.TangentField.Value); |
| 2569 |
// SampleSkinAnimation assumes that tangents and coords counts are equal |
| 2570 |
if Tangent.FdVector.Count <> Coord.FdPoint.Count then |
| 2571 |
begin |
| 2572 |
WritelnWarning('When animating using skin geometry %s, coords and tangents counts different', [ |
| 2573 |
Shape.Geometry.NiceName |
| 2574 |
]); |
| 2575 |
Tangent := nil; |
| 2576 |
end; |
| 2577 |
end else |
| 2578 |
begin |
| 2579 |
if ShapeLit(Shape) and |
| 2580 |
((Shape.Appearance.Material as TAbstractOneSidedMaterialNode).NormalTexture <> nil) then |
| 2581 |
WritelnWarning('TODO: Tangent vectors are not provided for a skinned geometry (using lit material with normalmap), and in effect the resulting animation will be slow as we''ll recalculate tangents more often than necessary. ' + 'For now it is adviced to generate glTF with tangents included for skinned meshes.'); |
| 2582 |
end; |
| 2583 |
|
| 2584 |
if (Shape.Geometry.InternalSkinJoints = nil) or |
| 2585 |
(Shape.Geometry.InternalSkinWeights = nil) then |
| 2586 |
begin |
| 2587 |
WritelnWarning('Cannot animate using skin geometry %s, no JOINTS_0 and WEIGHTS_0 information in the mesh', [ |
| 2588 |
Shape.Geometry.NiceName |
| 2589 |
]); |
| 2590 |
Exit; |
| 2591 |
end; |
| 2592 |
|
| 2593 |
for Anim in Animations do |
| 2594 |
begin |
| 2595 |
InterpolatorNameSuffix := |
| 2596 |
'SkinInterpolator_' |
| 2597 |
+ Anim.TimeSensor.X3DName + '_' |
| 2598 |
+ Shape.X3DName; |
| 2599 |
|
| 2600 |
CoordInterpolator := TCoordinateInterpolatorNode.Create; |
| 2601 |
CoordInterpolator.X3DName := 'Coord' + InterpolatorNameSuffix; |
| 2602 |
GatherAnimationKeysToSample(CoordInterpolator.FdKey.Items, Anim.Interpolators); |
| 2603 |
{ Assign count, avoids later reallocating memory when adding vectors (slow), |
| 2604 |
and avoids Capacity >> Count (wasted memory). |
| 2605 |
This is important on large models. |
| 2606 |
Testcase: mouse_multiple, |
| 2607 |
- memory use: 180 MB vs 140 MB on each animation of dancing |
| 2608 |
- loading time: 14 vs 10 sec total. } |
| 2609 |
CoordInterpolator.FdKeyValue.Count := CoordInterpolator.FdKey.Count * Coord.FdPoint.Count; |
| 2610 |
|
| 2611 |
ParentGroup.AddChildren(CoordInterpolator); |
| 2612 |
ParentGroup.AddRoute(Anim.TimeSensor.EventFraction_changed, CoordInterpolator.EventSet_fraction); |
| 2613 |
ParentGroup.AddRoute(CoordInterpolator.EventValue_changed, Coord.FdPoint); |
| 2614 |
|
| 2615 |
if Normal <> nil then |
| 2616 |
begin |
| 2617 |
NormalInterpolator := TCoordinateInterpolatorNode.Create; |
| 2618 |
NormalInterpolator.X3DName := 'Normal' + InterpolatorNameSuffix; |
| 2619 |
//GatherAnimationKeysToSample(NormalInterpolator.FdKey.Items, Anim.Interpolators); |
| 2620 |
// faster: |
| 2621 |
NormalInterpolator.FdKey.Assign(CoordInterpolator.FdKey); |
| 2622 |
NormalInterpolator.FdKeyValue.Count := NormalInterpolator.FdKey.Count * Normal.FdVector.Count; |
| 2623 |
|
| 2624 |
ParentGroup.AddChildren(NormalInterpolator); |
| 2625 |
ParentGroup.AddRoute(Anim.TimeSensor.EventFraction_changed, NormalInterpolator.EventSet_fraction); |
| 2626 |
ParentGroup.AddRoute(NormalInterpolator.EventValue_changed, Normal.FdVector); |
| 2627 |
|
| 2628 |
OriginalNormals := Normal.FdVector.Items; |
| 2629 |
AnimatedNormals := NormalInterpolator.FdKeyValue.Items; |
| 2630 |
end else |
| 2631 |
begin |
| 2632 |
NormalInterpolator := nil; |
| 2633 |
OriginalNormals := nil; |
| 2634 |
AnimatedNormals := nil; |
| 2635 |
end; |
| 2636 |
|
| 2637 |
if Tangent <> nil then |
| 2638 |
begin |
| 2639 |
TangentInterpolator := TCoordinateInterpolatorNode.Create; |
| 2640 |
TangentInterpolator.X3DName := 'Tangent' + InterpolatorNameSuffix; |
| 2641 |
//GatherAnimationKeysToSample(TangentInterpolator.FdKey.Items, Anim.Interpolators); |
| 2642 |
// faster: |
| 2643 |
TangentInterpolator.FdKey.Assign(CoordInterpolator.FdKey); |
| 2644 |
TangentInterpolator.FdKeyValue.Count := TangentInterpolator.FdKey.Count * Tangent.FdVector.Count; |
| 2645 |
|
| 2646 |
ParentGroup.AddChildren(TangentInterpolator); |
| 2647 |
ParentGroup.AddRoute(Anim.TimeSensor.EventFraction_changed, TangentInterpolator.EventSet_fraction); |
| 2648 |
ParentGroup.AddRoute(TangentInterpolator.EventValue_changed, Tangent.FdVector); |
| 2649 |
|
| 2650 |
OriginalTangents := Tangent.FdVector.Items; |
| 2651 |
AnimatedTangents := TangentInterpolator.FdKeyValue.Items; |
| 2652 |
end else |
| 2653 |
begin |
| 2654 |
TangentInterpolator := nil; |
| 2655 |
OriginalTangents := nil; |
| 2656 |
AnimatedTangents := nil; |
| 2657 |
end; |
| 2658 |
|
| 2659 |
for I := 0 to CoordInterpolator.FdKey.Items.Count - 1 do |
| 2660 |
begin |
| 2661 |
SampleSkinAnimation(Anim, I, CoordInterpolator.FdKey.Items[I], |
| 2662 |
Coord.FdPoint.Items, CoordInterpolator.FdKeyValue.Items, |
| 2663 |
OriginalNormals, AnimatedNormals, |
| 2664 |
OriginalTangents, AnimatedTangents, |
| 2665 |
Joints, JointsGltf, InverseBindMatrices, |
| 2666 |
SkeletonRootIndex, |
| 2667 |
Shape.Geometry.InternalSkinJoints, |
| 2668 |
Shape.Geometry.InternalSkinWeights); |
| 2669 |
end; |
| 2670 |
|
| 2671 |
MemoryTaken := CoordInterpolator.FdKeyValue.Items.Capacity * SizeOf(TVector3); |
| 2672 |
if NormalInterpolator <> nil then |
| 2673 |
MemoryTaken := MemoryTaken + NormalInterpolator.FdKeyValue.Items.Capacity * SizeOf(TVector3); |
| 2674 |
if TangentInterpolator <> nil then |
| 2675 |
MemoryTaken := MemoryTaken + TangentInterpolator.FdKeyValue.Items.Capacity * SizeOf(TVector3); |
| 2676 |
if MemoryTaken > 10 * 1024 * 1024 then // report only when memory usage > 10 MB |
| 2677 |
WritelnLog('glTF', 'Memory occupied by precalculating "%s" animation: %s', [ |
| 2678 |
Anim.TimeSensor.X3DName, |
| 2679 |
SizeToStr(MemoryTaken) |
| 2680 |
]); |
| 2681 |
|
| 2682 |
{ We want to use Shape.BBox for optimization (to avoid recalculating bbox). |
| 2683 |
Simple version: |
| 2684 |
|
| 2685 |
Shape.BBox := Shape.BBox + TBox3D.FromPoints(CoordInterpolator.FdKeyValue.Items); |
| 2686 |
|
| 2687 |
But it's more efficient to set bbox for specific animation |
| 2688 |
once the animation starts. |
| 2689 |
It also looks a bit more intuitive when you view bbox |
| 2690 |
(otherwise you would see a large bbox accounting for *all* animations, |
| 2691 |
but with mesh transformed with current animation, testcase: Bee, Monster). |
| 2692 |
|
| 2693 |
This matters, because bbox is also used for collisions. |
| 2694 |
E.g. knight in fps_game when Walking should not have huge bbox |
| 2695 |
because of Dying animation. } |
| 2696 |
SetBBoxWhenAnimationStarts(Anim.TimeSensor, Shape, |
| 2697 |
TBox3D.FromPoints(CoordInterpolator.FdKeyValue.Items), |
| 2698 |
ParentGroup); |
| 2699 |
end; |
| 2700 |
end; |
| 2701 |
|
| 2702 |
{ Apply Skin to deform shapes list. } |
| 2703 |
procedure ReadSkin(const SkinToInitialize: TSkinToInitialize; |
| 2704 |
const ParentGroup: TAbstractGroupingNode); |
| 2705 |
var |
| 2706 |
SkeletonRootIndex: Integer; |
| 2707 |
SkeletonRoot: TAbstractGroupingNode; |
| 2708 |
Joints: TX3DNodeList; |
| 2709 |
InverseBindMatrices: TMatrix4List; |
| 2710 |
I: Integer; |
| 2711 |
Skin: TPasGLTF.TSkin; |
| 2712 |
Shapes: TAbstractGroupingNode; |
| 2713 |
ShapeNode: TShapeNode; |
| 2714 |
begin |
| 2715 |
Skin := SkinToInitialize.Skin; |
| 2716 |
Shapes := SkinToInitialize.Shapes; |
| 2717 |
|
| 2718 |
SkeletonRootIndex := Skin.Skeleton; |
| 2719 |
if SkeletonRootIndex = -1 then |
| 2720 |
SkeletonRoot := Result // root node created by LoadGltf |
| 2721 |
else |
| 2722 |
begin |
| 2723 |
if not Between(SkeletonRootIndex, 0, Nodes.Count - 1) then |
| 2724 |
begin |
| 2725 |
WritelnWarning('Skin "%s" specifies invalid skeleton root node index %d', [ |
| 2726 |
Skin.Name, |
| 2727 |
SkeletonRootIndex |
| 2728 |
]); |
| 2729 |
Exit; |
| 2730 |
end; |
| 2731 |
SkeletonRoot := Nodes[SkeletonRootIndex] as TAbstractGroupingNode; |
| 2732 |
end; |
| 2733 |
|
| 2734 |
// first nil local variables, to reliably do try..finally that includes them all |
| 2735 |
Joints := nil; |
| 2736 |
InverseBindMatrices := nil; |
| 2737 |
|
| 2738 |
try |
| 2739 |
Joints := TX3DNodeList.Create(false); |
| 2740 |
Joints.Count := Skin.Joints.Count; |
| 2741 |
for I := 0 to Skin.Joints.Count - 1 do |
| 2742 |
begin |
| 2743 |
if not Between(Skin.Joints[I], 0, Nodes.Count - 1) then |
| 2744 |
begin |
| 2745 |
WritelnWarning('Skin "%s" specifies invalid joint index %d', [ |
| 2746 |
Skin.Name, |
| 2747 |
Skin.Joints[I] |
| 2748 |
]); |
| 2749 |
Exit; |
| 2750 |
end; |
| 2751 |
Joints[I] := Nodes[Skin.Joints[I]]; |
| 2752 |
end; |
| 2753 |
|
| 2754 |
InverseBindMatrices := TMatrix4List.Create; |
| 2755 |
AccessorToMatrix4(Skin.InverseBindMatrices, InverseBindMatrices, false); |
| 2756 |
|
| 2757 |
if Joints.Count <> InverseBindMatrices.Count then |
| 2758 |
begin |
| 2759 |
WritelnWarning('Joints and InverseBindMatrices counts differ for skin "%s": %d and %d', [ |
| 2760 |
Skin.Name, |
| 2761 |
Joints.Count, |
| 2762 |
InverseBindMatrices.Count |
| 2763 |
]); |
| 2764 |
Exit; |
| 2765 |
end; |
| 2766 |
|
| 2767 |
JointMatrix.Count := Joints.Count; |
| 2768 |
|
| 2769 |
{ To satisfy glTF requirements |
| 2770 |
""" |
| 2771 |
Client implementations should apply only the transform of the skeleton root |
| 2772 |
node to the skinned mesh while ignoring the transform of the skinned mesh node. |
| 2773 |
""" |
| 2774 |
Just reparent the meshes under skeleton root. |
| 2775 |
|
| 2776 |
Testcase: demo-models/blender/skinned_animation/skinned_anim.glb . } |
| 2777 |
if SkinToInitialize.ShapesParent <> SkeletonRoot then |
| 2778 |
begin |
| 2779 |
SkeletonRoot.AddChildren(Shapes); |
| 2780 |
SkinToInitialize.ShapesParent.RemoveChildren(Shapes); |
| 2781 |
SkinToInitialize.ShapesParent := SkeletonRoot; |
| 2782 |
end; |
| 2783 |
|
| 2784 |
for I := 0 to Shapes.FdChildren.Count - 1 do |
| 2785 |
if Shapes.FdChildren[I] is TShapeNode then |
| 2786 |
begin |
| 2787 |
ShapeNode := TShapeNode(Shapes.FdChildren[I]); |
| 2788 |
CalculateSkinInterpolators(ShapeNode, |
| 2789 |
Joints, Skin.Joints, InverseBindMatrices, |
| 2790 |
SkeletonRoot, SkeletonRootIndex, ParentGroup); |
| 2791 |
end; |
| 2792 |
finally |
| 2793 |
FreeAndNil(Joints); |
| 2794 |
FreeAndNil(InverseBindMatrices); |
| 2795 |
end; |
| 2796 |
end; |
| 2797 |
|
| 2798 |
{ Read glTF skins, which result in CoordinateInterpolator nodes |
| 2799 |
attached to shapes. |
| 2800 |
Must be called after Nodes and SkinsToInitialize are ready, so after ReadNodes. } |
| 2801 |
procedure ReadSkins(const ParentGroup: TAbstractGroupingNode); |
| 2802 |
var |
| 2803 |
SkinToInitialize: TSkinToInitialize; |
| 2804 |
begin |
| 2805 |
// one-time initialization of structures to process skin |
| 2806 |
AnimationSampler.TransformNodes := Nodes; |
| 2807 |
AnimationSampler.TransformNodesGltf := Document.Nodes; |
| 2808 |
|
| 2809 |
for SkinToInitialize in SkinsToInitialize do |
| 2810 |
ReadSkin(SkinToInitialize, ParentGroup); |
| 2811 |
end; |
| 2812 |
|
| 2813 |
{ EXPORT nodes, so that using glTF animations in X3D is possible, like on |
| 2814 |
demo-models/blender/skinned_animation/skinned_anim_run_animations_from_x3d.x3dv } |
| 2815 |
procedure DoExportNodes; |
| 2816 |
var |
| 2817 |
N: TX3DNode; |
| 2818 |
Anim: TAnimation; |
| 2819 |
begin |
| 2820 |
for N in ExportNodes do |
| 2821 |
if N.X3DName <> '' then |
| 2822 |
Result.ExportNode(N); |
| 2823 |
|
| 2824 |
for N in Appearances do |
| 2825 |
if N.X3DName <> '' then |
| 2826 |
Result.ExportNode(N); |
| 2827 |
|
| 2828 |
for N in Nodes do |
| 2829 |
if (N <> nil) and (N.X3DName <> '') then |
| 2830 |
Result.ExportNode(N); |
| 2831 |
|
| 2832 |
for Anim in Animations do |
| 2833 |
begin |
| 2834 |
N := Anim.TimeSensor; |
| 2835 |
if N.X3DName <> '' then |
| 2836 |
Result.ExportNode(N); |
| 2837 |
end; |
| 2838 |
end; |
| 2839 |
|
| 2840 |
var |
| 2841 |
Material: TPasGLTF.TMaterial; |
| 2842 |
Animation: TPasGLTF.TAnimation; |
| 2843 |
begin |
| 2844 |
Result := TX3DRootNode.Create('', BaseUrl); |
| 2845 |
try |
| 2846 |
// Set to nil local variables, to avoid nested try..finally..end construction |
| 2847 |
Document := nil; |
| 2848 |
DefaultAppearance := nil; |
| 2849 |
Appearances := nil; |
| 2850 |
Nodes := nil; |
| 2851 |
ExportNodes := nil; |
| 2852 |
SkinsToInitialize := nil; |
| 2853 |
Animations := nil; |
| 2854 |
AnimationSampler := nil; |
| 2855 |
JointMatrix := nil; |
| 2856 |
Lights := nil; |
| 2857 |
try |
| 2858 |
Document := TMyGltfDocument.Create(Stream, BaseUrl); |
| 2859 |
SkinsToInitialize := TSkinToInitializeList.Create(true); |
| 2860 |
Animations := TAnimationList.Create(true); |
| 2861 |
AnimationSampler := TAnimationSampler.Create; |
| 2862 |
JointMatrix := TMatrix4List.Create; |
| 2863 |
Lights := TPunctualLights.Create; |
| 2864 |
ExportNodes := TX3DNodeList.Create(false); |
| 2865 |
|
| 2866 |
ReadHeader; |
| 2867 |
Lights.ReadHeader(Document); |
| 2868 |
|
| 2869 |
{ Initialize DefaultAppearance. |
| 2870 |
Testcase: floor of ~/sources/castle-engine/demo-models/gltf/punctual_lights/test_lights.gltf, |
| 2871 |
it should use PBR (not be affected by PhongShading attribute). } |
| 2872 |
DefaultAppearance := TGltfAppearanceNode.Create; |
| 2873 |
DefaultAppearance.Material := TPhysicalMaterialNode.Create; |
| 2874 |
DefaultAppearance.DoubleSided := false; |
| 2875 |
|
| 2876 |
// read appearances (called "materials" in glTF; in X3D "material" is something smaller) |
| 2877 |
Appearances := TX3DNodeList.Create(false); |
| 2878 |
for Material in Document.Materials do |
| 2879 |
Appearances.Add(ReadAppearance(Material)); |
| 2880 |
|
| 2881 |
// read main scene |
| 2882 |
Nodes := TX3DNodeList.Create(false); |
| 2883 |
if Document.Scene <> -1 then |
| 2884 |
ReadScene(Document.Scene, Result) |
| 2885 |
else |
| 2886 |
begin |
| 2887 |
WritelnWarning('glTF does not specify a default scene to render. We will import the 1st scene, if available.'); |
| 2888 |
ReadScene(0, Result); |
| 2889 |
end; |
| 2890 |
|
| 2891 |
// once appearances Used, UsedAsLit are set, fix them |
| 2892 |
FixAppearances; |
| 2893 |
|
| 2894 |
// read animations |
| 2895 |
for Animation in Document.Animations do |
| 2896 |
ReadAnimation(Animation, Result); |
| 2897 |
ReadSkins(Result); |
| 2898 |
DoExportNodes; |
| 2899 |
finally |
| 2900 |
FreeAndNil(JointMatrix); |
| 2901 |
FreeAndNil(Animations); |
| 2902 |
FreeAndNil(SkinsToInitialize); |
| 2903 |
FreeAndNil(AnimationSampler); |
| 2904 |
FreeIfUnusedAndNil(DefaultAppearance); |
| 2905 |
X3DNodeList_FreeUnusedAndNil(Appearances); |
| 2906 |
{ Note that some Nodes[...] items may be nil. |
| 2907 |
|
| 2908 |
While in glTF there are no gaps (the nodes are a list without gaps), |
| 2909 |
but a particular Document.Scene may refer only to a subset of nodes, |
| 2910 |
and our ReadNode reads them recursively. |
| 2911 |
Unused nodes (not referred by Document.Scene) are left unprocessed, |
| 2912 |
and their Nodes[...] remains nil. |
| 2913 |
|
| 2914 |
Still, X3DNodeList_FreeUnusedAndNil guarantees to handle it. |
| 2915 |
Testcase: GLB from https://www.kenney.nl/assets/city-kit-suburban . } |
| 2916 |
X3DNodeList_FreeUnusedAndNil(Nodes); |
| 2917 |
FreeAndNil(ExportNodes); |
| 2918 |
FreeAndNil(Lights); |
| 2919 |
FreeAndNil(Document); |
| 2920 |
end; |
| 2921 |
except FreeAndNil(Result); raise end; |
| 2922 |
end; |
| 2923 |
|
| 2924 |
var |
| 2925 |
ModelFormat: TModelFormat; |
| 2926 |
initialization |
| 2927 |
ModelFormat := TModelFormat.Create; |
| 2928 |
ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadGLTF; |
| 2929 |
ModelFormat.OnLoadForceMemoryStream := true; |
| 2930 |
ModelFormat.MimeTypes.Add('model/gltf+json'); |
| 2931 |
ModelFormat.MimeTypes.Add('model/gltf-binary'); |
| 2932 |
ModelFormat.FileFilterName := 'glTF (*.glb, *.gltf)'; |
| 2933 |
ModelFormat.Extensions.Add('.glb'); |
| 2934 |
ModelFormat.Extensions.Add('.gltf'); |
| 2935 |
RegisterModelFormat(ModelFormat); |
| 2936 |
end. |