Debian Codegraph @

src/scene/castleinternalarraysgenerator.pas

raw
1 {
2 Copyright 2002-2023 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 { Generating TGeometryArrays for shapes (TArraysGenerator). }
17 unit CastleInternalArraysGenerator;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses CastleShapes, X3DNodes, X3DFields, CastleUtils, CastleInternalGeometryArrays,
24 CastleVectors;
25
26 type
27 { Generate TGeometryArrays for a shape. This is the basis
28 of our renderer, TRenderer will pass such arrays to OpenGL.
29 Geometry must be based on coordinates when using this,
30 that is TAbstractGeometryNode.Coord must return @true. }
31 TArraysGenerator = class
32 strict private
33 FShape: TShape;
34 FState: TX3DGraphTraverseState;
35 FGeometry: TAbstractGeometryNode;
36
37 FCurrentRangeNumber: Cardinal;
38 FCoord: TMFVec3f;
39
40 { Generalized version of AssignAttribute, AssignCoordinate. }
41 procedure AssignAttributeOrCoordinate(
42 const AttributeName: String;
43 const TargetPtr: Pointer; const TargetItemSize: SizeInt;
44 const SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
45 const TrivialIndex: Boolean);
46 protected
47 { Indexes, only when Arrays.Indexes = nil but original node was indexed.
48 This has only indexes >= 0.
49
50 This is TUInt32List, not TGeometryIndexList -- eventual conversion
51 32-bit indexes -> 16-bit (if necessary because of old OpenGLES) will happen later. }
52 IndexesFromCoordIndex: TUInt32List;
53
54 { Similar to IndexesFromCoordIndex, but not processed by CoordIndex[].
55 That is,
56
57 IndexesFromCoordIndex[Something] := CoordIndex.Items[SomethingElse];
58
59 where
60
61 TrivialIndexesFromCoordIndex[Something] := SomethingElse;
62
63 This is only non-nil when
64
65 - IndexesFromCoordIndex is non-nil
66 - moreover, node generator could use TrivialIndex.
67
68 Which is possible only when node may be indexed, but also use niPerVertexNonIndexed
69 at the same time, which is only possible for IndexedFaceSet with
70 non-trivial creaseAngle (the "Shape.NormalsCreaseAngle" then force
71 niPerVertexNonIndexed).
72
73 This is TUInt32List, not TGeometryIndexList -- eventual conversion
74 32-bit indexes -> 16-bit (if necessary because of old OpenGLES) will happen later. }
75 TrivialIndexesFromCoordIndex: TUInt32List;
76
77 { Index to Arrays. Suitable always to index Arrays.Position / Color / Normal
78 and other Arrays attribute arrays. Calculated in
79 each TAbstractCoordinateGenerator.GenerateVertex,
80 always call "inherited" first from GenerateVertex overrides.
81
82 There are three cases:
83
84 1. When CoordIndex <> nil (so we have indexed node) and
85 Arrays.Indexes <> nil (so we can render it by indexes,
86 because AllowIndexed = true) then it's an index to
87 node coordinates. It's equivalent to CoordIndex[IndexNum],
88 and it can be used to index node's Coord as well as Arrays.Position
89 (since they are ordered the same in this case).
90
91 2. When CoordIndex <> nil (so we have indexed node) and
92 Arrays.Indexes = nil (so we cannot render it by indexes,
93 because AllowIndexed = false) then it's a number of vertex,
94 that is it's incremented in each TAbstractCoordinateGenerator.GenerateVertex
95 call.
96
97 In this case IndexesFromCoordIndex <> nil,
98 and Arrays attributes have the same count as IndexesFromCoordIndex.Count.
99 GenerateVertex must be called in exactly the same order
100 as IndexesFromCoordIndex were generated for this.
101
102 3. When CoordIndex = nil (so we don't have an indexed node,
103 also Arrays.Indexes = IndexesFromCoordIndex = nil always in this case)
104 then it's an index to attributes. This is the trivial case,
105 as Arrays attributes are then ordered just like node's Coord.
106 It's equal to IndexNum then.
107 }
108 ArrayIndexNum: Integer;
109
110 { Generated TGeometryArrays instance, available inside GenerateCoordinate*. }
111 Arrays: TGeometryArrays;
112
113 { Coordinate index, taken from Geometry.CoordIndex.
114
115 If @nil, then GenerateVertex (and all other
116 routines taking some index) will just directly index Coord
117 (this is useful for non-indexed geometry, like TriangleSet
118 instead of IndexedTriangleSet). }
119 CoordIndex: TMFLong;
120
121 { Current shape properties, constant for the whole
122 lifetime of the generator, set in constructor.
123 @groupBegin }
124 property Shape: TShape read FShape;
125 property State: TX3DGraphTraverseState read FState;
126 property Geometry: TAbstractGeometryNode read FGeometry;
127 { @groupEnd }
128
129 { Coordinates, taken from Geometry.Coord.
130 Usually coming from (coord as Coordinate).points field.
131 If @nil then nothing will be rendered.
132
133 In our constructor we initialize Coord and CoordIndex
134 from Geometry, using TAbstractGeometryNode.Coord and
135 TAbstractGeometryNode.CoordIndex values. }
136 property Coord: TMFVec3f read FCoord;
137
138 { Generate arrays content for given vertex.
139 Given IndexNum indexes Coord, or (if CoordIndex is assigned)
140 indexes CoordIndex (and CoordIndex then indexes actual Coord). }
141 procedure GenerateVertex(IndexNum: Integer); virtual;
142
143 { Get vertex coordinate. Returned vertex is in local coordinate space
144 (use State.Transform if you want to get global coordinates). }
145 function GetVertex(IndexNum: integer): TVector3;
146
147 { Count of indexes. You can pass index between 0 and CoordCount - 1
148 to various methods taking an index, like GenerateVertex. }
149 function CoordCount: Integer;
150
151 { Generate contents of Arrays.
152 These are all called only when Coord is assigned.
153
154 GenerateCoordinate can be overridden only by the class
155 that actually knows how to deconstruct (triangulate etc.) this node.
156 It must call GenerateVertex (or call GenerateCoordsRange,
157 that has to be then overridden to call GenerateVertex after inherited).
158
159 GenerateCoordinateBegin, GenerateCoordinateEnd will be called
160 before / after GenerateCoordinate. It's useful to override them for
161 intermediate classes in this file, that cannot triangulate,
162 but still want to add something before / after GenerateCoordinate.
163 When overriding GenerateCoordinateBegin, always call inherited
164 at the begin. When overriding GenerateCoordinateEnd, always call inherited
165 at the end.
166 @groupBegin }
167 procedure GenerateCoordinate; virtual; abstract;
168 procedure GenerateCoordinateBegin; virtual;
169 procedure GenerateCoordinateEnd; virtual;
170 { @groupEnd }
171
172 { Generate arrays content for one coordinate range (like a face).
173 This is not called, not used, anywhere in this base
174 TAbstractCoordinateGenerator class.
175 In descendants, it may be useful to use this, like
176 Geometry.InternalMakeCoordRanges(State, @@GenerateCoordsRange).
177
178 GenerateCoordsRange is supposed to generate the parts of the mesh
179 between BeginIndex and EndIndex - 1 vertices.
180 BeginIndex and EndIndex are indexes to CoordIndex array,
181 if CoordIndex is assigned, or just indexes to Coord. }
182 procedure GenerateCoordsRange(
183 const RangeNumber: Cardinal;
184 BeginIndex, EndIndex: Integer); virtual;
185
186 { The number of current range (like a face), equal to RangeNumber passed to
187 GenerateCoordsRange. Read this only while in GenerateCoordsRange.
188 In fact, this is just set by GenerateCoordsRange in this class
189 (so call @code(inherited) first when overriding it).
190
191 It's comfortable e.g. when you need RangeNumber inside GenerateVertex,
192 and you know that GenerateVertex will be called only from
193 GenerateCoordsRange. }
194 property CurrentRangeNumber: Cardinal read FCurrentRangeNumber;
195
196 { If CoordIndex assigned (this VRML/X3D node is IndexedXxx)
197 then calculate and set IndexesFromCoordIndex here.
198 This is also the place to set Arrays.Primitive and Arrays.Counts. }
199 procedure PrepareIndexesPrimitives; virtual; abstract;
200
201 { Called when constructing Arrays, before the Arrays.Count is set.
202
203 Descendants can override this to do stuff like Arrays.AddColor or
204 Arrays.AddAttribute('foo'). After this method, the other code assumes that
205 Arrays.CoordinateSize and Arrays.AttributeSize is fully determined.
206
207 Descendants can also set AllowIndexed
208 to @false, if we can't use indexed rendering (because e.g. we have
209 colors per-face, which means that the same vertex position may have
210 different colors, which means it has to be duplicated in arrays anyway,
211 so there's no point in indexing). }
212 procedure PrepareAttributes(var AllowIndexed: boolean); virtual;
213
214 { Fill some attribute inside Arrays (in the Arrays.AttributeArray, Arrays.AttributeSize).
215
216 Suitable for use when the SourceCount corresponds to the original shape Coordinate count,
217 so the Source array (defined by SourcePtr, SourceItemSize, SourceCount) is accessed
218 in the same way as vertex coordinates: it is either indexed by shape coordIndex/index,
219 or it is not indexed. }
220 procedure AssignAttribute(const AttributeName: String;
221 const TargetPtr, SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
222 const TrivialIndex: Boolean = false);
223
224 { Fill some attribute inside Arrays (in the Arrays.CoordinateArray, Arrays.CoordinateSize).
225
226 Suitable for use when the SourceCount corresponds to the original shape Coordinate count,
227 so the Source array (defined by SourcePtr, SourceItemSize, SourceCount) is accessed
228 in the same way as vertex coordinates: it is either indexed by shape coordIndex/index,
229 or it is not indexed.
230
231 AttributeName is only for debug (to display nice logs / warnings). }
232 procedure AssignCoordinate(const AttributeName: String;
233 const TargetPtr, SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
234 const TrivialIndex: Boolean = false);
235 public
236 { Assign these before calling GenerateArrays.
237 @groupBegin }
238 TexCoordsNeeded: Cardinal;
239 FogVolumetric: boolean;
240 FogVolumetricDirection: TVector3;
241 FogVolumetricVisibilityStart: Single;
242 ShapeBumpMappingUsed: boolean;
243 ShapeBumpMappingTextureCoordinatesId: Cardinal;
244 { Do we need TGeometryArrays.Faces }
245 FacesNeeded: boolean;
246 { @groupEnd }
247
248 constructor Create(AShape: TShape); virtual;
249
250 { Create and generate Arrays contents. }
251 function GenerateArrays: TGeometryArrays;
252
253 class function BumpMappingAllowed: boolean; virtual;
254 end;
255
256 TArraysGeneratorClass = class of TArraysGenerator;
257
258 { TArraysGenerator class suitable for given geometry.
259 Returns @nil if not suitable generator for this node,
260 which means that this node cannot be rendered through TGeometryArrays. }
261 function GetArraysGenerator(AGeometry: TAbstractGeometryNode): TArraysGeneratorClass;
262
263 implementation
264
265 uses SysUtils, Math, Generics.Collections,
266 CastleLog, CastleTriangles, CastleColors, CastleBoxes, CastleTriangulate,
267 CastleStringUtils, CastleRenderOptions, CastleInternalGLUtils;
268
269 { Copying to interleaved memory utilities ------------------------------------ }
270
271 type
272 EAssignInterleavedRangeError = class(Exception);
273
274 { Copy Source contents to given Target memory. Each item in Target
275 is separated by the TargetItemSize bytes.
276
277 We copy CopyCount items (you usually want to pass the count of Target
278 data here). Source.Count must be >= CopyCount,
279 we check it and eventually raise EAssignInterleavedRangeError.
280
281 Warning: this is safely usable only for arrays of types that don't
282 require initialization / finalization. Otherwise target memory data
283 will not be properly referenced.
284
285 @raises EAssignInterleavedRangeError When Count < CopyCount. }
286 procedure AssignToInterleaved(
287 const AttributeName: String;
288 Target: Pointer; const TargetItemSize, CopyCount: SizeInt;
289 Source: Pointer; const SourceItemSize, SourceCount: SizeInt);
290 var
291 I: Integer;
292 begin
293 if SourceCount < CopyCount then
294 raise EAssignInterleavedRangeError.CreateFmt('Not enough items in %s: %d, but at least %d required', [
295 AttributeName,
296 SourceCount,
297 CopyCount
298 ]);
299
300 for I := 0 to CopyCount - 1 do
301 begin
302 Move(Source^, Target^, SourceItemSize);
303 PtrUInt(Source) := PtrUInt(Source) + SourceItemSize;
304 PtrUInt(Target) := PtrUInt(Target) + TargetItemSize;
305 end;
306 end;
307
308 { Copy Source contents to given Target memory. Each item in Target
309 is separated by the TargetItemSize bytes.
310
311 We copy CopyCount items (you usually want to pass the count of Target
312 data here). Indexes.Count must be >= CopyCount,
313 we check it and eventually raise EAssignInterleavedRangeError.
314
315 Item number I is taken from Source array, at Indexes[I], like Source[Indexes[I]].
316 All values on Indexes list must be valid (that is >= 0 and < SourceCount),
317 or we raise EAssignInterleavedRangeError.
318
319 Warning: this is safely usable only for arrays of types that don't
320 require initialization / finalization. Otherwise target memory data
321 will not be properly referenced.
322
323 @raises(EAssignInterleavedRangeError When Indexes.Count < CopyCount,
324 or some index points outside of array.) }
325 procedure AssignToInterleavedIndexed(
326 const AttributeName: String;
327 Target: Pointer; const TargetItemSize, CopyCount: SizeInt;
328 Source: Pointer; const SourceItemSize, SourceCount: SizeInt;
329 const Indexes: TUInt32List);
330 var
331 I: Integer;
332 Index: UInt32;
333 begin
334 if Indexes.Count < CopyCount then
335 raise EAssignInterleavedRangeError.CreateFmt('Not enough items in %s: %d, but at least %d required', [
336 AttributeName,
337 Indexes.Count,
338 CopyCount
339 ]);
340
341 for I := 0 to CopyCount - 1 do
342 begin
343 Index := Indexes.L[I];
344 if Index >= SourceCount then
345 raise EAssignInterleavedRangeError.CreateFmt('Invalid index: %d, but we have %d items in %s', [
346 Index,
347 SourceCount,
348 AttributeName
349 ]);
350
351 { Beware to not make multiplication below (* ItemSize) using 64-bit ints.
352 This would cause noticeable slowdown when using AssignToInterleavedIndexed
353 for ArraysGenerator, that in turn affects dynamic scenes
354 and especially dynamic shading like radiance_transfer. }
355 Move(Pointer(PtrUInt(Source) + PtrUInt(Index) * PtrUInt(SourceItemSize))^,
356 Target^, SourceItemSize);
357 PtrUInt(Target) := PtrUInt(Target) + TargetItemSize;
358 end;
359 end;
360
361 { Like AssignToInterleaved, but there is only one Source value,
362 that should be copied to all destinations. }
363 procedure AssignToInterleavedConstant(
364 Target: Pointer; const TargetItemSize, CopyCount: SizeInt;
365 const Source: Pointer; const SourceItemSize: SizeInt);
366 var
367 I: Integer;
368 begin
369 for I := 0 to CopyCount - 1 do
370 begin
371 Move(Source^, Target^, SourceItemSize);
372 PtrUInt(Target) := PtrUInt(Target) + TargetItemSize;
373 end;
374 end;
375
376 { classes -------------------------------------------------------------------- }
377
378 type
379 TTextureCoordsImplementation = (
380 { Texture coords not generated, because not needed by Renderer. }
381 tcNotGenerated,
382 { All texture coords (on all texture units, for multi-texturing)
383 are automatically generated.
384
385 Actually we could use some other value
386 like tcTexIndexed (anything else than tcNotGenerated) to indicate
387 this, since for everything <> tcNotGenerated we actually check
388 TexCoordGen to know if coords should be explicit or automatic.
389 But using special tcAllGenerated feels cleaner. }
390 tcAllGenerated,
391 { IndexNum is an index to TexCoordIndex, as this indexes TexCoordGen/Array[TextureUnit]. }
392 tcTexIndexed,
393 { IndexNum is an index to CoordIndex, as this indexes TexCoordGen/Array[TextureUnit]. }
394 tcCoordIndexed,
395 { IndexNum is a direct index to TexCoordGen/Array[TextureUnit]. }
396 tcNonIndexed);
397
398 { Handle texture coordinates.
399
400 Usage:
401
402 - TexCoord is already set from TAbstractGeometryNode.TexCoord,
403 so just be sure it's overriden for your Geometry node class.
404
405 Don't worry, we will automatically check TexCoord class,
406 and do something useful with it only if we can.
407 When TexCoord = @nil,
408 then we'll generate default texture coordinates,
409 following VRML 2.0 / X3D IndexedFaceSet default texture coord algorithm.
410
411 (X3D spec doesn't say what happens for nodes like
412 IndexedTriangleSet when texture is specified (in Appearance.texture)
413 but texture coords are not present.
414 For now, we just generate texture coords for them just like for
415 IndexedFaceSet.)
416
417 - Set TexCoordIndex, if available. This works just like CoordIndex:
418
419 If @nil, then GenerateVertex (and all other
420 routines taking some index) will just directly index TexCoord
421 (this is useful for non-indexed geometry, like TriangleSet
422 instead of IndexedTriangleSet). Otherwise, they will index TexCoordIndex,
423 and then TexCoordIndex provides index to TexCoord.
424
425 As a special case, if TexCoordIndex is assigned but empty
426 (actually, just checked as "shorter than CoordIndex")
427 then IndexNum indexed CoordIndex. So CoordIndex acts as
428 TexCoordIndex in this case. This case is specially for
429 for IndexedFaceSet in VRML >= 2.0.
430
431 Always when TexCoordIndex is non-nil, also make sure that CoordIndex
432 is non-nil. When TexCoordIndex is nil, make sure that CoordIndex is nil.
433 (This restriction may be removed in the future,
434 but for now nothing needs it.)
435
436 This class takes care to generate tex coords, or use supplied
437 TexCoord and TexCoordIndex. At least for texture units in
438 TexCoordsNeeded (although we may pass some more, will be unused).
439 So you do not have to generate any texture coordinates
440 in descendants. Everything related to textures is already
441 handled in this class. }
442 TAbstractTextureCoordinateGenerator = class(TArraysGenerator)
443 private
444 TexImplementation: TTextureCoordsImplementation;
445
446 { Source of explicit texture coordinates, for each texture unit
447 that has Arrays.TexCoord[I].Generation = tgExplicit.
448 The value of Arrays.TexCoord[I].Dimensions determines
449 which of these is actually used.
450
451 These arrays have always exactly the same length,
452 equal to Arrays.TexCoords.Count. }
453 TexCoordArray2d: array of TMFVec2f;
454 TexCoordArray3d: array of TMFVec3f;
455 TexCoordArray4d: array of TMFVec4f;
456
457 TexCoord: TX3DNode;
458 protected
459 TexCoordIndex: TMFLong;
460
461 { Return texture coordinate for given vertex, identified by IndexNum.
462 IndexNum indexes TexCoordGen/Array[TextureUnit], or TexCoordIndex
463 (if TexCoordIndex assigned),
464 or CoordIndex (if TexCoordIndex assigned but empty, for IndexedFaceSet).
465
466 Returns @false if no texture coords are available, for given
467 TextureUnit.
468
469 Works in all cases when we actually render some texture.
470
471 Overloaded version with only TVector2 just ignores the 3rd and
472 4th texture coordinate, working only when texture coord is
473 normal 2D coord. }
474 function GetTextureCoord(IndexNum: integer;
475 const TextureUnit: Cardinal; out Tex: TVector4): boolean; overload;
476 function GetTextureCoord(IndexNum: integer;
477 const TextureUnit: Cardinal; out Tex: TVector2): boolean; overload;
478
479 procedure PrepareAttributes(var AllowIndexed: boolean); override;
480
481 procedure GenerateVertex(IndexNum: Integer); override;
482
483 procedure GenerateCoordinateBegin; override;
484 public
485 constructor Create(AShape: TShape); override;
486 end;
487
488 TMaterials1Implementation = (miOverall,
489 miPerVertexCoordIndexed,
490 miPerVertexMatIndexed,
491 miPerFace,
492 miPerFaceMatIndexed);
493
494 { Handle per-face or per-vertex VRML 1.0 materials.
495
496 Usage:
497 - Just set MaterialIndex and MaterialBinding using your node's fields.
498 Call UpdateMat1Implementation afterwards.
499 - For VRML >= 2.0 nodes, you don't have to do anything.
500 You can just leave MaterialBinding as default BIND_DEFAULT,
501 but it really doesn't matter: the only effect of this class
502 are calls to Render_BindMaterial_1. And Render_BindMaterial_1
503 simply does nothing for VRML >= 2.0 geometry nodes.
504
505 Since this must have a notion of what "face" is, it assumes that
506 your GenerateCoordsRange constitutes rendering of a single face.
507 If this isn't true, then "per face" materials will not work
508 correctly.
509
510 Note that "per vertex" materials require smooth shading,
511 so you should set this in your Render. There's no way to implement
512 them with flat shading.
513
514 Everything related to VRML 1.0 materials is already handled in this class. }
515 TAbstractMaterial1Generator = class(TAbstractTextureCoordinateGenerator)
516 private
517 { Must be set in constructor. MaterialsBegin (may someday) depend on this.
518
519 For this reason, call UpdateMat1Implementation inside descendant
520 constructor after changing this. }
521 Mat1Implementation: TMaterials1Implementation;
522 FaceMaterial1Color: TVector4;
523 function GetMaterial1Color(const MaterialIndex: Integer): TVector4;
524 protected
525 { You can leave MaterialIndex as nil if you are sure that
526 MaterialBinding will not be any _INDEXED value.
527
528 Be sure to change these only inside constructor,
529 and call UpdateMat1Implementation afterwards. We want Mat1Implementation
530 ready after constructor. }
531 MaterialIndex: TMFLong;
532 MaterialBinding: Integer;
533 procedure UpdateMat1Implementation;
534
535 procedure PrepareAttributes(var AllowIndexed: boolean); override;
536 procedure GenerateVertex(IndexNum: Integer); override;
537 procedure GenerateCoordsRange(const RangeNumber: Cardinal;
538 BeginIndex, EndIndex: integer); override;
539 public
540 constructor Create(AShape: TShape); override;
541 end;
542
543 { Handle per-face or per-vertex VRML >= 2.0 colors.
544
545 Usage: set Color or ColorRGBA (at most one of them), ColorPerVertex,
546 ColorIndex.
547
548 If Color and ColorRGBA = @nil, this class will not do anything.
549 Otherwise, colors will be used.
550
551 ColorPerVertex specifies per-vertex or per-face.
552 Just like for VRML 1.0, the same restrictions apply:
553 - if you want per-face to work, then GenerateCoordsRange must
554 correspond to a single face.
555 - if you want per-vertex to work, you must use smooth shading.
556
557 ColorIndex:
558
559 - When ColorIndex is set and non-empty (worse optimized, seldom case), then
560
561 - when ColorPerVertex: vertex IndexNum is an index to ColorIndex
562 - when not ColorPerVertex: face number is an index to ColorIndex
563 And then ColorIndex indexes Color items.
564
565 - When ColorIndex is empty (better optimized, common case):
566
567 - when ColorPerVertex: vertex IndexNum is an index to CoordIndex
568 and CoordIndex in turn is an index to Color.
569 Unless CoordIndex assigned, then vertex IndexNum indexes Color.
570 - when not ColorPerVertex: face number in an index for Color.
571
572 }
573 TAbstractColorGenerator = class(TAbstractMaterial1Generator)
574 strict private
575 { Per-face color (used when ColorPerVertex=false), used when ColorRGBA is non-nil. }
576 FaceColorRgbAlpha: TCastleColor;
577 { Per-face color (used when ColorPerVertex=false), used when Color is non-nil. }
578 FaceColorRgb: TCastleColorRGB;
579 { Is ColorIndex assigned and non-empty. }
580 function UseColorIndex: Boolean;
581 protected
582 Color: TMFVec3f;
583 ColorRGBA: TMFColorRGBA;
584 ColorPerVertex: boolean;
585 ColorIndex: TMFLong;
586 ColorNode: TAbstractColorNode;
587
588 procedure PrepareAttributes(var AllowIndexed: boolean); override;
589 procedure GenerateVertex(IndexNum: integer); override;
590 procedure GenerateCoordinateBegin; override;
591 procedure GenerateCoordsRange(const RangeNumber: Cardinal;
592 BeginIndex, EndIndex: Integer); override;
593 end;
594
595 TNormalsImplementation = (
596 { TAbstractNormalGenerator does nothing about normals.
597 Descendants must override GetNormal and GenerateVertex to provide normals
598 calculated using a custom method. }
599 niNone,
600 { The first item of Normals specifies the one and only normal
601 for the whole geometry. }
602 niOverall,
603 { Shape does not have any way to define reasonable normals, and so is rendered unlit
604 (e.g. LineSet, IndexedLineSet, PointSet, at least when no explicit
605 normals are provided (X3D v4 may allow providing normals for them)). }
606 niUnlit,
607 { Each vertex has it's normal vector, IndexNum specifies direct index
608 to Normals. }
609 niPerVertexNonIndexed,
610 { Each vertex has it's normal vector, IndexNum specifies index to
611 CoordIndex and this is an index to Normals. }
612 niPerVertexCoordIndexed,
613 { Each vertex has it's normal vector, IndexNum specifies index to
614 NormalIndex and this is an index to Normals. }
615 niPerVertexNormalIndexed,
616 { Face number is the index to Normals. }
617 niPerFace,
618 { Face number is the index to NormalIndex, and this indexes Normals. }
619 niPerFaceNormalIndexed
620 );
621
622 { Handle normals, both taken from user data (that is, stored in VRML file)
623 and generated.
624
625 Usage:
626
627 - You have to set NorImplementation in descendant.
628 Default value, NorImplementation = niNone, simply means that
629 this class does nothing and it's your responsibility to generate
630 and use normal vectors. See TNormalsImplementation for other meanings,
631 and which properties from
632 Normals
633 NormalsCcw (should always be set when setting Normals)
634 NormalIndex
635 you also have to assign to make them work.
636
637 For VRML 1.0, you most definitely want to set both Normals
638 and NormalIndex and then call NorImplementation :=
639 NorImplementationFromVRML1Binding. This should take care of
640 VRML 1.0 needs completely.
641
642 - If and only if NorImplementation = niNone (either you left it as
643 default, or NorImplementationFromVRML1Binding returned this,
644 or you set this...) you have to
645
646 - Override GetNormal and return correct normals.
647 GetNormal results (vectors) must point from side set as NormalsCcw.
648 When NorImplementation <> niNone then GetNormal should return inherited.
649
650 - Override GenerateVertex and set Arrays.Normal(ArrayIndexNum)^ := ...;
651
652 Note that PerVertexXxx normals require smooth shading to work Ok. }
653 TAbstractNormalGenerator = class(TAbstractColorGenerator)
654 private
655 FaceNormal: TVector3;
656 function NormalsSafe(const Index: Integer): TVector3;
657 protected
658 NormalIndex: TMFLong;
659 Normals: TVector3List;
660 NormalsCcw: boolean;
661
662 { This is calculated in constructor. Unlike similar TexImplementation
663 (which is calculated only in GenerateCoordinateBegin).
664 Reasons:
665 - Descendants may want to change NorImplementation. In other words,
666 full automatic detection only in TAbstractNormalGenerator
667 is not done, it's possible in descendants to explicitly change this.
668 - NodeLit uses this, so it must be available after creation and
669 before rendering. }
670 NorImplementation: TNormalsImplementation;
671
672 function NorImplementationFromVRML1Binding(
673 NormalBinding: Integer): TNormalsImplementation;
674
675 { Returns normal vector for given vertex, identified by IndexNum
676 (IndexNum has the same meaning as for GenerateVertex) and FaceNumber
677 (since normals may be available per-face, we need to know face number
678 as well as vertex number).
679
680 Returns normal from the side specified as NormalsCcw.
681
682 Override this in descendants only to handle
683 NorImplementation = niNone case. }
684 procedure GetNormal(IndexNum: Integer; RangeNumber: Integer;
685 out N: TVector3); virtual;
686
687 { If @true, then it's guaranteed that normals for the same face will
688 be equal. This may be useful for various optimization purposes.
689
690 Override this in descendants only to handle
691 NorImplementation = niNone case. The implementation in this class
692 just derives it from NorImplementation, and for niNone answers @false
693 (safer answer). }
694 function NormalsFlat: boolean; virtual;
695
696 procedure GenerateCoordinateBegin; override;
697 procedure GenerateCoordinateEnd; override;
698 procedure GenerateCoordsRange(const RangeNumber: Cardinal;
699 BeginIndex, EndIndex: Integer); override;
700
701 procedure PrepareAttributes(var AllowIndexed: boolean); override;
702
703 procedure GenerateVertex(IndexNum: Integer); override;
704 end;
705
706 { Handle fog coordinate.
707 Descendants don't have to do anything, this just works
708 (using TAbstractGeometryNode.FogCoord). }
709 TAbstractFogGenerator = class(TAbstractNormalGenerator)
710 private
711 FogCoord: TSingleList;
712 protected
713 procedure PrepareAttributes(var AllowIndexed: boolean); override;
714 procedure GenerateVertex(IndexNum: Integer); override;
715 public
716 constructor Create(AShape: TShape); override;
717 end;
718
719 TX3DVertexAttributeNodes = {$ifdef FPC}specialize{$endif} TObjectList<TAbstractVertexAttributeNode>;
720
721 { Handle GLSL custom attributes from X3D "attrib" field.
722 Descendants don't have to do anything, this just works
723 (using TAbstractGeometryNode.Attrib). }
724 TAbstractShaderAttribGenerator = class(TAbstractFogGenerator)
725 strict private
726 type
727 TAttribInfo = record
728 Node: TAbstractVertexAttributeNode;
729 GeometryAttrib: TGeometryAttrib;
730 end;
731 var
732 Attribs: array of TAttribInfo;
733 protected
734 procedure PrepareAttributes(var AllowIndexed: boolean); override;
735 procedure GenerateCoordinateBegin; override;
736 public
737 constructor Create(AShape: TShape); override;
738 end;
739
740 { Handle bump mapping.
741
742 Descendants should:
743 - override BumpMappingAllowed to return true,
744 - call CalculateTangentVectors when needed.
745 - Also make sure that GetNormal always
746 works (since it's called by CalculateTangentVectors),
747 so if you may use NorImplementation = niNone: be sure to override
748 GetNormal to return correct normal. }
749 TAbstractBumpMappingGenerator = class(TAbstractShaderAttribGenerator)
750 strict private
751 Tangent: TVector3;
752 CalculateTangents: Boolean;
753 protected
754 { If tangents are provided in the TAbstractComposedGeometryNode.FdTangent,
755 descendants should set them here. }
756 TangentsFromNode: TVector3List;
757
758 procedure PrepareAttributes(var AllowIndexed: boolean); override;
759 procedure GenerateCoordinateBegin; override;
760 procedure GenerateVertex(IndexNum: Integer); override;
761
762 { Update tangent vectors (Tangent, Bitangent).
763 Without this, bump mapping will be wrong.
764 Give triangle indexes (like IndexNum for GenerateVertex). }
765 procedure CalculateTangentVectors(
766 const TriangleIndex1, TriangleIndex2, TriangleIndex3: Integer);
767 end;
768
769 { Most complete implementation of arrays generator,
770 should be used to derive non-abstract renderers for nodes. }
771 TAbstractCompleteGenerator = TAbstractBumpMappingGenerator;
772
773 { TArraysGenerator ------------------------------------------------------ }
774
775 constructor TArraysGenerator.Create(AShape: TShape);
776 begin
777 inherited Create;
778
779 FShape := AShape;
780 FGeometry := FShape.Geometry;
781 FState := FShape.State;
782
783 Check(Geometry.InternalCoord(State, FCoord),
784 'TAbstractCoordinateRenderer is only for coordinate-based nodes');
785 CoordIndex := Geometry.CoordIndexField;
786 end;
787
788 function TArraysGenerator.GenerateArrays: TGeometryArrays;
789 var
790 AllowIndexed: boolean;
791 MaxIndex: UInt32;
792 begin
793 Arrays := TGeometryArrays.Create;
794 Result := Arrays;
795
796 { no geometry if coordinates are empty. Leave empty Arrays. }
797 if Coord = nil then Exit;
798
799 { initialize stuff for generating }
800 IndexesFromCoordIndex := nil;
801 try
802 ArrayIndexNum := -1;
803
804 PrepareIndexesPrimitives;
805
806 { Assert about Arrays.Counts.Sum. Note that even when
807 IndexesFromCoordIndex = nil, Arrays.Counts.Sum should usually be equal
808 to final Arrays.Count. But not always: it may not be equal
809 for invalid nodes, with non-complete triangle strips / fans etc.
810 (then Arrays.Counts will not contain all coordinates). }
811 Assert(
812 (Arrays.Counts = nil) or
813 (IndexesFromCoordIndex = nil) or
814 (Arrays.Counts.Sum = IndexesFromCoordIndex.Count) );
815
816 AllowIndexed := true;
817
818 if IndexesFromCoordIndex <> nil then
819 begin
820 Assert(CoordIndex <> nil);
821 { Do not check IndexesFromCoordIndex.Max when IndexesFromCoordIndex is empty.
822 The "Max" would be then 0 (it has to be, for an unsigned value),
823 and would cause invalid warnings on empty IndexedFaceSet
824 (with empty Coordinate and empty coordIndex). }
825 if IndexesFromCoordIndex.Count <> 0 then
826 begin
827 MaxIndex := IndexesFromCoordIndex.Max;
828
829 { check do we have enough coordinates. TGeometryArrays data may be passed
830 quite raw to OpenGL, so this may be our last chance to check correctness
831 and avoid passing data that would cause OpenGL errors. }
832 if MaxIndex >= Coord.Count then
833 begin
834 CoordIndex.WritelnWarning_WrongVertexIndex(Geometry.X3DType,
835 MaxIndex, Coord.Count);
836 Exit; { leave Arrays created but empty }
837 end;
838
839 {$ifdef GLIndexesShort}
840 { In case our indexes could not be expressed using TGeometryIndexList,
841 do not use indexes (i.e. leave Arrays.Indexes = nil).
842 This is important in case we have to use 16-bit indexes for OpenGLES
843 (when GLIndexesShort is defined and TGLIndex = UInt16)
844 but our input data needs larger indexes.
845
846 This code would actually compile when GLIndexesShort is not defined too,
847 but the condition is then always false (and causes FPC warning).
848
849 See GLIndexesShort notes for other approaches to it in the future. }
850 if MaxIndex > High(TGLIndex) then
851 AllowIndexed := false;
852 {$endif}
853 end;
854 end;
855
856 PrepareAttributes(AllowIndexed);
857
858 try
859 Arrays.CoordinatePreserveGeometryOrder := AllowIndexed or (IndexesFromCoordIndex = nil);
860 if Arrays.CoordinatePreserveGeometryOrder then
861 begin
862 if IndexesFromCoordIndex <> nil then
863 begin
864 { Set Arrays.Indexes to be equal to IndexesFromCoordIndex }
865 {$ifdef GLIndexesShort}
866 { Convert 32-bit indexes in IndexesFromCoordIndex into 16-bit indexes in Arrays.Indexes }
867 Arrays.Indexes := TGeometryIndexList.Create;
868 Arrays.Indexes.Assign(IndexesFromCoordIndex);
869 FreeAndNil(IndexesFromCoordIndex);
870 {$else}
871 { Just use 32-bit indexes in IndexesFromCoordIndex as Arrays.Indexes }
872 Arrays.Indexes := IndexesFromCoordIndex;
873 IndexesFromCoordIndex := nil;
874 {$endif}
875 end;
876
877 Arrays.Count := Coord.Count;
878 end else
879 begin
880 { Each AssignCoordinate, AssignAttribute will expand the IndexesFromCoordIndex,
881 to specify vertexes multiple times in this case. }
882 Arrays.Count := IndexesFromCoordIndex.Count;
883 Assert(Arrays.Indexes = nil); // leaving Arrays.Indexes empty
884 end;
885
886 AssignCoordinate('coordinates', Arrays.Position, Coord.Items.L, Coord.Items.ItemSize, Coord.Items.Count);
887
888 if LogShapes then
889 WritelnLog('Renderer', Format('Shape %s rendered:' + NL +
890 '- using original indexes (desired, makes more compact GPU representation (array count)): %s' + NL +
891 '- preserving geometry order (desired, makes updating CoordinateInterpolator faster): %s' + NL +
892 '- array count: %d', [
893 Shape.NiceName,
894 BoolToStr(AllowIndexed, true),
895 BoolToStr(Arrays.CoordinatePreserveGeometryOrder, true),
896 Arrays.Count
897 ]));
898
899 GenerateCoordinateBegin;
900 try
901 GenerateCoordinate;
902 finally GenerateCoordinateEnd; end;
903 except
904 on E: EAssignInterleavedRangeError do
905 WritelnWarning('X3D', Format('Invalid number of items in an attribute array for shape "%s": %s',
906 [Shape.NiceName, E.Message]));
907 end;
908 finally
909 FreeAndNil(IndexesFromCoordIndex);
910 FreeAndNil(TrivialIndexesFromCoordIndex);
911 end;
912 end;
913
914 procedure TArraysGenerator.AssignAttributeOrCoordinate(
915 const AttributeName: String;
916 const TargetPtr: Pointer; const TargetItemSize: SizeInt;
917 const SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
918 const TrivialIndex: Boolean);
919 begin
920 { Following TArraysGenerator.GenerateArrays logic, there are various cases:
921
922 - Arrays.CoordinatePreserveGeometryOrder = true
923
924 This means:
925 - Arrays.Indexes may be nil or non-nil
926 (it will be nil if geometry has no indexes, like LineSet, PointSet, TriangleSet;
927 it will be non-nil if geometry has indexes, like IndexedFaceSet, IndexedTriangleSet etc.)
928 - IndexesFromCoordIndex is nil when this function is called
929 (TArraysGenerator.GenerateArrays maybe saw it non-nil at some point)
930 - maybe something set "AllowIndexed := false" during PrepareAttributes,
931 maybe not.
932 AllowIndexed is ignored if geometry has no indexes anyway (LineSet, PointSet, TriangleSet).
933 - Arrays.Count = Coord.Count
934 - So the target data layout (in Arrays.AttributeArray) is in the same order
935 as source data (defined by SourcePtr, SourceItemSize, SourceCount)
936
937 - Arrays.CoordinatePreserveGeometryOrder = false
938
939 This means:
940 - Arrays.Indexes = nil
941 - IndexesFromCoordIndex <> nil
942 - something set "AllowIndexed := false" during PrepareAttributes
943 - So we have coordIndex on geometry, but we have to "expand" data when copying,
944 making it non-indexed, because for some reason we cannot render it indexed
945 }
946 if TrivialIndex then
947 begin
948 Assert(not Arrays.CoordinatePreserveGeometryOrder, 'Set AllowIndexed := false when there''s a possibility to call with TrivialIndex');
949 Assert(TrivialIndexesFromCoordIndex <> nil, 'Generate TrivialIndexesFromCoordIndex for all geometries that may call with TrivialIndex');
950 AssignToInterleavedIndexed(AttributeName, TargetPtr, TargetItemSize, Arrays.Count, SourcePtr, SourceItemSize, SourceCount, TrivialIndexesFromCoordIndex);
951 end else
952 if Arrays.CoordinatePreserveGeometryOrder then
953 AssignToInterleaved (AttributeName, TargetPtr, TargetItemSize, Arrays.Count, SourcePtr, SourceItemSize, SourceCount)
954 else
955 AssignToInterleavedIndexed(AttributeName, TargetPtr, TargetItemSize, Arrays.Count, SourcePtr, SourceItemSize, SourceCount, IndexesFromCoordIndex);
956 end;
957
958 procedure TArraysGenerator.AssignAttribute(const AttributeName: String;
959 const TargetPtr, SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
960 const TrivialIndex: Boolean);
961 begin
962 AssignAttributeOrCoordinate(AttributeName, TargetPtr, Arrays.AttributeSize, SourcePtr, SourceItemSize, SourceCount, TrivialIndex);
963 end;
964
965 procedure TArraysGenerator.AssignCoordinate(const AttributeName: String;
966 const TargetPtr, SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt;
967 const TrivialIndex: Boolean);
968 begin
969 AssignAttributeOrCoordinate(AttributeName, TargetPtr, Arrays.CoordinateSize, SourcePtr, SourceItemSize, SourceCount, TrivialIndex);
970 end;
971
972 procedure TArraysGenerator.PrepareAttributes(var AllowIndexed: boolean);
973 begin
974 if Geometry is TAbstractComposedGeometryNode then
975 begin
976 Arrays.CullFace := Geometry.Solid;
977 Arrays.FrontFaceCcw := (Geometry as TAbstractComposedGeometryNode).FdCcw.Value;
978 end;
979 end;
980
981 procedure TArraysGenerator.GenerateCoordinateBegin;
982 begin
983 { nothing to do in this class }
984 end;
985
986 procedure TArraysGenerator.GenerateCoordinateEnd;
987 begin
988 { nothing to do in this class }
989 end;
990
991 procedure TArraysGenerator.GenerateVertex(IndexNum: integer);
992 begin
993 if CoordIndex <> nil then
994 begin
995 if Arrays.Indexes = nil then
996 Inc(ArrayIndexNum) else
997 ArrayIndexNum := CoordIndex.Items.L[IndexNum];
998 end else
999 ArrayIndexNum := IndexNum;
1000 end;
1001
1002 function TArraysGenerator.GetVertex(IndexNum: integer): TVector3;
1003 begin
1004 { This assertion should never fail, it's the responsibility
1005 of the programmer. }
1006 Assert(IndexNum < CoordCount);
1007
1008 if CoordIndex <> nil then
1009 Result := Coord.ItemsSafe[CoordIndex.Items.L[IndexNum]]
1010 else
1011 Result := Coord.Items.L[IndexNum];
1012 end;
1013
1014 function TArraysGenerator.CoordCount: Integer;
1015 begin
1016 if CoordIndex <> nil then
1017 Result := CoordIndex.Items.Count
1018 else
1019 Result := Coord.Items.Count;
1020 end;
1021
1022 procedure TArraysGenerator.GenerateCoordsRange(
1023 const RangeNumber: Cardinal; BeginIndex, EndIndex: Integer);
1024 begin
1025 FCurrentRangeNumber := RangeNumber;
1026 end;
1027
1028 class function TArraysGenerator.BumpMappingAllowed: boolean;
1029 begin
1030 Result := false;
1031 end;
1032
1033 { TAbstractTextureCoordinateGenerator ----------------------------------------- }
1034
1035 constructor TAbstractTextureCoordinateGenerator.Create(AShape: TShape);
1036 begin
1037 inherited;
1038 if not Geometry.InternalTexCoord(State, TexCoord) then
1039 TexCoord := nil;
1040 end;
1041
1042 procedure TAbstractTextureCoordinateGenerator.PrepareAttributes(
1043 var AllowIndexed: boolean);
1044
1045 { Is a texture used on given unit, and it's 3D texture. }
1046 function IsTexture3D(const TexUnit: Cardinal): boolean;
1047
1048 { Knowing that Tex is not nil,
1049 check is it a single (not MultiTexture) 3D texture. }
1050 function IsSingleTexture3D(Tex: TX3DNode): boolean;
1051 begin
1052 Result :=
1053 (Tex is TAbstractTexture3DNode) or
1054 ((Tex is TShaderTextureNode) and
1055 (TShaderTextureNode(Tex).FdDefaultTexCoord.Value = 'BOUNDS3D'));
1056 end;
1057
1058 var
1059 Tex: TAbstractTextureNode;
1060 begin
1061 Tex := State.MainTexture;
1062 Result := (
1063 (Tex <> nil) and
1064 ( ( (TexUnit = 0) and IsSingleTexture3D(Tex) )
1065 or
1066 ( (Tex is TMultiTextureNode) and
1067 (TMultiTextureNode(Tex).FdTexture.Count > TexUnit) and
1068 IsSingleTexture3D(TMultiTextureNode(Tex).FdTexture[TexUnit])
1069 )));
1070 end;
1071
1072 { Set length of TexCoordArray* arrays. }
1073 procedure SetTexLengths(const Count: Integer);
1074 begin
1075 SetLength(TexCoordArray2d, Count);
1076 SetLength(TexCoordArray3d, Count);
1077 SetLength(TexCoordArray4d, Count);
1078 end;
1079
1080 function Bounds2DTextureGenVectors: TTextureGenerationVectors;
1081 var
1082 LocalBBox: TBox3D;
1083 LocalBBoxSize: TVector3;
1084
1085 { Setup and enable glTexGen to make automatic 2D texture coords
1086 based on shape bounding box. On texture unit 0. }
1087 procedure SetupCoordGen(out Gen: TVector4;
1088 const Coord: integer; const GenStart, GenEnd: Single);
1089
1090 { We want to map float from range
1091 LocalBBox[0, Coord]...LocalBBox[0, Coord] + LocalBBoxSize[Coord]
1092 to
1093 GenStart...GenEnd.
1094
1095 For a 3D point V let's define S1 as
1096 S1 = (V[Coord] - LocalBBox[0, Coord]) / LocalBBoxSize[Coord]
1097 and so S1 is in 0..1 range, now
1098 S = S1 * (GenEnd - GenStart) + GenStart
1099 and so S is in GenStart...GenEnd range, like we wanted.
1100
1101 It remains to rewrite this to a form that we can pass to OpenGL
1102 glTexGenfv(..., GL_OBJECT_PLANE, ...).
1103
1104 S = V[Coord] * (GenEnd - GenStart) / LocalBBoxSize[Coord]
1105 - LocalBBox[0, Coord] * (GenEnd - GenStart) / LocalBBoxSize[Coord]
1106 + GenStart
1107
1108 Simple check: for GenStart = 0, GenEnd = 1 this simplifies to
1109 S = V[Coord] / LocalBBoxSize[Coord] -
1110 LocalBBox[0, Coord] / LocalBBoxSize[Coord]
1111 = (V[Coord] - LocalBBox[0, Coord]) / LocalBBoxSize[Coord]
1112 = S1
1113 }
1114
1115 begin
1116 FillChar(Gen, SizeOf(Gen), 0);
1117 Gen.Data[Coord] := (GenEnd - GenStart) / LocalBBoxSize[Coord];
1118 Gen.Data[3] :=
1119 - LocalBBox.Data[0].Data[Coord] * (GenEnd - GenStart) / LocalBBoxSize[Coord]
1120 + GenStart;
1121 end;
1122
1123 var
1124 SCoord, TCoord: T3DAxis;
1125 begin
1126 LocalBBox := Shape.LocalBoundingBox;
1127
1128 if not LocalBBox.IsEmpty then
1129 begin
1130 LocalBBoxSize := LocalBBox.Size;
1131
1132 Geometry.GetTextureBounds2DST(LocalBBoxSize, SCoord, TCoord);
1133
1134 { Calculate TextureGen[0..1]. }
1135 SetupCoordGen(Result[0], SCoord, 0, 1);
1136 SetupCoordGen(Result[1], TCoord, 0, LocalBBoxSize[TCoord] / LocalBBoxSize[SCoord]);
1137 end else
1138 begin
1139 { When local bounding box is empty, set these to any sensible value }
1140 Result[0] := Vector4(1, 0, 0, 0);
1141 Result[1] := Vector4(0, 1, 0, 0);
1142 end;
1143
1144 Result[2] := Vector4(0, 0, 1, 0); //< whatever, just to be defined.
1145 end;
1146
1147 function Bounds3DTextureGenVectors: TTextureGenerationVectors;
1148 var
1149 Box: TBox3D;
1150 XStart, YStart, ZStart, XSize, YSize, ZSize: Single;
1151 begin
1152 Box := Shape.LocalBoundingBox;
1153
1154 if not Box.IsEmpty then
1155 begin
1156 { Texture S should range from 0..1 when X changes from X1 .. X2.
1157 So S = X / (X2 - X1) - X1 / (X2 - X1).
1158 Same for T.
1159 For R, X3D spec says that coords go backwards, so just SwapValues. }
1160
1161 SwapValues(Box.Data[0].Z, Box.Data[1].Z);
1162
1163 XStart := Box.Data[0].X;
1164 YStart := Box.Data[0].Y;
1165 ZStart := Box.Data[0].Z;
1166
1167 XSize := Box.Data[1].X - Box.Data[0].X;
1168 YSize := Box.Data[1].Y - Box.Data[0].Y;
1169 ZSize := Box.Data[1].Z - Box.Data[0].Z;
1170
1171 Result[0] := Vector4(1 / XSize, 0, 0, - XStart / XSize);
1172 Result[1] := Vector4(0, 1 / YSize, 0, - YStart / YSize);
1173 Result[2] := Vector4(0, 0, 1 / ZSize, - ZStart / ZSize);
1174 end else
1175 begin
1176 { When local bounding box is empty, set these to any sensible value }
1177 Result[0] := Vector4(1, 0, 0, 0);
1178 Result[1] := Vector4(0, 1, 0, 0);
1179 Result[2] := Vector4(0, 0, 1, 0);
1180 end;
1181 end;
1182
1183 { Initialize Arrays.TexCoords and TexCoordArray2/3/4d, based on TexCoord.
1184
1185 If any usable tex coords are found
1186 (that is, Arrays.TexCoords.Count <> 0 on exit) then this array
1187 contains at least TexCoordsNeeded units. }
1188 procedure InitializeTexCoordGenArray;
1189
1190 { Add single texture coord configuration
1191 to Arrays.TexCoord and TexCoordArray2/3/4d.
1192 Assume that TexCoordArray2/3/4d already have required length.
1193 Pass any TexCoord node except TMultiTextureCoordinateNode. }
1194 procedure AddSingleTexCoord(const TextureUnit: Cardinal; TexCoord: TX3DNode);
1195
1196 function TexCoordGenFromString(const S: string; const IsTexture3D: boolean): TTextureCoordinateGeneration;
1197 begin
1198 if S = 'SPHERE' then
1199 Result := tgSphereMap else
1200 if S = 'COORD' then
1201 Result := tgCoord else
1202 if (S = 'COORD-EYE') or (S = 'CAMERASPACEPOSITION') then
1203 Result := tgCoordEye else
1204 if S = 'CAMERASPACENORMAL' then
1205 Result := tgCameraSpaceNormal else
1206 if S = 'WORLDSPACENORMAL' then
1207 Result := tgWorldSpaceNormal else
1208 if S = 'CAMERASPACEREFLECTIONVECTOR' then
1209 Result := tgCameraSpaceReflectionVector else
1210 if S = 'WORLDSPACEREFLECTIONVECTOR' then
1211 Result := tgWorldSpaceReflectionVector else
1212 if S = 'PROJECTION' then
1213 Result := tgProjection else
1214 if S = 'BOUNDS' then
1215 begin
1216 if IsTexture3D then
1217 Result := tgBounds3d
1218 else
1219 Result := tgBounds2d;
1220 end else
1221 if S = 'BOUNDS2D' then
1222 Result := tgBounds2d else
1223 if S = 'BOUNDS3D' then
1224 Result := tgBounds3d else
1225 if S = 'MIRROR-PLANE' then
1226 Result := tgMirrorPlane else
1227 begin
1228 Result := tgCoord;
1229 WritelnWarning('X3D', Format('Unsupported TextureCoordinateGenerator.mode: "%s", will use "COORD" instead',
1230 [S]));
1231 end;
1232 end;
1233
1234 { For tgProjection generation, calculate function that should be
1235 later used to calculate matrix to pass to glTexGen as eye plane.
1236
1237 Gets projector matrices from a TextureCoordinateGenerator or
1238 ProjectedTextureCoordinate node.
1239 If this projector is a correct light source or viewpoint,
1240 then get it's projection and modelview matrix and return @true.
1241 Returns @false (and does correct WritelnWarning)
1242 if it's empty or incorrect. }
1243 function GetProjectorMatrixFunction(GeneratorNode: TX3DNode): TProjectorMatrixFunction;
1244 var
1245 ProjectorValue: TX3DNode; { possible ProjectorLight or ProjectorViewpoint }
1246 begin
1247 Result := nil;
1248
1249 if GeneratorNode is TTextureCoordinateGeneratorNode then
1250 begin
1251 ProjectorValue := TTextureCoordinateGeneratorNode(GeneratorNode).FdProjectedLight.Value;
1252 if (ProjectorValue <> nil) and
1253 (ProjectorValue is TAbstractPunctualLightNode) then
1254 begin
1255 Result := {$ifdef FPC}@{$endif}TAbstractPunctualLightNode(ProjectorValue).GetProjectorMatrix;
1256 end else
1257 WritelnWarning('X3D', 'Using TextureCoordinateGenerator.mode = "PROJECTION", but TextureCoordinateGenerator.projectedLight is NULL or incorrect');
1258 end else
1259 if GeneratorNode is TProjectedTextureCoordinateNode then
1260 begin
1261 ProjectorValue := TProjectedTextureCoordinateNode(GeneratorNode).FdProjector.Value;
1262 if ProjectorValue is TAbstractPunctualLightNode then // checks also ProjectorValue <> nil
1263 begin
1264 Result := {$ifdef FPC}@{$endif}TAbstractPunctualLightNode(ProjectorValue).GetProjectorMatrix;
1265 end else
1266 if ProjectorValue is TAbstractViewpointNode then // checks also ProjectorValue <> nil
1267 begin
1268 Result := {$ifdef FPC}@{$endif}TAbstractViewpointNode(ProjectorValue).GetProjectorMatrix;
1269 end else
1270 WritelnWarning('X3D', 'ProjectedTextureCoordinate.projector is NULL or incorrect');
1271 end else
1272 { This should not actually happen (GeneratorNode passed here should be like this) }
1273 WritelnWarning('X3D', 'Invalid texture generator node');
1274 end;
1275
1276 begin
1277 if TexCoord is TTextureCoordinateNode then
1278 begin
1279 Arrays.AddTexCoord2D(TextureUnit);
1280 TexCoordArray2d[TextureUnit] := TTextureCoordinateNode(TexCoord).FdPoint;
1281 end else
1282 if TexCoord is TTextureCoordinate2Node_1 then
1283 begin
1284 Arrays.AddTexCoord2D(TextureUnit);
1285 TexCoordArray2d[TextureUnit] := TTextureCoordinate2Node_1(TexCoord).FdPoint;
1286 end else
1287 if TexCoord is TTextureCoordinate3DNode then
1288 begin
1289 Arrays.AddTexCoord3D(TextureUnit);
1290 TexCoordArray3d[TextureUnit] := TTextureCoordinate3DNode(TexCoord).FdPoint;
1291 end else
1292 if TexCoord is TTextureCoordinate4DNode then
1293 begin
1294 Arrays.AddTexCoord4D(TextureUnit);
1295 TexCoordArray4d[TextureUnit] := TTextureCoordinate4DNode(TexCoord).FdPoint;
1296 end else
1297 if TexCoord is TTextureCoordinateGeneratorNode then
1298 begin
1299 Arrays.AddTexCoordGenerated(
1300 TexCoordGenFromString(TTextureCoordinateGeneratorNode(TexCoord).FdMode.Value,
1301 IsTexture3D(TextureUnit)), TextureUnit);
1302 end else
1303 if TexCoord is TProjectedTextureCoordinateNode then
1304 begin
1305 Arrays.AddTexCoordGenerated(tgProjection, TextureUnit);
1306 end else
1307 begin
1308 { dummy default }
1309 Arrays.AddTexCoordGenerated(tgBounds2d, TextureUnit);
1310 if TexCoord <> nil then
1311 WritelnWarning('X3D', Format('Unsupported texture coordinate node: %s, inside multiple texture coordinate', [TexCoord.X3DType])) else
1312 WritelnWarning('X3D', 'NULL texture coordinate node');
1313 end;
1314
1315 { Calculate some Generation-specific values }
1316 case Arrays.TexCoords[TextureUnit].Generation of
1317 tgBounds2d: Arrays.TexCoords[TextureUnit].GenerationBoundsVector := Bounds2DTextureGenVectors;
1318 tgBounds3d: Arrays.TexCoords[TextureUnit].GenerationBoundsVector := Bounds3DTextureGenVectors;
1319 tgProjection: Arrays.TexCoords[TextureUnit].GenerationProjectorMatrix := GetProjectorMatrixFunction(TexCoord);
1320 else ;
1321 end;
1322 end;
1323
1324 var
1325 MultiTexCoord: TMFNode;
1326 I, LastCoord: Integer;
1327 begin
1328 if TexCoord = nil then
1329 begin
1330 { Leave TexCoords.Count = 0, no WritelnWarning }
1331 Exit;
1332 end else
1333 if TexCoord is TMultiTextureCoordinateNode then
1334 begin
1335 MultiTexCoord := TMultiTextureCoordinateNode(TexCoord).FdTexCoord;
1336 SetTexLengths(MultiTexCoord.Count);
1337 for I := 0 to MultiTexCoord.Count - 1 do
1338 AddSingleTexCoord(I, MultiTexCoord[I]);
1339 end else
1340 begin
1341 SetTexLengths(1);
1342 AddSingleTexCoord(0, TexCoord);
1343 end;
1344
1345 Assert(Arrays.TexCoords.Count = Length(TexCoordArray2d));
1346 Assert(Arrays.TexCoords.Count = Length(TexCoordArray3d));
1347 Assert(Arrays.TexCoords.Count = Length(TexCoordArray4d));
1348
1349 if (Arrays.TexCoords.Count <> 0) and
1350 (Arrays.TexCoords.Count < TexCoordsNeeded) then
1351 begin
1352 LastCoord := Arrays.TexCoords.Count - 1;
1353 SetTexLengths(TexCoordsNeeded);
1354
1355 { We copy tex coord LastCoord values to all following items.
1356 This way we do what X3D spec says:
1357 - if non-MultiTextureCoordinate is used for multitexturing,
1358 channel 0 is replicated
1359 - if MultiTextureCoordinate is used, but with too few items,
1360 last channel is replicated. }
1361 for I := LastCoord + 1 to TexCoordsNeeded - 1 do
1362 begin
1363 Arrays.AddTexCoordCopy(I, LastCoord);
1364 TexCoordArray2d[I] := TexCoordArray2d[LastCoord];
1365 TexCoordArray3d[I] := TexCoordArray3d[LastCoord];
1366 TexCoordArray4d[I] := TexCoordArray4d[LastCoord];
1367 end;
1368 end;
1369 end;
1370
1371 { Setup 2D texture coordinates suitable for IndexedFaceSet without
1372 explicit texture coords, following X3D 3D Texturing spec.
1373 We set texture generation to tgBounds2d
1374 on all texture units within TexCoordsNeeded.
1375 We also set TexImplementation := tcAllGenerated. }
1376 procedure Bounds2DTextureGen;
1377 var
1378 I: integer;
1379 TexGenVectors: TTextureGenerationVectors;
1380 begin
1381 TexGenVectors := Bounds2DTextureGenVectors;
1382
1383 TexImplementation := tcAllGenerated;
1384 SetTexLengths(TexCoordsNeeded);
1385 for I := 0 to TexCoordsNeeded - 1 do
1386 begin
1387 Arrays.AddTexCoordGenerated(tgBounds2d, I);
1388 Arrays.TexCoords[I].GenerationBoundsVector := TexGenVectors;
1389 end;
1390 end;
1391
1392 { Setup 3D texture coordinates suitable for "primitives without
1393 explicit texture coordinates", following X3D 3D Texturing spec.
1394 We set tgBounds3d on all texture units within TexCoordsNeeded.
1395 We also set TexImplementation := tcAllGenerated. }
1396 procedure Bounds3DTextureGen;
1397 var
1398 I: Integer;
1399 TexGenVectors: TTextureGenerationVectors;
1400 begin
1401 TexGenVectors := Bounds3DTextureGenVectors;
1402
1403 TexImplementation := tcAllGenerated;
1404 SetTexLengths(TexCoordsNeeded);
1405 for I := 0 to TexCoordsNeeded - 1 do
1406 begin
1407 Arrays.AddTexCoordGenerated(tgBounds3d, I);
1408 Arrays.TexCoords[I].GenerationBoundsVector := TexGenVectors;
1409 end;
1410 end;
1411
1412 begin
1413 inherited;
1414
1415 TexImplementation := tcNotGenerated;
1416
1417 { Make sure they are initially empty. }
1418 Assert(Arrays.TexCoords.Count = 0);
1419 Assert(Length(TexCoordArray2d) = 0);
1420 Assert(Length(TexCoordArray3d) = 0);
1421 Assert(Length(TexCoordArray4d) = 0);
1422
1423 if TexCoordsNeeded > 0 then
1424 begin
1425 if { Original shape node is a primitive, without explicit texCoord }
1426 Shape.OriginalGeometry.AutoGenerate3DTexCoords and
1427 { First texture is 3D texture }
1428 IsTexture3D(0) then
1429 begin
1430 Bounds3DTextureGen;
1431 end else
1432
1433 { Handle VRML 1.0 case when TexCoord present but TexCoordIndex empty
1434 before calling InitializeTexCoordGenArray. That's because we have
1435 to ignore TexCoord in this case (so says VRML 1.0 spec, and it's
1436 sensible since for VRML 1.0 there is always some last TexCoord node).
1437 So we don't want to let InitializeTexCoordGenArray to call
1438 any Arrays.AddTexCoord. }
1439 if (State.ShapeNode = nil) and
1440 (TexCoordIndex <> nil) and
1441 (TexCoordIndex.Count < CoordIndex.Count) then
1442 begin
1443 Bounds2DTextureGen;
1444 end else
1445
1446 begin
1447 InitializeTexCoordGenArray;
1448 if Arrays.TexCoords.Count > 0 then
1449 begin
1450 if TexCoordIndex = nil then
1451 begin
1452 { This happens only for X3D non-indexed primitives:
1453 Triangle[Fan/Strip]Set, QuadSet. Spec says that TexCoord should be
1454 used just like Coord, so IndexNum indexes it directly. }
1455 TexImplementation := tcNonIndexed;
1456 Assert(CoordIndex = nil);
1457 end else
1458 if { Use texIndexed if texture coordinates are indexed by *something else*
1459 than CoordIndex. So check "TexCoordIndex <> CoordIndex".
1460
1461 In case of X3D primitives like IndexedTriangle[Fan/Strip]Set, QuadSet,
1462 they always have TexCoordIndex = CoordIndex (just taken from "index" field).
1463 And we don't want to use tcTexIndexed for them (because it is less optimal,
1464 as sets AllowIndexed=false, CoordinatePreserveGeometryOrder=false). }
1465 (TexCoordIndex <> CoordIndex) and
1466 (TexCoordIndex.Count >= CoordIndex.Count) then
1467 begin
1468 TexImplementation := tcTexIndexed;
1469 end else
1470 begin
1471 { X3D primitives like IndexedTriangle[Fan/Strip]Set, QuadSet
1472 will arrive here, because they always have TexCoordIndex = CoordIndex.
1473
1474 Others will arrive here when TexCoord <> nil
1475 (non-zero Arrays.TexCoords.Count guarantees this)
1476 but TexCoordIndex is empty. Then:
1477
1478 - VRML 2.0 spec of IndexedFaceSet says that coordIndex is used
1479 to index texture coordinates.
1480
1481 - VRML 1.0 spec says that in this case default texture
1482 coordinates should be generated (that's because for
1483 VRML 1.0 there is always some TexCoord <> nil,
1484 so it cannot be used to produce different behavior).
1485 We handled this case in code above.
1486 }
1487 Assert(State.ShapeNode <> nil);
1488 TexImplementation := tcCoordIndexed;
1489 end;
1490 end else
1491 Bounds2DTextureGen;
1492 end;
1493 end;
1494
1495 if TexImplementation in [tcTexIndexed, tcNonIndexed] then
1496 AllowIndexed := false;
1497 end;
1498
1499 procedure TAbstractTextureCoordinateGenerator.GenerateCoordinateBegin;
1500
1501 { Set explicit texture coordinates in Arrays,
1502 for texture units where Arrays.TexCoords[].Generation = tgExplicit.
1503 This is only for TexImplementation in [tcNonIndexed, tcCoordIndexed],
1504 other TexImplementation have to be handled elsewhere. }
1505 procedure EnableExplicitTexCoord;
1506 var
1507 I: Integer;
1508 begin
1509 for I := 0 to Arrays.TexCoords.Count - 1 do
1510 if Arrays.TexCoords[I].Generation = tgExplicit then
1511 case Arrays.TexCoords[I].Dimensions of
1512 2: AssignAttribute('2D texture coordinates', Arrays.TexCoord(I), TexCoordArray2d[I].Items.L, TexCoordArray2d[I].Items.ItemSize, TexCoordArray2d[I].Items.Count);
1513 3: AssignAttribute('3D texture coordinates', Arrays.TexCoord(I), TexCoordArray3d[I].Items.L, TexCoordArray3d[I].Items.ItemSize, TexCoordArray3d[I].Items.Count);
1514 4: AssignAttribute('4D texture coordinates', Arrays.TexCoord(I), TexCoordArray4d[I].Items.L, TexCoordArray4d[I].Items.ItemSize, TexCoordArray4d[I].Items.Count);
1515 end;
1516 end;
1517
1518 begin
1519 inherited;
1520
1521 if TexImplementation in [tcNonIndexed, tcCoordIndexed] then
1522 EnableExplicitTexCoord;
1523 end;
1524
1525 function TAbstractTextureCoordinateGenerator.GetTextureCoord(
1526 IndexNum: integer; const TextureUnit: Cardinal;
1527 out Tex: TVector4): boolean;
1528
1529 function GenerateTexCoord(const TexCoord: TGeometryTexCoord): TVector4;
1530 var
1531 Vertex: TVector3;
1532 begin
1533 case TexCoord.Generation of
1534 tgBounds2d:
1535 begin
1536 Vertex := GetVertex(IndexNum);
1537 Result.X := TVector4.DotProduct(Vector4(Vertex, 1), TexCoord.GenerationBoundsVector[0]);
1538 Result.Y := TVector4.DotProduct(Vector4(Vertex, 1), TexCoord.GenerationBoundsVector[1]);
1539 Result.Z := 0;
1540 Result.W := 1;
1541 end;
1542 tgBounds3d:
1543 begin
1544 Vertex := GetVertex(IndexNum);
1545 Result.X := TVector4.DotProduct(Vector4(Vertex, 1), TexCoord.GenerationBoundsVector[0]);
1546 Result.Y := TVector4.DotProduct(Vector4(Vertex, 1), TexCoord.GenerationBoundsVector[1]);
1547 Result.Z := TVector4.DotProduct(Vector4(Vertex, 1), TexCoord.GenerationBoundsVector[2]);
1548 Result.W := 1;
1549 end;
1550 tgCoord:
1551 begin
1552 Vertex := GetVertex(IndexNum);
1553 Result.X := Vertex.X;
1554 Result.Y := Vertex.Y;
1555 Result.Z := Vertex.Z;
1556 Result.W := 1;
1557 end;
1558 else WritelnWarning('X3D', Format('Generating on CPU texture coordinates with %d not implemented yet',
1559 [Integer(TexCoord.Generation)]));
1560 end;
1561 end;
1562
1563 { Sets Tex to TexCoordArray*[TextureUnit][Index] value. }
1564 procedure SetTexFromTexCoordArray(const Dimensions: TTexCoordDimensions;
1565 const Index: Integer);
1566 var
1567 Tex2d: TVector2 absolute Tex;
1568 Tex3d: TVector3 absolute Tex;
1569 begin
1570 case Dimensions of
1571 2: Tex2d := TexCoordArray2d[TextureUnit].ItemsSafe[Index];
1572 3: Tex3d := TexCoordArray3d[TextureUnit].ItemsSafe[Index];
1573 4: Tex := TexCoordArray4d[TextureUnit].ItemsSafe[Index];
1574 end;
1575 end;
1576
1577 begin
1578 Result := TexImplementation <> tcNotGenerated;
1579
1580 if Result then
1581 begin
1582 { This assertion should never fail, it's the responsibility
1583 of the programmer. Note that we don't need any TexCoordCount
1584 here, since IndexNum allowed for GetTextureCoord are the same
1585 and come from the same range as coords. }
1586 Assert(IndexNum < CoordCount);
1587
1588 { Initialize to common values }
1589 Tex := Vector4(0, 0, 0, 1);
1590
1591 Result := TextureUnit < Arrays.TexCoords.Count;
1592 if not Result then Exit;
1593
1594 if Arrays.TexCoords[TextureUnit].Generation = tgExplicit then
1595 begin
1596 case TexImplementation of
1597 tcTexIndexed:
1598 { tcTexIndexed is set only if
1599 TexCoordIndex.Count >= CoordIndex.Count, so the IndexNum index
1600 is Ok for sure. That's why we don't do "ItemsSafe"
1601 for TexCoordIndex. }
1602 SetTexFromTexCoordArray(Arrays.TexCoords[TextureUnit].Dimensions, TexCoordIndex.Items.L[IndexNum]);
1603 tcCoordIndexed:
1604 { We already checked that IndexNum < CoordCount, so the first index
1605 is Ok for sure. }
1606 SetTexFromTexCoordArray(Arrays.TexCoords[TextureUnit].Dimensions, CoordIndex.Items.L[IndexNum]);
1607 tcNonIndexed:
1608 SetTexFromTexCoordArray(Arrays.TexCoords[TextureUnit].Dimensions, IndexNum);
1609 else raise EInternalError.Create('TAbstractTextureCoordinateGenerator.GetTextureCoord?');
1610 end;
1611 end else
1612 Tex := GenerateTexCoord(Arrays.TexCoords[TextureUnit]);
1613 end;
1614 end;
1615
1616 function TAbstractTextureCoordinateGenerator.GetTextureCoord(
1617 IndexNum: integer; const TextureUnit: Cardinal;
1618 out Tex: TVector2): boolean;
1619 var
1620 Tex4f: TVector4;
1621 begin
1622 Result := GetTextureCoord(IndexNum, TextureUnit, Tex4f);
1623 Tex.X := Tex4f.X;
1624 Tex.Y := Tex4f.Y;
1625 end;
1626
1627 procedure TAbstractTextureCoordinateGenerator.GenerateVertex(indexNum: integer);
1628
1629 procedure DoTexCoord(Index: Integer);
1630 var
1631 TextureUnit: Integer;
1632 begin
1633 Assert(Arrays.Indexes = nil);
1634 for TextureUnit := 0 to Arrays.TexCoords.Count - 1 do
1635 if Arrays.TexCoords[TextureUnit].Generation = tgExplicit then
1636 case Arrays.TexCoords[TextureUnit].Dimensions of
1637 2: Arrays.TexCoord2D(TextureUnit, ArrayIndexNum)^ := TexCoordArray2d[TextureUnit].ItemsSafe[Index];
1638 3: Arrays.TexCoord3D(TextureUnit, ArrayIndexNum)^ := TexCoordArray3d[TextureUnit].ItemsSafe[Index];
1639 4: Arrays.TexCoord4D(TextureUnit, ArrayIndexNum)^ := TexCoordArray4d[TextureUnit].ItemsSafe[Index];
1640 end;
1641 end;
1642
1643 begin
1644 inherited;
1645
1646 { Observe that tcTexIndexed (seldom case, not even possible in glTF) is much worse optimized than
1647 tcNonIndexed or tcCoordIndexed (common case).
1648 tcTexIndexed needs to be performed in GenerateVertex.
1649
1650 I considered optimizing tcTexIndexed, but it would hurt the common case.
1651
1652 - We would need to extend AssignAttributeOrCoordinate to handle "IndexForSource: TInt32List".
1653
1654 - To implement IndexForSource, we must know how indexes (from coordIndex) map
1655 to vertexes. This information is no longer present in IndexesFromCoordIndex,
1656 as IndexesFromCoordIndex doesn't correspond to coordIndex anymore
1657 (e.g. coordIndex may have -1 in case of IndexedFaceSet,
1658 but IndexesFromCoordIndex has only >= indexes,
1659 after faces have been triangulated).
1660
1661 - So it would require creating IndexesFromCoordIndexMap, that maps index of indexes -> where to find it.
1662 E.g. instead of this:
1663
1664 IndexesFromCoordIndex.L[IFSNextIndex] := CoordIndex.Items.L[BeginIndex]; Inc(IFSNextIndex);
1665 IndexesFromCoordIndex.L[IFSNextIndex] := CoordIndex.Items.L[I + 1]; Inc(IFSNextIndex);
1666 IndexesFromCoordIndex.L[IFSNextIndex] := CoordIndex.Items.L[I + 2]; Inc(IFSNextIndex);
1667
1668 => we would need this:
1669
1670 IndexesFromCoordIndexMap.L[IFSNextIndex] := BeginIndex; Inc(IFSNextIndex);
1671 IndexesFromCoordIndexMap.L[IFSNextIndex] := I + 1; Inc(IFSNextIndex);
1672 IndexesFromCoordIndexMap.L[IFSNextIndex] := I + 2; Inc(IFSNextIndex);
1673
1674 - However, in many cases this IndexesFromCoordIndexMap would be useless.
1675 For tcNonIndexed or tcCoordIndexed it would be useless.
1676 And so making IndexesFromCoordIndexMap would be a waste of time.
1677 E.g. right now IndexedTriangleSetNode does this in TTriangleSetGenerator.PrepareIndexesPrimitives:
1678
1679 IndexesFromCoordIndex := TUInt32List.Create;
1680 IndexesFromCoordIndex.Assign(CoordIndex.Items);
1681 IndexesFromCoordIndex.Count := (IndexesFromCoordIndex.Count div 3) * 3;
1682
1683 It would require extra iteration instead of simple "IndexesFromCoordIndex.Assign"
1684 to create IndexedTriangleSetNode.
1685 }
1686 if TexImplementation = tcTexIndexed then
1687 DoTexCoord(TexCoordIndex.Items.L[IndexNum]);
1688 end;
1689
1690 { TAbstractMaterial1Generator ------------------------------------------ }
1691
1692 {$warnings off} // using deprecated to keep supporting VRML 1
1693 constructor TAbstractMaterial1Generator.Create(AShape: TShape);
1694 begin
1695 inherited;
1696 MaterialBinding := BIND_DEFAULT;
1697 UpdateMat1Implementation;
1698 end;
1699
1700 procedure TAbstractMaterial1Generator.UpdateMat1Implementation;
1701
1702 function IndexListNotEmpty(MFIndexes: TMFLong): boolean;
1703 begin
1704 Result :=
1705 (MFIndexes.Count > 0) and
1706 { For VRML 1.0, [-1] value is default for materialIndex
1707 and should be treated as "empty", as far as I understand
1708 the spec. }
1709 (not ((MFIndexes.Count = 1) and (MFIndexes.Items.L[0] = -1)));
1710 end;
1711
1712 begin
1713 { Calculate Mat1Implementation }
1714
1715 Mat1Implementation := miOverall;
1716
1717 case MaterialBinding of
1718 { BIND_OVERALL, BIND_DEFAULT: take default miOverall }
1719 BIND_PER_VERTEX:
1720 Mat1Implementation := miPerVertexCoordIndexed;
1721 BIND_PER_VERTEX_INDEXED:
1722 if IndexListNotEmpty(MaterialIndex) then
1723 Mat1Implementation := miPerVertexMatIndexed;
1724 BIND_PER_PART, BIND_PER_FACE:
1725 Mat1Implementation := miPerFace;
1726 BIND_PER_PART_INDEXED, BIND_PER_FACE_INDEXED:
1727 if IndexListNotEmpty(MaterialIndex) then
1728 Mat1Implementation := miPerFaceMatIndexed;
1729 end;
1730
1731 { TODO: we handle all material bindings, but we handle BIND_PER_PART
1732 and BIND_PER_PART_INDEXED wrong for IndexedLineSet. }
1733 end;
1734 {$warnings on}
1735
1736 procedure TAbstractMaterial1Generator.PrepareAttributes(var AllowIndexed: boolean);
1737 begin
1738 inherited;
1739
1740 if Mat1Implementation in
1741 [ miPerFace, miPerFaceMatIndexed,
1742 miPerVertexCoordIndexed, miPerVertexMatIndexed ] then
1743 begin
1744 Arrays.AddColor(cmReplace, true);
1745 if Mat1Implementation in
1746 [ miPerFace, miPerFaceMatIndexed, miPerVertexMatIndexed ] then
1747 AllowIndexed := false;
1748 end;
1749 end;
1750
1751 function TAbstractMaterial1Generator.GetMaterial1Color(
1752 const MaterialIndex: Integer): TVector4;
1753 var
1754 M: TPhongMaterialInfo; // VRML 1.0 has only Phong lighting model
1755 begin
1756 M := State.VRML1State.Material.MaterialInfo(MaterialIndex);
1757 if M.PureEmissive then
1758 Result := Vector4(M.EmissiveColor, M.Opacity)
1759 else
1760 Result := Vector4(M.DiffuseColor, M.Opacity);
1761 end;
1762
1763 procedure TAbstractMaterial1Generator.GenerateVertex(IndexNum: Integer);
1764 begin
1765 inherited;
1766 case Mat1Implementation of
1767 miPerVertexCoordIndexed:
1768 Arrays.ColorRgbAlpha(ArrayIndexNum)^ := GetMaterial1Color(CoordIndex.ItemsSafe[IndexNum]);
1769 miPerVertexMatIndexed:
1770 Arrays.ColorRgbAlpha(ArrayIndexNum)^ := GetMaterial1Color(MaterialIndex.ItemsSafe[IndexNum]);
1771 miPerFace, miPerFaceMatIndexed:
1772 Arrays.ColorRgbAlpha(ArrayIndexNum)^ := FaceMaterial1Color;
1773 else ;
1774 end;
1775 end;
1776
1777 procedure TAbstractMaterial1Generator.GenerateCoordsRange(
1778 const RangeNumber: Cardinal; BeginIndex, EndIndex: Integer);
1779 begin
1780 inherited;
1781
1782 case Mat1Implementation of
1783 miPerFace:
1784 FaceMaterial1Color := GetMaterial1Color(RangeNumber);
1785 miPerFaceMatIndexed:
1786 FaceMaterial1Color := GetMaterial1Color(MaterialIndex.Items.L[RangeNumber]);
1787 else ;
1788 end;
1789 end;
1790
1791 { TAbstractColorGenerator --------------------------------------- }
1792
1793 procedure TAbstractColorGenerator.PrepareAttributes(var AllowIndexed: boolean);
1794 begin
1795 inherited;
1796
1797 if ColorNode <> nil then
1798 begin
1799 Assert((Color <> nil) or (ColorRGBA <> nil));
1800 Arrays.AddColor(ColorNode.Mode, ColorRGBA <> nil);
1801 { In case of X3D primitives like IndexedTriangle[Fan/Strip]Set,
1802 ColorIndex is set but always equal to CoordIndex.
1803 This means we don't have to disable AllowIndexed (which is beneficial for speed).
1804
1805 Testcase: test examples/fps_game/data/knight_creature/knight.gltf
1806 with LogShapes, observe it should have AllowIndexed=true
1807 and CoordinatePreserveGeometryOrder=true. }
1808 if ((ColorIndex <> nil) and (ColorIndex <> CoordIndex)) or
1809 (not ColorPerVertex) then
1810 AllowIndexed := false;
1811 end;
1812 end;
1813
1814 function TAbstractColorGenerator.UseColorIndex: Boolean;
1815 begin
1816 Result := (ColorIndex <> nil) and (ColorIndex.Count <> 0);
1817 end;
1818
1819 procedure TAbstractColorGenerator.GenerateCoordinateBegin;
1820 begin
1821 inherited;
1822
1823 { This method, and GenerateVertex, closely fill all possible cases.
1824 When possible, this method (which results in more optimal code) takes care
1825 of the job, and then GenerateVertex does nothing. }
1826
1827 if Color <> nil then
1828 begin
1829 if ColorPerVertex then
1830 begin
1831 if not UseColorIndex then
1832 AssignAttribute('colors', Arrays.ColorRgb, Color.Items.L, Color.Items.ItemSize, Color.Items.Count);
1833 end;
1834 end else
1835 if ColorRGBA <> nil then
1836 begin
1837 if ColorPerVertex then
1838 begin
1839 if not UseColorIndex then
1840 AssignAttribute('RGB colors', Arrays.ColorRgbAlpha, ColorRGBA.Items.L, ColorRGBA.Items.ItemSize, ColorRGBA.Items.Count);
1841 end;
1842 end;
1843 end;
1844
1845 procedure TAbstractColorGenerator.GenerateVertex(IndexNum: integer);
1846 begin
1847 inherited;
1848 if Color <> nil then
1849 begin
1850 if ColorPerVertex then
1851 begin
1852 if UseColorIndex then
1853 Arrays.ColorRgb(ArrayIndexNum)^ := Color.ItemsSafe[ColorIndex.ItemsSafe[IndexNum]];
1854 end else
1855 Arrays.ColorRgb(ArrayIndexNum)^ := FaceColorRgb;
1856 end else
1857 if ColorRGBA <> nil then
1858 begin
1859 if ColorPerVertex then
1860 begin
1861 if UseColorIndex then
1862 Arrays.ColorRgbAlpha(ArrayIndexNum)^ := ColorRGBA.ItemsSafe[ColorIndex.ItemsSafe[IndexNum]];
1863 end else
1864 Arrays.ColorRgbAlpha(ArrayIndexNum)^ := FaceColorRgbAlpha;
1865 end;
1866 end;
1867
1868 procedure TAbstractColorGenerator.GenerateCoordsRange(
1869 const RangeNumber: Cardinal; BeginIndex, EndIndex: Integer);
1870 begin
1871 inherited;
1872
1873 { Implement different color per face here. }
1874 if (Color <> nil) and (not ColorPerVertex) then
1875 begin
1876 if UseColorIndex then
1877 FaceColorRgb := Color.ItemsSafe[ColorIndex.ItemsSafe[RangeNumber]]
1878 else
1879 FaceColorRgb := Color.ItemsSafe[RangeNumber];
1880 end else
1881 if (ColorRGBA <> nil) and (not ColorPerVertex) then
1882 begin
1883 if UseColorIndex then
1884 FaceColorRgbAlpha := ColorRGBA.ItemsSafe[ColorIndex.ItemsSafe[RangeNumber]]
1885 else
1886 FaceColorRgbAlpha := ColorRGBA.ItemsSafe[RangeNumber];
1887 end;
1888 end;
1889
1890 { TAbstractNormalGenerator ----------------------------------------------------- }
1891
1892 procedure TAbstractNormalGenerator.PrepareAttributes(
1893 var AllowIndexed: boolean);
1894 begin
1895 inherited;
1896
1897 if not (
1898 { When IndexNum for normal works exactly like for position,
1899 then normals can be indexed. This is true in two cases:
1900 - there is no coordIndex, and normal vectors are not indexed
1901 - there is coordIndex, and normal vectors are indexed by coordIndex
1902 - also niOverall, niUnlit can work in every possible case
1903 (they just set the same value always).
1904
1905 Note that when niPerVertexNonIndexed and CoordIndex <> nil,
1906 then we set AllowIndexed := false.
1907 This happens in particular when we have auto-generated normals based
1908 on creaseAngle in IndexedFaceSet.
1909 Testcase: auto_normals_indexed_geometry.x3dv
1910 }
1911 (NorImplementation in [niPerVertexCoordIndexed, niOverall, niUnlit]) or
1912 ((NorImplementation = niPerVertexNonIndexed) and (CoordIndex = nil)) ) then
1913 AllowIndexed := false;
1914 end;
1915
1916 {$warnings off} // using deprecated to keep supporting VRML 1
1917 function TAbstractNormalGenerator.
1918 NorImplementationFromVRML1Binding(NormalBinding: Integer): TNormalsImplementation;
1919 begin
1920 Result := niNone;
1921
1922 if (Normals = nil) or (NormalIndex = nil) then
1923 Exit;
1924
1925 case NormalBinding of
1926 BIND_DEFAULT, BIND_PER_VERTEX_INDEXED:
1927 if (NormalIndex.Count > 0) and (NormalIndex.Items.L[0] >= 0) then
1928 Result := niPerVertexNormalIndexed;
1929 BIND_PER_VERTEX:
1930 if CoordIndex <> nil then
1931 Result := niPerVertexCoordIndexed;
1932 BIND_OVERALL:
1933 if Normals.Count > 0 then
1934 Result := niOverall;
1935 BIND_PER_PART, BIND_PER_FACE:
1936 Result := niPerFace;
1937 BIND_PER_PART_INDEXED, BIND_PER_FACE_INDEXED:
1938 if (NormalIndex.Count > 0) and (NormalIndex.Items.L[0] >= 0) then
1939 Result := niPerFaceNormalIndexed;
1940 end;
1941
1942 { If no normals are provided (for VRML 1.0, this means that last Normal
1943 node was empty, or it's the default empty node from VRML1DefaultState)
1944 then generate normals. }
1945 if Normals.Count = 0 then
1946 Result := niNone;
1947 end;
1948 {$warnings on}
1949
1950 function TAbstractNormalGenerator.NormalsSafe(const Index: Integer): TVector3;
1951 begin
1952 if Index < Normals.Count then
1953 Result := Normals.L[Index]
1954 else
1955 Result := TVector3.Zero;
1956 end;
1957
1958 procedure TAbstractNormalGenerator.GetNormal(
1959 IndexNum: Integer; RangeNumber: Integer; out N: TVector3);
1960 begin
1961 case NorImplementation of
1962 niOverall:
1963 N := Normals.L[0];
1964 niUnlit:
1965 N := TVector3.Zero; // return anything defined
1966 niPerVertexNonIndexed:
1967 N := Normals.L[IndexNum];
1968 niPerVertexCoordIndexed:
1969 N := Normals.L[CoordIndex.Items.L[IndexNum]];
1970 niPerVertexNormalIndexed:
1971 N := Normals.L[NormalIndex.ItemsSafe[IndexNum]];
1972 niPerFace:
1973 N := Normals.L[RangeNumber];
1974 niPerFaceNormalIndexed:
1975 N := Normals.L[NormalIndex.ItemsSafe[RangeNumber]];
1976 else
1977 raise EInternalError.CreateFmt('NorImplementation unknown (probably niNone, and not overridden GetNormal) in class %s',
1978 [ClassName]);
1979 end;
1980 end;
1981
1982 function TAbstractNormalGenerator.NormalsFlat: boolean;
1983 begin
1984 Result := NorImplementation in [niUnlit, niOverall, niPerFace, niPerFaceNormalIndexed];
1985 end;
1986
1987 procedure TAbstractNormalGenerator.GenerateVertex(IndexNum: Integer);
1988 begin
1989 inherited;
1990 case NorImplementation of
1991 niPerVertexNormalIndexed:
1992 begin
1993 Assert(Arrays.Indexes = nil);
1994 Arrays.Normal(ArrayIndexNum)^ := NormalsSafe(NormalIndex.ItemsSafe[IndexNum]);
1995 end;
1996 niPerVertexNonIndexed:
1997 if CoordIndex <> nil then
1998 begin
1999 Assert(Arrays.Indexes = nil);
2000 Arrays.Normal(ArrayIndexNum)^ := NormalsSafe(IndexNum);
2001 end;
2002 niPerFace, niPerFaceNormalIndexed:
2003 begin
2004 Assert(Arrays.Indexes = nil);
2005 Arrays.Normal(ArrayIndexNum)^ := FaceNormal;
2006 end;
2007 else ;
2008 end;
2009 end;
2010
2011 procedure TAbstractNormalGenerator.GenerateCoordinateBegin;
2012
2013 procedure SetAllNormals(const Value: TVector3);
2014 begin
2015 AssignToInterleavedConstant(Arrays.Normal, Arrays.CoordinateSize, Arrays.Count, @Value, SizeOf(TVector3));
2016 end;
2017
2018 begin
2019 inherited;
2020
2021 case NorImplementation of
2022 niPerVertexCoordIndexed:
2023 AssignCoordinate('normals', Arrays.Normal, Normals.L, Normals.ItemSize, Normals.Count);
2024 niPerVertexNonIndexed:
2025 AssignCoordinate('normals', Arrays.Normal, Normals.L, Normals.ItemSize, Normals.Count, CoordIndex <> nil);
2026 niOverall: SetAllNormals(NormalsSafe(0));
2027 niUnlit: SetAllNormals(TVector3.Zero);
2028 else ;
2029 end;
2030 end;
2031
2032 procedure TAbstractNormalGenerator.GenerateCoordinateEnd;
2033 begin
2034 inherited;
2035 end;
2036
2037 procedure TAbstractNormalGenerator.GenerateCoordsRange(
2038 const RangeNumber: Cardinal; BeginIndex, EndIndex: Integer);
2039 begin
2040 inherited;
2041
2042 { FaceNormal will be actually copied to Arrays.Normal in GenerateVertex
2043 for this face. }
2044 case NorImplementation of
2045 niPerFace:
2046 FaceNormal := NormalsSafe(RangeNumber);
2047 niPerFaceNormalIndexed:
2048 FaceNormal := NormalsSafe(NormalIndex.ItemsSafe[RangeNumber]);
2049 else ;
2050 end;
2051 end;
2052
2053 { TAbstractFogGenerator --------------------------------- }
2054
2055 constructor TAbstractFogGenerator.Create(AShape: TShape);
2056 begin
2057 inherited;
2058
2059 if Geometry.InternalFogCoord <> nil then
2060 FogCoord := Geometry.InternalFogCoord.Items;
2061 end;
2062
2063 procedure TAbstractFogGenerator.PrepareAttributes(
2064 var AllowIndexed: boolean);
2065 begin
2066 inherited;
2067
2068 if (FogCoord <> nil) or FogVolumetric then
2069 begin
2070 Arrays.AddFogCoord;
2071 Arrays.FogDirectValues := FogCoord <> nil;
2072 end;
2073 end;
2074
2075 procedure TAbstractFogGenerator.GenerateVertex(
2076 IndexNum: Integer);
2077
2078 function GetFogCoord: Single;
2079 begin
2080 { make IndexNum independent of coordIndex, always work like index to coords }
2081 if CoordIndex <> nil then
2082 IndexNum := CoordIndex.Items.L[IndexNum];
2083
2084 { calculate Fog, based on FogCoord and IndexNum }
2085 if IndexNum < FogCoord.Count then
2086 Result := FogCoord.L[IndexNum]
2087 else
2088 if FogCoord.Count <> 0 then
2089 Result := FogCoord.Last
2090 else
2091 Result := 0; //< some default
2092 end;
2093
2094 function GetFogVolumetric: Single;
2095 var
2096 Position, Projected: TVector3;
2097 begin
2098 { calculate global vertex position }
2099 if CoordIndex <> nil then
2100 Position := Coord.Items.L[CoordIndex.Items.L[IndexNum]]
2101 else
2102 Position := Coord.Items.L[IndexNum];
2103 Position := State.Transformation.Transform.MultPoint(Position);
2104
2105 Projected := PointOnLineClosestToPoint(
2106 TVector3.Zero, FogVolumetricDirection, Position);
2107 Result := Projected.Length;
2108 if not AreParallelVectorsSameDirection(
2109 Projected, FogVolumetricDirection) then
2110 Result := -Result;
2111 { Now I want
2112 - Result = FogVolumetricVisibilityStart -> 0
2113 - Result = FogVolumetricVisibilityStart + X -> X
2114 (so that Result = FogVolumetricVisibilityStart +
2115 FogVisibilityRangeScaled -> FogVisibilityRangeScaled) }
2116 Result := Result - FogVolumetricVisibilityStart;
2117 end;
2118
2119 procedure SetFog(const Fog: Single);
2120 begin
2121 { When Result < 0 our intention is to have no fog (at least
2122 for volumetric fog, for explicit FogCoordinate we don't know what
2123 was user's intention).
2124 So Result < 0 should be equivalent to Result = 0.
2125 However, OpenGL doesn't necessarily interpret it like this.
2126
2127 Since factor given by glFogCoordfEXT is interpreted just like
2128 eye distance (i.e. it's processed by appopriate linear or exp or exp2
2129 equations), negative values may produce quite unexpected results
2130 (unless you really look at the equations).
2131
2132 This is mentioned in the extension specification
2133 [http://oss.sgi.com/projects/ogl-sample/registry/EXT/fog_coord.txt].
2134 First is says:
2135
2136 * Should the specified value be used directly as the fog weighting
2137 factor, or in place of the z input to the fog equations?
2138
2139 As the z input; more flexible and meets ISV requests.
2140
2141 ... which means that what glFogCoordfEXT gives is interpreted
2142 just like eye distance for normal fog (so it's e.g. affected
2143 by fog linear / exp / exp2 modes, affected by fog start and end values,
2144 etc.). Later it says:
2145
2146 * Should the fog coordinate be restricted to non-negative values?
2147
2148 Perhaps. Eye-coordinate distance of fragments will be
2149 non-negative due to clipping. Specifying explicit negative
2150 coordinates may result in very large computed f values, although
2151 they are defined to be clipped after computation.
2152
2153 ... and this is precisely why specifying negative glFogCoordfEXT
2154 parameters is a bad idea: you don't really know what OpenGL
2155 implementation will do. NVidia OpenGL seems to actually assume
2156 that factor < 0 means the same as factor = 0, so my code
2157 worked OK without clamping below
2158 (because NVidia OpenGL was actually doing it anyway).
2159 Mesa 3D (and Radeon, as I suspect, because similar problems
2160 were reported for "The Castle" on Radeon) seem to just use the negative
2161 value directly, which causes strange artifacts
2162 (see e.g. "The Castle" gate_final.wrl VRML file).
2163
2164 The clamping below makes volumetric fog work
2165 OK as expected for all OpenGL implementations.
2166
2167 Note: we don't limit Fog to be <= 1 (although we could
2168 for X3D FogCoordinate). glFogCoord is like a distance from the eye,
2169 so it may be >= 1, and GetFogVolumetric depends on it to work. }
2170 Arrays.FogCoord(ArrayIndexNum)^ := Max(Fog, 0);
2171 end;
2172
2173 begin
2174 inherited;
2175 if FogCoord <> nil then
2176 SetFog(GetFogCoord) else
2177 if FogVolumetric then
2178 SetFog(GetFogVolumetric);
2179 end;
2180
2181 { TAbstractShaderAttribGenerator ------------------------------ }
2182
2183 constructor TAbstractShaderAttribGenerator.Create(AShape: TShape);
2184 var
2185 A: TMFNode;
2186 I: Integer;
2187 begin
2188 inherited;
2189
2190 A := Geometry.AttribField;
2191 if A <> nil then
2192 begin
2193 SetLength(Attribs, A.Count); // in the most common case, when A.Count, this does nothing
2194 for I := 0 to A.Count - 1 do
2195 if A[I] is TAbstractVertexAttributeNode then
2196 Attribs[I].Node := TAbstractVertexAttributeNode(A[I]);
2197 end;
2198 end;
2199
2200 procedure TAbstractShaderAttribGenerator.PrepareAttributes(var AllowIndexed: boolean);
2201 var
2202 I: Integer;
2203 NumComponents: Integer;
2204 begin
2205 inherited;
2206 for I := 0 to High(Attribs) do
2207 begin
2208 // this will be used later to check, with assert, that all clauses below set Attribs[I].GeometryAttrib
2209 {$ifdef DEBUG} Attribs[I].GeometryAttrib := TGeometryAttrib(Pointer(1)); {$endif}
2210
2211 { call Arrays.AddGLSLAttribute* }
2212 if Attribs[I].Node is TFloatVertexAttributeNode then
2213 begin
2214 NumComponents := TFloatVertexAttributeNode(Attribs[I].Node).NumComponents;
2215 case NumComponents of
2216 1: Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeFloat(Attribs[I].Node.NameField, false);
2217 2: Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeVector2(Attribs[I].Node.NameField, false);
2218 3: Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeVector3(Attribs[I].Node.NameField, false);
2219 4: Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeVector4(Attribs[I].Node.NameField, false);
2220 else
2221 begin
2222 Attribs[I].GeometryAttrib := nil;
2223 WritelnWarning('X3D', Format('Invalid FloatVertexAttribute.numComponents: %d (should be between 1..4)',
2224 [NumComponents]));
2225 end;
2226 end;
2227 end else
2228 if Attribs[I].Node is TMatrix3VertexAttributeNode then
2229 begin
2230 Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeMatrix3(Attribs[I].Node.NameField, false);
2231 end else
2232 if Attribs[I].Node is TMatrix4VertexAttributeNode then
2233 begin
2234 Attribs[I].GeometryAttrib := Arrays.AddGLSLAttributeMatrix4(Attribs[I].Node.NameField, false);
2235 end else
2236 begin
2237 Attribs[I].GeometryAttrib := nil;
2238 WritelnWarning('X3D', Format('Not handled vertex attribute class %s',
2239 [Attribs[I].Node.X3DType]));
2240 end;
2241
2242 Assert(Attribs[I].GeometryAttrib <> TGeometryAttrib(Pointer(1))); // all cases above should have set Attribs[I].GeometryAttrib explicitly
2243 end;
2244 end;
2245
2246 procedure TAbstractShaderAttribGenerator.GenerateCoordinateBegin;
2247
2248 procedure SetAttrib(const AttributeName: String;
2249 const TargetAttrib: TGeometryAttrib; const SourcePtr: Pointer; const SourceItemSize, SourceCount: SizeInt);
2250 begin
2251 AssignAttribute(AttributeName,
2252 Pointer(Arrays.GLSLAttribute(TargetAttrib)), SourcePtr, SourceItemSize, SourceCount);
2253 end;
2254
2255 var
2256 I: Integer;
2257 NumComponents: Integer;
2258 AttributeName: String;
2259 begin
2260 inherited;
2261 for I := 0 to High(Attribs) do
2262 begin
2263 AttributeName := TAbstractVertexAttributeNode(Attribs[I].Node).NameField;
2264
2265 { Note we don't do some warnings here, that were already done
2266 in PrepareAttributes (and set Attribs[I].Node = nil). }
2267 if Attribs[I].Node is TFloatVertexAttributeNode then
2268 begin
2269 NumComponents := TFloatVertexAttributeNode(Attribs[I].Node).NumComponents;
2270 { For NumComponents = 1, each TFloatVertexAttributeNode item is one attribute.
2271 For NumComponents = 2,3,4:
2272 Vector attributes in X3D are expressed using TFloatVertexAttributeNode,
2273 with each vector component one after another.
2274 We copy them fast, knowing that memory layout of TSingleList is the same as TVectorXxxList. }
2275 SetAttrib(AttributeName, Attribs[I].GeometryAttrib,
2276 TFloatVertexAttributeNode(Attribs[I].Node).FdValue.Items.L, SizeOf(Single) * NumComponents,
2277 TFloatVertexAttributeNode(Attribs[I].Node).FdValue.Items.Count div NumComponents);
2278 end else
2279 if Attribs[I].Node is TMatrix3VertexAttributeNode then
2280 begin
2281 SetAttrib(AttributeName, Attribs[I].GeometryAttrib,
2282 TMatrix3VertexAttributeNode(Attribs[I].Node).FdValue.Items.L, SizeOf(TMatrix3),
2283 TMatrix3VertexAttributeNode(Attribs[I].Node).FdValue.Items.Count);
2284 end else
2285 if Attribs[I].Node is TMatrix4VertexAttributeNode then
2286 begin
2287 SetAttrib(AttributeName, Attribs[I].GeometryAttrib,
2288 TMatrix4VertexAttributeNode(Attribs[I].Node).FdValue.Items.L, SizeOf(TMatrix4),
2289 TMatrix4VertexAttributeNode(Attribs[I].Node).FdValue.Items.Count);
2290 end;
2291 end;
2292 end;
2293
2294 { TAbstractBumpMappingGenerator ----------------------------------------------- }
2295
2296 procedure TAbstractBumpMappingGenerator.PrepareAttributes(var AllowIndexed: boolean);
2297 begin
2298 inherited;
2299 if ShapeBumpMappingUsed then
2300 Arrays.AddTangent;
2301 end;
2302
2303 procedure TAbstractBumpMappingGenerator.GenerateCoordinateBegin;
2304 begin
2305 inherited;
2306
2307 CalculateTangents := false;
2308 if ShapeBumpMappingUsed then
2309 begin
2310 if (TangentsFromNode <> nil) and
2311 (NorImplementation in [niPerVertexCoordIndexed, niPerVertexNonIndexed]) then
2312 begin
2313 AssignCoordinate('tangents', Arrays.Tangent, TangentsFromNode.L, TangentsFromNode.ItemSize, TangentsFromNode.Count)
2314 end else
2315 begin
2316 { If ShapeBumpMappingUsed, but we cannot use TangentsFromNode, then we need
2317 to calculate tangents per-vertex or per-face here. }
2318 CalculateTangents := true;
2319 { Too verbose? Would also show when we only do this once
2320 (because the geometry is not animated), which is not really a problem. }
2321 // WritelnWarning('Calculating tangent vectors during rendering. This is slow. Export model with "Tangents" selected to make it much faster to render.');
2322 end;
2323 end;
2324 end;
2325
2326 procedure TAbstractBumpMappingGenerator.GenerateVertex(IndexNum: Integer);
2327
2328 procedure SetTangents;
2329 var
2330 Normal: TVector3;
2331 begin
2332 if NormalsFlat then
2333 begin
2334 Arrays.Tangent(ArrayIndexNum)^ := Tangent;
2335 end else
2336 begin
2337 { If NormalsFlat = false,
2338 we want to calculate *local* Tangent,
2339 which is Tangent adjusted to the current vertex
2340 (since every vertex on this face may have a different normal).
2341
2342 Without doing this, you would see strange artifacts, smoothed
2343 faces would look somewhat like flat faces.
2344 Conceptually, for smoothed
2345 faces, whole tangent space should vary for each vertex, so Normal,
2346 and both tangents/bitangents may be different on each vertex. }
2347
2348 GetNormal(IndexNum, CurrentRangeNumber, Normal);
2349 Arrays.Tangent(ArrayIndexNum)^ := MakeVectorOrthogonal(Tangent, Normal);
2350 end;
2351 end;
2352
2353 begin
2354 inherited;
2355 if CalculateTangents then
2356 SetTangents;
2357 end;
2358
2359 procedure TAbstractBumpMappingGenerator.CalculateTangentVectors(
2360 const TriangleIndex1, TriangleIndex2, TriangleIndex3: Integer);
2361 var
2362 TriangleCoord: TTriangle3;
2363 TriangleTexCoord: TTriangle2;
2364 begin
2365 if CalculateTangents then
2366 begin
2367 { calculate TriangleCoord }
2368 TriangleCoord[0] := GetVertex(TriangleIndex1);
2369 TriangleCoord[1] := GetVertex(TriangleIndex2);
2370 TriangleCoord[2] := GetVertex(TriangleIndex3);
2371
2372 if not (
2373 { calculate TriangleTexCoord }
2374 GetTextureCoord(TriangleIndex1, ShapeBumpMappingTextureCoordinatesId, TriangleTexCoord.Data[0]) and
2375 GetTextureCoord(TriangleIndex2, ShapeBumpMappingTextureCoordinatesId, TriangleTexCoord.Data[1]) and
2376 GetTextureCoord(TriangleIndex3, ShapeBumpMappingTextureCoordinatesId, TriangleTexCoord.Data[2]) and
2377 { calculate Tangent }
2378 CalculateTangent(true , Tangent, TriangleCoord, TriangleTexCoord) ) then
2379 begin
2380 { Would be more correct to set Tangent as anything perpendicular to Normal. }
2381 Tangent := TVector3.One[0];
2382 end;
2383
2384 { It *is* possible that we'll get somewhat incorrect tangents in practice,
2385 but it's not really useful to check it (at least in non-debug builds)
2386 because we don't really have here a better fallback.
2387 Using above "TVector3.One[0]" isn't really better. }
2388 {
2389 if not ( (Abs(TVector3.DotProduct(Tangent, Bitangent)) < 0.95) and
2390 (Abs(TVector3.DotProduct(Tangent, Normal)) < 0.95) and
2391 (Abs(TVector3.DotProduct(Bitangent, Normal)) < 0.95) ) then
2392 WritelnWarning('Tangents are likely incorrect');
2393 }
2394 end;
2395 end;
2396
2397 { non-abstract generators ---------------------------------------------------- }
2398
2399 {$I castleinternalarraysgenerator_rendering.inc}
2400 {$I castleinternalarraysgenerator_geometry3d.inc}
2401
2402 { global routines ------------------------------------------------------------ }
2403
2404 function GetArraysGenerator(AGeometry: TAbstractGeometryNode): TArraysGeneratorClass;
2405 begin
2406 if AGeometry is TIndexedTriangleMeshNode_1 then
2407 Result := TTriangleStripSetGenerator else
2408 if AGeometry is TIndexedFaceSetNode_1 then
2409 Result := TIndexedFaceSet_1Generator else
2410 if AGeometry is TIndexedFaceSetNode then
2411 Result := TIndexedFaceSetGenerator else
2412 if AGeometry is TIndexedLineSetNode_1 then
2413 Result := TIndexedLineSet_1Generator else
2414 if (AGeometry is TIndexedLineSetNode) or
2415 (AGeometry is TLineSetNode) then
2416 Result := TLineSetGenerator else
2417 if AGeometry is TPointSetNode_1 then
2418 Result := TPointSet_1Generator else
2419 if AGeometry is TPointSetNode then
2420 Result := TPointSetGenerator else
2421 if (AGeometry is TTriangleSetNode) or
2422 (AGeometry is TIndexedTriangleSetNode) or
2423 { That is correct, TQuadSetNode goes to TTriangleSetGenerator,
2424 as TQuadSetNode.InternalTrianglesCoordIndex allows to treat it pretty much
2425 like TIndexedTriangleSetNode. }
2426 (AGeometry is TQuadSetNode) then
2427 Result := TTriangleSetGenerator else
2428 if (AGeometry is TTriangleFanSetNode) or
2429 (AGeometry is TIndexedTriangleFanSetNode) then
2430 Result := TTriangleFanSetGenerator else
2431 if (AGeometry is TTriangleStripSetNode) or
2432 (AGeometry is TIndexedTriangleStripSetNode) then
2433 Result := TTriangleStripSetGenerator else
2434 if (AGeometry is TIndexedQuadSetNode) then
2435 Result := TQuadSetGenerator else
2436 Result := nil;
2437 end;
2438
2439 end.