Debian Codegraph @

src/scene/load/x3dloadinternal3ds.pas

raw
1 {
2 Copyright 2002-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { 3DS loader. }
17
18 unit X3DLoadInternal3DS;
19
20 {$I castleconf.inc}
21
22 interface
23
24 implementation
25
26 uses SysUtils, Classes, Generics.Collections, Math,
27 X3DNodes, X3DLoad, CastleUtils, CastleClassUtils, CastleVectors, X3DCameraUtils,
28 X3DLoadInternalUtils, CastleLog, CastleDownload, CastleUriUtils,
29 CastleStreamUtils;
30
31 { 3DS reading mostly based on spec from
32 [http://www.martinreddy.net/gfx/3d/3DS.spec].
33
34 TScene3DS corresponds to the whole 3DS file,
35 that is the MAIN chunk, and also (since we don't handle keyframes from 3DS)
36 the OBJMESH chunk.
37
38 It contains lists of triangle meshes, cameras and lights. They are all TObject3DS,
39 and correspond to OBJBLOCK chunk, with inside TRIMESH, CAMERA or LIGHT chunk.
40 As far as I understand, OBJBLOCK in 3DS may contain only *one* of
41 trimesh, light or camera. We assume this.
42 - Trimesh wraps OBJBLOCK chunk with VERTLIST subchunk.
43
44 Moreover TScene3DS has a list of TMaterial3ds, that correspond
45 to the MATERIAL chunk.
46
47 TODO:
48 - properties that are read from 3ds but not used anywhere because their exact
49 interpretation is not known for me:
50 TCamera3ds.Lens
51 TMaterialMap3ds.Offset (I don't know wheteher use it before of after
52 Scale, again I need some test 3ds scenes to check that)
53 TMaterial3ds.TextureMap2
54 TMaterial3ds.ShininessStrenth, TransparencyFalloff, ReflectBlur
55
56 - TFace3ds.Wrap interpretation is known but it is not used (because
57 1. implementing it requires some mess in code
58 since this Wrap is the property of _each face_ (instead of _each texture_,
59 which would be simpler to map to OpenGL and VRML)
60 2. and I don't have enough test 3ds scenes with textures to really
61 see the difference. So, I will probably implement it someday when
62 I'll need it.
63 }
64
65 { Declare classes ------------------------------------------------------------ }
66
67 type
68 EInvalid3dsFile = class(Exception);
69 EMaterialNotInitialized = class(EInvalid3dsFile);
70
71 TMaterialMap3ds = record
72 Exists: boolean;
73 MapUrl: String;
74 Scale, Offset: TVector2;
75 end;
76
77 TMaterial3ds = class
78 strict private
79 FName: string;
80 FInitialized: boolean;
81 public
82 property Name: string read FName;
83
84 { When @false, this material was found in TTrimesh but was not yet
85 defined in 3DS file. }
86 property Initialized: boolean read FInitialized default false;
87 public
88 { Material properties. Have default values (following VRML and OpenGL
89 defaults, as I don't know 3DS defaults) in case they would be
90 undefined in 3DS file. }
91 AmbientColor: TVector4;
92 DiffuseColor: TVector4;
93 SpecularColor: TVector4;
94
95 { Texture maps, initialized with Exists = false }
96 TextureMap1, TextureMap2, TextureMapBump: TMaterialMap3ds;
97
98 { All Singles below are always read from 3ds file (they are required
99 subchunks of material chunk). They are in range 0..1. } { }
100 Shininess: Single;
101 ShininessStrenth, Transparency,
102 TransparencyFalloff, ReflectBlur :Single; {< By default 0 }
103
104 constructor Create(const AName: string);
105
106 { Read CHUNK_MATERIAL, initializing our fields and changing
107 @link(Initialized) to @true. }
108 procedure ReadFromStream(Stream: TStream; EndPos: Int64);
109 end;
110
111 TMaterial3dsList = class({$ifdef FPC}specialize{$endif} TObjectList<TMaterial3ds>)
112 public
113 { Index of material with given name. If material doesn't exist,
114 it will be added. }
115 function MaterialIndex(const MatName: string): Integer;
116 { Raises EMaterialNotInitialized if any not TMaterial3ds.Initialized
117 material present on the list. You should call it at the end of reading
118 3DS file, to make sure all used materials were found in 3DS file. }
119 procedure CheckAllInitialized;
120 procedure ReadMaterial(Stream: TStream; EndPos: Int64);
121 end;
122
123 { }
124 TScene3DS = class;
125
126 { @abstract(Abstract class for 3DS triangle mesh, camera or light source.)
127
128 Use CreateObject3DS method to read contents from stream,
129 creating appropriate non-abstract TObject3DS descendant. }
130 TObject3DS = class
131 strict private
132 FName: string;
133 FScene: TScene3DS;
134 public
135 property Name: string read FName;
136 { Scene containing this object. }
137 property Scene: Tscene3DS read FScene;
138
139 { Constructor reading 3DS chunk of object part,
140 like CHUNK_TRIMESH or CHUNK_CAMERA or CHUNK_LIGHT.
141
142 Assumes that we just read from stream chunk header (with id =
143 one of the above and length indicating that Stream.Position >= ChunkEndPos
144 is after the object part), then we read AName (so now we can read subchunks).
145
146 You don't have to finish reading at ChunkEndPos, we'll rewind
147 the stream position afterwards if necessary. }
148 constructor Create(const AName: string; AScene: TScene3DS;
149 Stream: TStream; const ChunkEndPos: Int64); virtual;
150 end;
151
152 TFace3ds = record
153 VertsIndices: TVector3Cardinal;
154 EdgeFlags: packed array[0..2]of boolean;
155 Wrap: packed array[0..1]of boolean;
156 { Index to the Scene.Materials.
157 -1 means "not specified in 3DS file" and means that face
158 uses default material. There are some 3DS that have faces without
159 material defined --- for example therack.3ds. }
160 FaceMaterialIndex: Integer;
161 end;
162 TFace3dsArray = packed array [0 .. MaxInt div SizeOf(TFace3ds) - 1] of TFace3ds;
163 PFace3dsArray = ^TFace3dsArray;
164
165 { Vertex information from 3DS. }
166 TVertex3ds = packed record
167 Pos: TVector3;
168 { Texture coordinates. (0, 0) if the object doesn't have texture coords
169 (HasTexCoords is @false). }
170 TexCoord: TVector2;
171 end;
172 TVertex3dsArray = packed array [0 .. MaxInt div SizeOf(TVertex3ds) - 1] of TVertex3ds;
173 PVertex3dsArray = ^TVertex3dsArray;
174
175 { Triangle mesh. }
176 TTrimesh3ds = class(TObject3DS)
177 strict private
178 FVertsCount, FFacesCount: Word;
179 FHasTexCoords: boolean;
180 public
181 { Vertexes and faces. Read-only from outside of this class.
182 @groupBegin }
183 Verts: PVertex3dsArray;
184 Faces: PFace3dsArray;
185 { @groupEnd }
186 { Do the vertexes have meaningful texture coordinates? }
187 property HasTexCoords: boolean read FHasTexCoords;
188 { Number of vertexes and faces.
189 Remember that VertsCount = FacesCount = 0 is possible, e.g. 0155.3ds.
190 @groupBegin }
191 property VertsCount: Word read FVertsCount;
192 property FacesCount: Word read FFacesCount;
193 { @groupEnd }
194
195 constructor Create(const AName: string; AScene: TScene3DS;
196 Stream: TStream; const ChunkEndPos: Int64); override;
197 destructor Destroy; override;
198 end;
199
200 TCamera3ds = class(TObject3DS)
201 strict private
202 FPosition, FTarget: TVector3;
203 FBank, FLens: Single;
204 public
205 property Position: TVector3 read FPosition;
206 property Target: TVector3 read FTarget;
207 property Bank: Single read FBank;
208 property Lens: Single read FLens;
209 constructor Create(const AName: string; AScene: TScene3DS;
210 Stream: TStream; const ChunkEndPos: Int64); override;
211
212 { Camera direction. Calculated from Position and Target. }
213 function Direction: TVector3;
214 { Camera up. Calculated from Direction and Bank. }
215 function Up: TVector3;
216 end;
217
218 TLight3ds = class(TObject3DS)
219 public
220 Pos: TVector3;
221 Col: TVector3;
222 Enabled: boolean;
223 constructor Create(const AName: string; AScene: TScene3DS;
224 Stream: TStream; const ChunkEndPos: Int64); override;
225 end;
226
227 TTrimesh3dsList = {$ifdef FPC}specialize{$endif} TObjectList<TTrimesh3ds>;
228 TCamera3dsList = {$ifdef FPC}specialize{$endif} TObjectList<TCamera3ds>;
229 TLight3dsList = {$ifdef FPC}specialize{$endif} TObjectList<TLight3ds>;
230
231 { 3DS loader. }
232 TScene3DS = class
233 public
234 { Triangle meshes, cameras and other properties of the scene.
235 They are created and destroyed by TScene3DS
236 object --- so these fields are read-only from outside of this class.
237 @groupBegin }
238 Trimeshes: TTrimesh3dsList;
239 Cameras: TCamera3dsList;
240 Lights: TLight3dsList;
241 Materials: TMaterial3dsList;
242 { @groupEnd }
243 { Autodesk version used to create this 3DS. }
244 Version: UInt32;
245 constructor Create(const Stream: TStream);
246 destructor Destroy; override;
247 end;
248
249 { Chunks utilities ----------------------------------------------------------- }
250
251 { The indentation below corresponds to chunk relations in 3DS file.
252 Based on example 3dsRdr.c, with new needed chunks added, based
253 on various Internal sources about 3DS and MLI, with some new comments.
254
255 Some subchunks that are required within parent chunks are marked as such. }
256 const
257 { Color chunks may be in various places in 3DS file.
258 _GAMMA suffix means that these colors are already gamma corrected.
259 @groupBegin }
260 CHUNK_RGBF = $0010;
261 CHUNK_RGBB = $0011;
262 CHUNK_RGBB_GAMMA = $0012;
263 CHUNK_RGBF_GAMMA = $0013;
264 { @groupEnd }
265
266 { CHUNK_DOUBLE_BYTE from MLI specification. Experiments show
267 that this has 0..100 range, at least when used for shininess subchunks
268 (in other uses, like transparency, the range @italic(may) be smaller).
269
270 lib3ds confirms this, by even calling this as INT_PERCENTAGE instead
271 of DOUBLE_BYTE. Used for CHUNK_SHININESS, CHUNK_SHININESS_STRENTH,
272 CHUNK_TRANSPARENCY, CHUNK_TRANSPARENCY_FALLOFF, CHUNK_REFLECT_BLUR. }
273 CHUNK_DOUBLE_BYTE = $0030;
274
275 { Root file chunks.
276 MAIN chunk is the whole 3DS file.
277 MLI chunk is the whole MLI (Material-Library) file.
278 Probably PRJ chunk is also something like that (some "project" ?).
279 @groupBegin }
280 CHUNK_PRJ = $C23D;
281 CHUNK_MLI = $3DAA;
282 CHUNK_MAIN = $4D4D;
283 { @groupEnd }
284
285 CHUNK_VERSION = $0002;
286 CHUNK_OBJMESH = $3D3D;
287 CHUNK_BKGCOLOR = $1200;
288 CHUNK_AMBCOLOR = $2100;
289 { As I understand, exactly one of the subchunks TRIMESH, LIGHT
290 and CAMERA appears in one OBJBLOCK chunk. } { }
291 CHUNK_OBJBLOCK = $4000;
292 CHUNK_TRIMESH = $4100;
293 CHUNK_VERTLIST = $4110;
294 CHUNK_FACELIST = $4120;
295 CHUNK_FACEMAT = $4130;
296 CHUNK_MAPLIST = $4140; {< texture coordinates }
297 CHUNK_SMOOLIST = $4150;
298 CHUNK_TRMATRIX = $4160;
299 CHUNK_LIGHT = $4600;
300 CHUNK_SPOTLIGHT = $4610;
301 CHUNK_CAMERA = $4700;
302 CHUNK_HIERARCHY = $4F00;
303 CHUNK_VIEWPORT = $7001;
304
305 CHUNK_MATERIAL = $AFFF;
306 CHUNK_MATNAME = $A000; {< required; asciiz, no subchunks }
307 CHUNK_AMBIENT = $A010; {< required; subchunks are RGB chunk[s] }
308 CHUNK_DIFFUSE = $A020; {< required; subchunks are RGB chunk[s] }
309 CHUNK_SPECULAR = $A030; {< required; subchunks are RGB chunk[s] }
310 CHUNK_SHININESS = $A040; {< required; subchunks are DOUBLE_BYTE chunk[s] }
311 CHUNK_SHININESS_STRENTH = $A041; {< required; subchunks are DOUBLE_BYTE chunk[s] }
312 CHUNK_TRANSPARENCY = $A050; {< required; subchunks are DOUBLE_BYTE chunk[s] }
313 CHUNK_TRANSPARENCY_FALLOFF = $A052; {< required; subchunks are DOUBLE_BYTE chunk[s] }
314 CHUNK_REFLECT_BLUR = $A053; {< required; subchunks are DOUBLE_BYTE chunk[s] }
315
316 CHUNK_TEXMAP_1 = $A200; {< two texture maps }
317 CHUNK_TEXMAP_2 = $A33A;
318 CHUNK_BUMPMAP = $A230;
319 { All MAP chunks below can be subchunks of all MAP chunks above. } { }
320 CHUNK_MAP_FILE = $A300; {< asciiz, no subchunks }
321 CHUNK_MAP_USCALE = $A356; {< single, no subchunks }
322 CHUNK_MAP_VSCALE = $A354; {< single, no subchunks }
323 CHUNK_MAP_UOFFSET = $A358; {< single, no subchunks }
324 CHUNK_MAP_VOFFSET = $A35A; {< single, no subchunks }
325
326 CHUNK_KEYFRAMER = $B000;
327 CHUNK_AMBIENTKEY = $B001;
328 CHUNK_TRACKINFO = $B002;
329 CHUNK_TRACKOBJNAME = $B010;
330 CHUNK_TRACKPIVOT = $B013;
331 CHUNK_TRACKPOS = $B020;
332 CHUNK_TRACKROTATE = $B021;
333 CHUNK_TRACKSCALE = $B022;
334 CHUNK_OBJNUMBER = $B030;
335 CHUNK_TRACKCAMERA = $B003;
336 CHUNK_TRACKFOV = $B023;
337 CHUNK_TRACKROLL = $B024;
338 CHUNK_TRACKCAMTGT = $B004;
339 CHUNK_TRACKLIGHT = $B005;
340 CHUNK_TRACKLIGTGT = $B006;
341 CHUNK_TRACKSPOTL = $B007;
342 CHUNK_FRAMES = $B008;
343
344 type
345 TChunkHeader = packed record
346 Id: Word;
347 Len: UInt32;
348 procedure ReadFromStream(const Stream: TStream);
349 end;
350
351 procedure TChunkHeader.ReadFromStream(const Stream: TStream);
352 begin
353 Stream.ReadBuffer(Id, SizeOf(Id));
354 Stream.ReadBuffer(Len, SizeOf(Len));
355 Id := LEtoN(Id);
356 Len := LEtoN(Len);
357 end;
358
359 { TODO: Using this (with "inline" or not) causes various Internal Errors
360 with FPC 3.1.1:
361
362 x3dloadinternal3ds.pas(<end line>,4) Fatal: Internal error 2011031501
363
364 or
365
366 x3dnodes.pas(99,1) Fatal: Internal error 200611031
367
368 or sometimes access violation. It is reproducible by
369
370 make clean
371 fpc fpmake.pp
372 ./fpmake build --nofpccfg --verbose --globalunitdir="$FPCDIR"
373
374 in CGE. It also occurs (but completely randomly, I failed to reproduce
375 it reliably so far) with FPC 2.6.4 and 3.0.0.
376
377 So far, I failed to express this bug in a simple testcase for FPC bugreport. }
378
379 (*
380 T3dsStreamHelper = class helper(TStreamHelper) for TStream
381 procedure ReadChunkHeader(out Buffer: TChunkHeader); inline;
382 end;
383
384 procedure T3dsStreamHelper.ReadChunkHeader(out Buffer: TChunkHeader); inline;
385 begin
386 ReadBuffer(Buffer, SizeOf(Buffer));
387 Buffer.id := LEtoN(Buffer.id);
388 Buffer.len := LEtoN(Buffer.len);
389 end;
390 *)
391
392 procedure Check3dsFile(TrueValue: boolean; const ErrMessg: string);
393 begin
394 if not TrueValue then raise EInvalid3dsFile.Create(ErrMessg);
395 end;
396
397 { Read 3DS subchunks until EndPos, ignoring everything except color information.
398 It's guaranteed that Stream.Position is EndPos at the end.
399
400 Returns did we find any color information. If @false,
401 Col is left not modified (it's intentionally a "var" parameter,
402 not an "out" parameter).
403
404 Overloaded version with 4 components always returns alpha = 1. }
405 function TryReadColorInSubchunks(var Col: TVector3;
406 Stream: TStream; EndPos: Int64): boolean; overload;
407 var
408 h: TChunkHeader;
409 hEnd: Int64;
410 Col3Byte: TVector3Byte;
411 {$ifdef ENDIAN_BIG}
412 b: Byte;
413 {$endif ENDIAN_BIG}
414 begin
415 result := false;
416 while Stream.Position < EndPos do
417 begin
418 h.ReadFromStream(Stream);
419 hEnd := Stream.Position -SizeOf(TChunkHeader) + h.len;
420 { TODO: we ignore gamma correction entirely so we don't distinct
421 gamma corrected and not corrected colors }
422 case h.id of
423 CHUNK_RGBF, CHUNK_RGBF_GAMMA:
424 begin
425 Stream.ReadLE(Col);
426 result := true;
427 break;
428 end;
429 CHUNK_RGBB, CHUNK_RGBB_GAMMA:
430 begin
431 Stream.ReadBuffer(Col3Byte, SizeOf(Col3Byte));
432 Col := Vector3(Col3Byte);
433 result := true;
434 break;
435 end;
436 else Stream.Position := hEnd;
437 end;
438 end;
439 Stream.Position := EndPos;
440 end;
441
442 function TryReadColorInSubchunks(var Col: TVector4;
443 Stream: TStream; EndPos: Int64): boolean; overload;
444 var
445 Col3Single: TVector3;
446 begin
447 result := TryReadColorInSubchunks(Col3Single, Stream, EndPos);
448 if result then Col := Vector4(Col3Single, 1);
449 end;
450
451 { Read 3DS subchunks until EndPos, ignoring everything except CHUNK_DOUBLE_BYTE
452 value. Returns the value / 100.
453 Similar comments as for TryReadColorInSubchunks. }
454 function TryReadPercentageInSubchunks(var Value: Single;
455 Stream: TStream; EndPos: Int64): boolean;
456 var
457 h: TChunkHeader;
458 hEnd: Int64;
459 DoubleByte: Word;
460 begin
461 result := false;
462 while Stream.Position < EndPos do
463 begin
464 h.ReadFromStream(Stream);
465 hEnd := Stream.Position -SizeOf(TChunkHeader) + h.len;
466 if h.id = CHUNK_DOUBLE_BYTE then
467 begin
468 Stream.ReadLE(DoubleByte);
469 result := true;
470 break;
471 end else
472 Stream.Position := hEnd;
473 end;
474 Stream.Position := EndPos;
475 if result then Value := Min(DoubleByte / 100, 1.0);
476 end;
477
478 { 3DS materials -------------------------------------------------------------- }
479
480 const
481 { TODO: I don't know default 3DS material parameters.
482 Below I just use some default OpenGL and VRML 1.0 values. } { }
483 Default3dsMatAmbient: TVector4 = (X: 0.2; Y: 0.2; Z: 0.2; W: 1.0);
484 Default3dsMatDiffuse: TVector4 = (X: 0.8; Y: 0.8; Z: 0.8; W: 1.0);
485 Default3dsMatSpecular: TVector4 = (X: 0; Y: 0; Z: 0; W: 1.0);
486 Default3dsMatShininess: Single = 0.2; {< in range 0..1 }
487
488 constructor TMaterial3ds.Create(const AName: string);
489 begin
490 inherited Create;
491 FName := AName;
492 FInitialized := false;
493 AmbientColor := Default3dsMatAmbient;
494 DiffuseColor := Default3dsMatDiffuse;
495 SpecularColor := Default3dsMatSpecular;
496 Shininess := Default3dsMatShininess;
497 TextureMap1.Exists := false;
498 TextureMap2.Exists := false;
499 TextureMapBump.Exists := false;
500 end;
501
502 procedure TMaterial3ds.ReadFromStream(Stream: TStream; EndPos: Int64);
503
504 function ReadMaterialMap(EndPos: Int64): TMaterialMap3ds;
505 const
506 InitialExistingMatMap: TMaterialMap3ds =
507 (Exists: true; MapUrl: ''; Scale: (X: 1; Y: 1); Offset: (X: 0; Y: 0));
508 var
509 h: TChunkHeader;
510 hEnd: Int64;
511 begin
512 result := InitialExistingMatMap;
513
514 { read MAP subchunks }
515 while Stream.Position < EndPos do
516 begin
517 h.ReadFromStream(Stream);
518 hEnd := Stream.Position -SizeOf(TChunkHeader) +h.len;
519 case h.id of
520 CHUNK_MAP_FILE: Result.MapUrl := StreamReadZeroEndString(Stream);
521 CHUNK_MAP_USCALE: Stream.ReadLE(Result.Scale.X);
522 CHUNK_MAP_VSCALE: Stream.ReadLE(Result.Scale.Y);
523 CHUNK_MAP_UOFFSET: Stream.ReadLE(Result.Offset.X);
524 CHUNK_MAP_VOFFSET: Stream.ReadLE(Result.Offset.Y);
525 else Stream.Position := hEnd;
526 end;
527 end;
528 end;
529
530 var
531 h: TChunkHeader;
532 hEnd: Int64;
533 begin
534 { read material subchunks }
535 while Stream.Position < EndPos do
536 begin
537 h.ReadFromStream(Stream);
538 hEnd := Stream.Position -SizeOf(TChunkHeader) +h.len;
539 case h.id of
540 { Colors }
541 CHUNK_AMBIENT: TryReadColorInSubchunks(AmbientColor, Stream, hEnd);
542 CHUNK_DIFFUSE: TryReadColorInSubchunks(DiffuseColor, Stream, hEnd);
543 CHUNK_SPECULAR: TryReadColorInSubchunks(SpecularColor, Stream, hEnd);
544
545 { Percentage values }
546 CHUNK_SHININESS:
547 TryReadPercentageInSubchunks(Shininess, Stream, hEnd);
548 CHUNK_SHININESS_STRENTH:
549 TryReadPercentageInSubchunks(ShininessStrenth, Stream, hEnd);
550 CHUNK_TRANSPARENCY:
551 TryReadPercentageInSubchunks(Transparency, Stream, hEnd);
552 CHUNK_TRANSPARENCY_FALLOFF:
553 TryReadPercentageInSubchunks(TransparencyFalloff, Stream, hEnd);
554 CHUNK_REFLECT_BLUR:
555 TryReadPercentageInSubchunks(ReflectBlur, Stream, hEnd);
556
557 CHUNK_TEXMAP_1: TextureMap1 := ReadMaterialMap(hEnd);
558 CHUNK_TEXMAP_2: TextureMap2 := ReadMaterialMap(hEnd);
559 CHUNK_BUMPMAP : TextureMapBump := ReadMaterialMap(hEnd);
560 else Stream.Position := hEnd;
561 end;
562 end;
563
564 FInitialized := true;
565 end;
566
567 { TMaterial3dsList ----------------------------------------------------- }
568
569 function TMaterial3dsList.MaterialIndex(const MatName: string): Integer;
570 begin
571 for result := 0 to Count-1 do
572 if Items[result].Name = MatName then exit;
573 {material not found ?}
574 Add(TMaterial3ds.Create(MatName));
575 result := Count-1;
576 end;
577
578 procedure TMaterial3dsList.CheckAllInitialized;
579 var
580 i: integer;
581 begin
582 for i := 0 to Count-1 do
583 if not Items[i].Initialized then
584 raise EMaterialNotInitialized.Create(
585 'Material "'+Items[i].Name+'" used but does not exist');
586 end;
587
588 procedure TMaterial3dsList.ReadMaterial(Stream: TStream; EndPos: Int64);
589 var
590 ind: Integer;
591 MatName: string;
592 StreamStartPos: Int64;
593 h: TChunkHeader;
594 begin
595 { every material must have chunk MATNAME, otherwise it's useless
596 (visible objects may use the material only by name).
597 As far as I know, only one MATNAME is allowed (only one name for one material).
598 Look for MATNAME chunk now. }
599 StreamStartPos := Stream.Position;
600 MatName := '';
601
602 while Stream.Position < EndPos do
603 begin
604 h.ReadFromStream(Stream);
605 if h.id = CHUNK_MATNAME then
606 begin
607 MatName := StreamReadZeroEndString(Stream);
608 break;
609 end else
610 Stream.Position := Stream.Position -SizeOf(TChunkHeader) +h.len;
611 end;
612
613 Stream.Position := StreamStartPos; { restore original position in Stream }
614 if MatName = '' then raise EInvalid3dsFile.Create('Unnamed material');
615
616 { found MatName. Add it to Items, unless it's already there.
617 In the latter case, mark it initialized (if not already), or raise exception
618 (because it means material properties were specified two times). }
619 ind := MaterialIndex(MatName);
620 with Items[ind] do
621 begin
622 Check3dsFile( not Initialized, 'Duplicate material '+MatName+' specification');
623 { if not Initialized then material was added to the list by MaterialIndex
624 or was used in a trimesh already --- but was not yet defined in 3DS.
625 So initialize it now. }
626 ReadFromStream(Stream, EndPos);
627 end;
628 end;
629
630 { Useful consts -------------------------------------------------------------- }
631
632 const
633 { Bit flags for checking is there an edge flag between I and ((I+1) mod 3) vertex. }
634 FACEFLAG_EDGES: array[0..2]of Word = ($4, $2, $1);
635 { Bit flags for checking texture wrap u,v. }
636 FACEFLAG_WRAP: array[0..1]of Word = ($8, $10);
637
638 { TObject3DS ----------------------------------------------------------------- }
639
640 constructor TObject3DS.Create(const AName: string; AScene: TScene3DS;
641 Stream: TStream; const ChunkEndPos: Int64);
642 { don't ever call directly this constructor - we can get here
643 only by "inherited" call from Descendant's constructor }
644 begin
645 inherited Create;
646 FName := AName;
647 FScene := AScene;
648 end;
649
650 function CreateObject3DS(AScene: TScene3DS; Stream: TStream; const ObjectEndPos: Int64): TObject3DS;
651 var
652 ObjName: string;
653 ChunkEndPos: Int64;
654 h: TChunkHeader;
655 begin
656 ObjName := StreamReadZeroEndString(Stream);
657 Result := nil;
658
659 { searching for chunk TRIMESH / CAMERA / LIGHT }
660 while Stream.Position < ObjectEndPos do
661 begin
662 h.ReadFromStream(Stream);
663 ChunkEndPos := Stream.Position + h.len - SizeOf(TChunkHeader);
664 case h.id of
665 CHUNK_TRIMESH: Result := TTrimesh3ds.Create(ObjName, AScene, Stream, ChunkEndPos);
666 CHUNK_CAMERA: Result := TCamera3ds.Create(ObjName, AScene, Stream, ChunkEndPos);
667 CHUNK_LIGHT: Result := TLight3ds.Create(ObjName, AScene, Stream, ChunkEndPos);
668 end;
669 if Result <> nil then break;
670 Stream.Position := ChunkEndPos;
671 end;
672
673 {if none of the TRIMESH / CAMERA / LIGHT chunks found raise error}
674 Check3dsFile( Result <> nil, 'No object recorded under the name '+ObjName);
675
676 { set stream pos at the end of object }
677 Stream.Position := ObjectEndPos;
678 end;
679
680 { TTrimesh3ds --------------------------------------------------------------- }
681
682 constructor TTrimesh3ds.Create(const AName: string; AScene: TScene3DS;
683 Stream: TStream; const ChunkEndPos: Int64);
684
685 { Read FVertsCount, initialize Verts.
686 Unless Verts is already non-zero, then only check it's correct
687 (as FVertsCount of trimesh may be specified in a couple places,
688 like VERTLIST and MAPLIST chunk). }
689 procedure ReadVertsCount;
690 var
691 VertsCountCheck: Word;
692 begin
693 if VertsCount = 0 then
694 begin
695 Stream.ReadLE(FVertsCount);
696 { Use GetClearMem to have Verts memory safely initialized to 0 }
697 Verts := GetClearMem(SizeOf(TVertex3ds)*VertsCount);
698 end else
699 begin
700 Stream.ReadLE(VertsCountCheck);
701 Check3dsFile( VertsCountCheck = VertsCount,
702 'Different VertexCount info for 3ds object '+Name);
703 end;
704 end;
705
706 procedure ReadVertlist;
707 var
708 i: integer;
709 begin
710 ReadVertsCount;
711 for i := 0 to VertsCount-1 do
712 Stream.ReadLE(Verts^[i].Pos);
713 end;
714
715 procedure ReadMaplist(chunkEnd: Int64);
716 var
717 i: integer;
718 begin
719 FHasTexCoords := true;
720 ReadVertsCount;
721 for i := 0 to VertsCount-1 do
722 Stream.ReadLE(Verts^[i].TexCoord);
723 Stream.Position := chunkEnd; { skip subchunks }
724 end;
725
726 procedure ReadFacelist(chunkEnd: Int64);
727
728 procedure ReadFacemat;
729 var
730 MatName: string;
731 MatFaceCount: Word;
732 FaceNum: Word;
733 i, MatIndex: Integer;
734 begin
735 MatName := StreamReadZeroEndString(Stream);
736 MatIndex := Scene.Materials.MaterialIndex(MatName);
737 Stream.ReadLE(MatFaceCount);
738 for i := 1 to MatFaceCount do
739 begin
740 Stream.ReadLE(FaceNum);
741 Check3dsFile(FaceNum < FacesCount,
742 'Invalid face number for material '+MatName);
743 Check3dsFile(Faces^[FaceNum].FaceMaterialIndex = -1,
744 'Duplicate material specification for face');
745 Faces^[FaceNum].FaceMaterialIndex := MatIndex;
746 end;
747 end;
748
749 var
750 i, j: integer;
751 Flags: Word;
752 Word3: packed array[0..2]of Word;
753 h: TChunkHeader;
754 hEnd: Int64;
755 begin
756 Check3dsFile(FacesCount = 0, 'Duplicate faces specification for 3ds object '+Name);
757 Stream.ReadLE(FFacesCount);
758 Faces := GetMem(SizeOf(TFace3ds)*FacesCount);
759 for i := 0 to FacesCount-1 do
760 with Faces^[i] do
761 begin
762 { init face }
763 Stream.ReadBuffer(Word3, SizeOf(Word3));
764 for j := 0 to 2 do
765 VertsIndices.Data[j] := LEtoN(Word3[j]);
766 Stream.ReadLE(Flags);
767 { decode Flags }
768 for j := 0 to 2 do
769 EdgeFlags[j]:=(FACEFLAG_EDGES[j] and Flags) <> 0;
770 for j := 0 to 1 do
771 Wrap[j]:=(FACEFLAG_WRAP[j] and Flags) <> 0;
772 FaceMaterialIndex := -1;
773 end;
774
775 { read subchunks - look for FACEMAT chunk }
776 while Stream.Position < chunkEnd do
777 begin
778 h.ReadFromStream(Stream);
779 hEnd := Stream.Position + h.len - SizeOf(TChunkHeader);
780 if h.id = CHUNK_FACEMAT then
781 ReadFacemat else
782 Stream.Position := hEnd;
783 end;
784 end;
785
786 (*
787 procedure ReadMatrix(ChunkEnd: Int64);
788 var
789 I: Integer;
790 Matrix: TMatrix4;
791 MatrixTransform: TMatrixTransformNode;
792 begin
793 Matrix := TMatrix4.Identity;
794 for I := 0 to 3 do
795 Stream.ReadLE(Matrix[I]);
796 { The 4th row of our matrix will remain (0,0,0,1). }
797
798 if not MatricesPerfectlyEqual(Matrix, TMatrix4.Identity) then
799 begin
800 FreeIfUnusedAndNil(Group);
801 MatrixTransform := TMatrixTransformNode.Create;
802 MatrixTransform.Matrix := Matrix;
803 Group := MatrixTransform;
804 end;
805
806 if Stream.Position <> ChunkEnd then
807 begin
808 WritelnWarning('3DS', 'CHUNK_TRMATRIX should contain only 4x3 floats');
809 Stream.Position := ChunkEnd;
810 end;
811 end;
812 *)
813
814 var
815 h: TChunkHeader;
816 hEnd: Int64;
817 begin
818 inherited;
819
820 FHasTexCoords := false;
821
822 { read subchunks inside CHUNK_TRIMESH }
823 while Stream.Position < ChunkEndPos do
824 begin
825 h.ReadFromStream(Stream);
826 hend := Stream.Position + h.len - SizeOf(TChunkHeader);
827 case h.id of
828 CHUNK_VERTLIST: ReadVertlist;
829 CHUNK_FACELIST: ReadFacelist(hEnd);
830 CHUNK_MAPLIST: ReadMaplist(hEnd);
831 { The correct behavior to handle CHUNK_TRMATRIX is to ignore it, it seems.
832 Looking at what Blender 3DS importer does: it seems they use matrix
833 to transform object, but they also multiply mesh by the matrix inverse.
834 IOW, matrix stores the transformation, which is useful for 3D modelling,
835 but if you just want to display the model, then just ignore it.
836 CHUNK_TRMATRIX: ReadMatrix(hEnd); }
837 else Stream.Position := hEnd;
838 end;
839 end;
840 end;
841
842 destructor TTrimesh3ds.Destroy;
843 begin
844 FreeMemNiling(Pointer(Verts));
845 FreeMemNiling(Pointer(Faces));
846 inherited;
847 end;
848
849 { TCamera3ds --------------------------------------------------------------- }
850
851 constructor TCamera3ds.Create(const AName: string; AScene: TScene3DS;
852 Stream: TStream; const ChunkEndPos: Int64);
853 begin
854 inherited;
855
856 { read CHUNK_CAMERA }
857 Stream.ReadLE(FPosition);
858 Stream.ReadLE(FTarget);
859 Stream.ReadLE(FBank);
860 Stream.ReadLE(FLens);
861 end;
862
863 function TCamera3ds.Direction: TVector3;
864 begin
865 result := Target - Position;
866 end;
867
868 function TCamera3ds.Up: TVector3;
869 var
870 D: TVector3;
871 const
872 StandardUp: TVector3 = (X: 0; Y: 0; Z: 1);
873 StandardUpAlt: TVector3 = (X: 0; Y: 1; Z: 0);
874 begin
875 D := Direction;
876
877 { TODO: this is just a guesswork. We're just guessing that standard
878 up is StandardUp or StandardUpAlt,
879 we're just guessing that Bank works this way.
880 Results on test models seem sensible, consistent with view3ds. }
881
882 if VectorsParallel(D, StandardUp) then
883 result := StandardUpAlt else
884 result := StandardUp;
885 result := RotatePointAroundAxisRad(DegToRad(Bank), result, D);
886 end;
887
888 { TLights3ds --------------------------------------------------------------- }
889
890 constructor TLight3ds.Create(const AName: string; AScene: TScene3DS;
891 Stream: TStream; const ChunkEndPos: Int64);
892 begin
893 inherited;
894
895 { init defaults }
896 Enabled := true; { TODO: we could read this from 3ds file }
897
898 { read inside CHUNK_LIGHT }
899 Stream.ReadLE(Pos);
900 TryReadColorInSubchunks(Col, Stream, ChunkEndPos);
901 end;
902
903 { TScene3DS ----------------------------------------------------------------- }
904
905 constructor TScene3DS.Create(const Stream: TStream);
906 var
907 hmain, hsubmain, hsubObjMesh: TChunkHeader;
908 hsubmainEnd, hsubObjMeshEnd: Int64;
909 Object3DS: TObject3DS;
910 begin
911 inherited Create;
912
913 Trimeshes := TTrimesh3dsList.Create;
914 Cameras := TCamera3dsList.Create;
915 Lights := TLight3dsList.Create;
916 Materials := TMaterial3dsList.Create;
917
918 hmain.ReadFromStream(Stream);
919 Check3dsFile(hmain.id = CHUNK_MAIN, 'First chunk id <> CHUNK_MAIN');
920
921 while Stream.Position < hmain.len do
922 begin
923 hsubmain.ReadFromStream(Stream);
924 hsubmainEnd := Stream.Position+hsubmain.len-SizeOf(TChunkHeader);
925 case hsubmain.id of
926 CHUNK_OBJMESH:
927 begin
928 { look for chunks OBJBLOCK and MATERIAL }
929 while Stream.Position < hsubmainEnd do
930 begin
931 hsubObjMesh.ReadFromStream(Stream);
932 hsubObjMeshEnd := Stream.Position + hsubObjMesh.len - SizeOf(TChunkHeader);
933 case hsubObjMesh.id of
934 CHUNK_OBJBLOCK:
935 begin
936 Object3DS := CreateObject3DS(Self, Stream, hsubObjMeshEnd);
937 if Object3DS is TTrimesh3ds then
938 Trimeshes.Add(TTrimesh3ds(Object3DS)) else
939 if Object3DS is TCamera3ds then
940 Cameras.Add(TCamera3ds(Object3DS)) else
941 Lights.Add(Object3DS as TLight3ds);
942 end;
943 CHUNK_MATERIAL: Materials.ReadMaterial(Stream, hsubObjMeshEnd);
944 else Stream.Position := hsubObjMeshEnd;
945 end;
946 end;
947 end;
948 CHUNK_VERSION: Stream.ReadLE(Version);
949 else Stream.Position := hsubmainEnd;
950 end;
951 end;
952
953 Materials.CheckAllInitialized;
954 end;
955
956 destructor TScene3DS.Destroy;
957 begin
958 FreeAndNil(Trimeshes);
959 FreeAndNil(Cameras);
960 FreeAndNil(Lights);
961 FreeAndNil(Materials);
962 inherited;
963 end;
964
965 { Load3DS -------------------------------------------------------------------- }
966
967 function Load3DS(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
968 var
969 O3ds: TScene3DS;
970
971 { Prefix names with things like "Material_", to make sure these
972 names not collide with each other. (I don't know if they are in
973 separate namespace in 3DS, but better be safe.)
974
975 Note that we don't check here whether all names are really unique,
976 as they don't have to be unique for VRML/X3D. We just make reasonable
977 effort to keep them unique (to help storing them with DEF/USE),
978 if they were unique in 3DS. }
979
980 function MaterialVRMLName(const Mat3dsName: string): string;
981 begin Result := 'Material_' + Mat3dsName end;
982
983 function TrimeshVRMLName(const Tri3dsName: string): string;
984 begin Result := 'Trimesh_' + Tri3dsName end;
985
986 function ViewpointVRMLName(const Camera3dsName: string): string;
987 begin Result := 'Camera_' + Camera3dsName end;
988
989 function LightVRMLName(const Light3dsName: string): string;
990 begin Result := 'Light_' + Light3dsName end;
991
992 procedure AddViewpoints;
993 var
994 Viewpoint: TAbstractChildNode;
995 I: Integer;
996 begin
997 for I := 0 to O3ds.Cameras.Count - 1 do
998 begin
999 {$warnings off} // TODO: fix using deprecated MakeCameraNode
1000 // TODO: what is 3DS convention for up? +Y or Z? Using GravityUp = Up below is uncomfortable.
1001
1002 Viewpoint := MakeCameraNode(cvVrml2_X3d, BaseUrl,
1003 O3ds.Cameras[I].Position,
1004 O3ds.Cameras[I].Direction,
1005 O3ds.Cameras[I].Up,
1006 O3ds.Cameras[I].Up { GravityUp equals Up });
1007
1008 {$warnings on}
1009
1010 Viewpoint.X3DName := ViewpointVRMLName(O3ds.Cameras[I].Name);
1011 Result.AddChildren(Viewpoint);
1012
1013 { TODO: use other 3ds camera fields }
1014 end;
1015 end;
1016
1017 procedure AddLights;
1018 var
1019 I: Integer;
1020 Light: TPointLightNode;
1021 begin
1022 for I := 0 to O3ds.Lights.Count - 1 do
1023 begin
1024 Light := TPointLightNode.Create(LightVRMLName(
1025 O3ds.Lights[I].Name), BaseUrl);
1026 Result.AddChildren(Light);
1027
1028 Light.IsOn := O3ds.Lights[I].Enabled;
1029 Light.Location := O3ds.Lights[I].Pos;
1030 Light.Color := O3ds.Lights[I].Col;
1031 end;
1032 end;
1033
1034 function MaterialToVRML(Material: TMaterial3ds): TAppearanceNode;
1035 var
1036 Mat: TMaterialNode;
1037 Tex: TImageTextureNode;
1038 TexTransform: TTextureTransformNode;
1039 begin
1040 Result := TAppearanceNode.Create(MaterialVRMLName(Material.Name), BaseUrl);
1041
1042 Mat := TMaterialNode.Create('', BaseUrl);
1043 Mat.DiffuseColor := Material.DiffuseColor.XYZ;
1044 Mat.AmbientIntensity := AmbientIntensity(Material.AmbientColor, Material.DiffuseColor);
1045 Mat.SpecularColor := Material.SpecularColor.XYZ;
1046 Mat.Shininess := Material.Shininess;
1047 Mat.Transparency := Material.Transparency;
1048 Result.Material := Mat;
1049
1050 if Material.TextureMap1.Exists then
1051 begin
1052 Tex := TImageTextureNode.Create('', BaseUrl);
1053 Tex.SetUrl([SearchTextureFile(BaseUrl, Material.TextureMap1.MapUrl)]);
1054 Result.Texture := Tex;
1055
1056 TexTransform := TTextureTransformNode.Create('', BaseUrl);
1057 TexTransform.Scale := Material.TextureMap1.Scale;
1058 Result.TextureTransform := TexTransform;
1059
1060 if Material.TextureMapBump.Exists then
1061 begin
1062 Tex := TImageTextureNode.Create('', BaseUrl);
1063 Tex.SetUrl([SearchTextureFile(BaseUrl, Material.TextureMapBump.MapUrl)]);
1064 Result.NormalMap := Tex;
1065
1066 { We don't have separate TextureTransform for bump map.
1067 Just check that in 3DS bump map and diffuse textures have equal transform. }
1068 if not TVector2.Equals(
1069 Material.TextureMap1.Scale,
1070 Material.TextureMapBump.Scale) then
1071 WritelnWarning('VRML/X3D', 'Texture scale for diffuse and normal (bump) maps is different in the 3DS file. Currently this is not correctly handled when converting to X3D');
1072 end;
1073 end;
1074 end;
1075
1076 { How many faces have the same material index.
1077 Starts, and compares, with the face numnbered StartFace (must be < FacesCount). }
1078 function SameMaterialFacesCount(Faces: PFace3dsArray; FacesCount: integer;
1079 StartFace: integer): integer;
1080 var
1081 I: Integer;
1082 begin
1083 I := StartFace + 1;
1084 while (I < FacesCount) and
1085 (Faces^[I].FaceMaterialIndex = Faces^[StartFace].FaceMaterialIndex) do
1086 Inc(i);
1087 Result := I - StartFace;
1088 end;
1089
1090 var
1091 Trimesh3ds: TTrimesh3ds;
1092 Appearances: TX3DNodeList;
1093 Coord: TCoordinateNode;
1094 IFS: TIndexedFaceSetNode;
1095 TexCoord: TTextureCoordinateNode;
1096 Shape: TShapeNode;
1097 I, J, FaceMaterialNum, ThisMaterialFacesCount, FaceNum: Integer;
1098 begin
1099 Appearances := nil;
1100 O3ds := TScene3DS.Create(Stream);
1101 try
1102 Result := TX3DRootNode.Create('', BaseUrl);
1103 try
1104 Result.HasForceVersion := true;
1105 Result.ForceVersion := X3DVersion;
1106
1107 AddViewpoints;
1108 AddLights;
1109
1110 { Convert every 3DS material into VRML/X3D Appearance node }
1111 Appearances := TX3DNodeList.Create(false);
1112 Appearances.Count := O3ds.Materials.Count;
1113 for i := 0 to O3ds.Materials.Count - 1 do
1114 Appearances[I] := MaterialToVRML(O3ds.Materials[i]);
1115
1116 { Add 3DS triangle meshes. Each trimesh is split into a number of
1117 VRML/X3D IndexedFaceSet nodes, sharing common Coordinate node,
1118 but having different materials. }
1119 for i := 0 to O3ds.Trimeshes.Count-1 do
1120 begin
1121 Trimesh3ds := O3ds.Trimeshes[I];
1122
1123 { Create Coordinate node }
1124 Coord := TCoordinateNode.Create('Coord_' + TrimeshVRMLName(Trimesh3ds.Name), BaseUrl);
1125 Coord.FdPoint.Count := Trimesh3ds.VertsCount;
1126 for J := 0 to Trimesh3ds.VertsCount-1 do
1127 Coord.FdPoint.Items.L[J] := Trimesh3ds.Verts^[J].Pos;
1128
1129 { Create TextureCoordinate node, or nil if not available }
1130 if Trimesh3ds.HasTexCoords then
1131 begin
1132 TexCoord := TTextureCoordinateNode.Create('TexCoord_' + TrimeshVRMLName(Trimesh3ds.Name), BaseUrl);
1133 TexCoord.FdPoint.Count := Trimesh3ds.VertsCount;
1134 for j := 0 to Trimesh3ds.VertsCount - 1 do
1135 TexCoord.FdPoint.Items.L[J] := Trimesh3ds.Verts^[J].TexCoord;
1136 end else
1137 TexCoord := nil;
1138
1139 { Convert faces with equal material to IndexedFaceSet }
1140 J := 0;
1141 while J < Trimesh3ds.FacesCount do
1142 begin
1143 IFS := TIndexedFaceSetNode.Create('', BaseUrl);
1144 IFS.TexCoord := TexCoord;
1145 IFS.Coord := Coord;
1146 { We don't support 3DS smoothing groups.
1147 So instead assign some sensible non-zero crease angle. }
1148 IFS.CreaseAngle := NiceCreaseAngle;
1149 IFS.Solid := false;
1150
1151 Shape := TShapeNode.Create('', BaseUrl);
1152 Shape.Geometry := IFS;
1153
1154 FaceMaterialNum := Trimesh3ds.Faces^[j].FaceMaterialIndex;
1155 if FaceMaterialNum <> -1 then
1156 Shape.Appearance := TAppearanceNode(Appearances[FaceMaterialNum]);
1157
1158 Result.AddChildren(Shape);
1159
1160 ThisMaterialFacesCount := SameMaterialFacesCount(Trimesh3ds.Faces,
1161 Trimesh3ds.FacesCount, J);
1162
1163 IFS.FdCoordIndex.Count := ThisMaterialFacesCount * 4;
1164 for FaceNum := 0 to ThisMaterialFacesCount - 1 do
1165 begin
1166 with IFS.FdCoordIndex.Items do
1167 begin
1168 L[FaceNum * 4 ] := Trimesh3ds.Faces^[J].VertsIndices[0];
1169 L[FaceNum * 4 + 1] := Trimesh3ds.Faces^[J].VertsIndices[1];
1170 L[FaceNum * 4 + 2] := Trimesh3ds.Faces^[J].VertsIndices[2];
1171 L[FaceNum * 4 + 3] := -1;
1172 end;
1173 Inc(J);
1174 end;
1175
1176 { If Trimesh3ds.HasTexCoords then IFS.texCoordIndex should be taken
1177 from IFS.coordIndex. And VRML 2.0/X3D do this by default, so no need
1178 to do anything. }
1179 end;
1180
1181 Coord.FreeIfUnused;
1182 Coord := nil;
1183 if TexCoord <> nil then
1184 begin
1185 TexCoord.FreeIfUnused;
1186 TexCoord := nil;
1187 end;
1188 end;
1189
1190 for I := 0 to Appearances.Count - 1 do
1191 Appearances[I].FreeIfUnused;
1192 except FreeAndNil(result); raise end;
1193 finally
1194 FreeAndNil(O3ds);
1195 FreeAndNil(Appearances)
1196 end;
1197 end;
1198
1199 var
1200 ModelFormat: TModelFormat;
1201 initialization
1202 ModelFormat := TModelFormat.Create;
1203 ModelFormat.OnLoad := {$ifdef FPC}@{$endif} Load3DS;
1204 ModelFormat.OnLoadForceMemoryStream := true;
1205 ModelFormat.MimeTypes.Add('image/x-3ds');
1206 ModelFormat.FileFilterName := '3D Studio (*.3ds)';
1207 ModelFormat.Extensions.Add('.3ds');
1208 RegisterModelFormat(ModelFormat);
1209 end.