| 1 |
{ |
| 2 |
Copyright 2003-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 |
{ @abstract(Loading and saving nodes.) |
| 17 |
|
| 18 |
Almost every format is handled by converting it into VRML / X3D nodes graph. |
| 19 |
This allows to use nodes throughout the engine, for all rendering and processing. |
| 20 |
|
| 21 |
Basic guide for adding a new format: |
| 22 |
|
| 23 |
@unorderedList( |
| 24 |
@item( |
| 25 |
Particular formats are implemented inside various X3DLoadInternalXxx units. |
| 26 |
Implementation of this unit calls them. In the future, |
| 27 |
a mechanism that allows you to "register" an importer, without modifying |
| 28 |
this unit's implementation, may be done --- report if needed.) |
| 29 |
|
| 30 |
@item(Scene formats are also listed in the file filters constants: |
| 31 |
see LoadScene_FileFilters . |
| 32 |
Each format has a file filter to specifically choose this format, |
| 33 |
and also is added to the "All Scenes" filter.) |
| 34 |
|
| 35 |
@item(Enable castle-model-viewer to associate with this file format on freedesktops |
| 36 |
(GNOME, and other following freedesktop.org specs). For this, |
| 37 |
|
| 38 |
1. Update castle-model-viewer MIME database. |
| 39 |
Simply add appopriate element to ../../../castle-model-viewer/freedesktop/castle-model-viewer.xml. |
| 40 |
Format of that MIME xml file is self-explanatory. |
| 41 |
It's good idea to google first |
| 42 |
to search for standard MIME type for your model format (e.g. wikipedia |
| 43 |
shows mime types for formats). |
| 44 |
If none is found, just use application/x-???, where ??? is some short |
| 45 |
name for your format. |
| 46 |
|
| 47 |
2. After adding to MIME database, you want to also add format to |
| 48 |
../../../castle-model-viewer/freedesktop/castle-model-viewer.desktop, to indicate that |
| 49 |
castle-model-viewer handles this MIME type. |
| 50 |
|
| 51 |
3. Finally, also add this to ../../../castle-model-viewer/freedesktop/install_thumbnailer.sh, |
| 52 |
so that GNOME nautilus thumbnailers for this MIME types can be installed.) |
| 53 |
|
| 54 |
@item(You probably also want to extend documentation. |
| 55 |
At least https://castle-engine.io/creating_data_model_formats.php , |
| 56 |
it lists all supported scene formats.) |
| 57 |
) |
| 58 |
} |
| 59 |
unit X3DLoad; |
| 60 |
|
| 61 |
{$I castleconf.inc} |
| 62 |
|
| 63 |
interface |
| 64 |
|
| 65 |
uses SysUtils, Classes, |
| 66 |
CastleUtils, CastleVectors, X3DNodes, CastleStringUtils; |
| 67 |
|
| 68 |
{ Load a scene as X3D node. Guesses scene format based on the URL extension. |
| 69 |
We load a large number of formats, see https://castle-engine.io/creating_data_model_formats.php . |
| 70 |
|
| 71 |
All the scene formats are loaded as a graph of X3D nodes. |
| 72 |
|
| 73 |
URL is downloaded using the CastleDownload unit, |
| 74 |
so it supports files, http resources and more. |
| 75 |
See https://castle-engine.io/manual_network.php |
| 76 |
about supported URL schemes. |
| 77 |
If you all you care about is loading normal files, then just pass |
| 78 |
a normal filename (absolute or relative to the current directory) |
| 79 |
as the URL parameter. |
| 80 |
|
| 81 |
To actually display, animate and do many other things with the loaded |
| 82 |
model, you usually want to load it to TCastleScene, using |
| 83 |
the @link(TCastleSceneCore.Load) method. |
| 84 |
Like this: |
| 85 |
|
| 86 |
@longCode(# |
| 87 |
var |
| 88 |
RootNode: TX3DRootNode; |
| 89 |
Scene: TCastleScene; |
| 90 |
begin |
| 91 |
RootNode := LoadNode('my_model.x3d'); |
| 92 |
Scene := TCastleScene.Create(Application); |
| 93 |
Scene.Load(RootNode, true); |
| 94 |
// The 2nd parameter of Load says that Scene owns RootNode |
| 95 |
end; |
| 96 |
#) |
| 97 |
|
| 98 |
Actually, in most cases you don't need to use LoadNode (and this unit, X3DLoad) |
| 99 |
at all, and you can simply load from an URL: |
| 100 |
|
| 101 |
@longCode(# |
| 102 |
var |
| 103 |
Scene: TCastleScene; |
| 104 |
begin |
| 105 |
Scene := TCastleScene.Create(Application); |
| 106 |
Scene.Load('my_model.x3d'); |
| 107 |
// you can access Scene.RootNode after loading, if needed |
| 108 |
end; |
| 109 |
#) |
| 110 |
|
| 111 |
Note that usually you want to load models from the game data, |
| 112 |
so you would actually use @code('castle-data:/my_model.x3d') URL instead |
| 113 |
of @code('my_model.x3d'). |
| 114 |
} |
| 115 |
function LoadNode(const Url: String): TX3DRootNode; overload; |
| 116 |
|
| 117 |
{ Load a scene as X3D node from TStream. |
| 118 |
|
| 119 |
Takes a TStream instance with contents to load, |
| 120 |
and MimeType parameter determines the data content (e.g. X3D or glTF or Spine model). |
| 121 |
|
| 122 |
In most cases, instead of this, you should use a simpler LoadNode overloaded version |
| 123 |
that just takes URL parameter without the explicit Stream or MimeType parameters. |
| 124 |
It will automatically create the stream and guess MIME type. |
| 125 |
|
| 126 |
The BaseUrl parameter here is used to resolve relative URLs inside the model, |
| 127 |
e.g. references to textures from various 3D and 2D model formats are resolved |
| 128 |
relative to this base URL. |
| 129 |
It generally should be a URL from which you downloaded the model. |
| 130 |
If you don't know it, you can use the current directory (which can be conveniently |
| 131 |
expressed by BaseUrl = '', which is a relative empty URL implying current working dir). |
| 132 |
We @bold(do not) use BaseUrl to determine file contents (e.g. we don't look at filename |
| 133 |
extension here) in this routine. |
| 134 |
|
| 135 |
Note that some formats (like glTF) require a stream with free seeking capabilities. |
| 136 |
Call @link(Download) with soForceMemoryStream, or wrap the stream in TMemoryStream manually, |
| 137 |
if unsure. The overloaded LoadNode without explicit TStream uses soForceMemoryStream |
| 138 |
when necessary. |
| 139 |
|
| 140 |
Note that this routine assumes that the stream is not gzip-compressed. |
| 141 |
The overloaded LoadNode without explicit TStream accounts for gzip-compressed streams |
| 142 |
in some cases. |
| 143 |
} |
| 144 |
function LoadNode(const Stream: TStream; BaseUrl: String; const MimeType: String): TX3DRootNode; overload; |
| 145 |
|
| 146 |
const |
| 147 |
DefaultBakedAnimationSmoothness = 1; |
| 148 |
|
| 149 |
var |
| 150 |
{ A smoothness value for "baked" animations loaded from castle-anim-frames |
| 151 |
files. This is multiplied by the scenes_per_time value recorded |
| 152 |
in castle-anim-frames file (30 by default), and determines the number |
| 153 |
of extra frames we add to the baked animation (between key frames). } |
| 154 |
BakedAnimationSmoothness: Single = DefaultBakedAnimationSmoothness; |
| 155 |
|
| 156 |
{ Save model to a file. |
| 157 |
|
| 158 |
See SaveNode_FileFilters for all model formats that we can save. |
| 159 |
|
| 160 |
If you provide explicit URL, it determines the output format. |
| 161 |
If you provide a Stream and MimeType, then MimeType determines the output format. |
| 162 |
E.g. use MimeType = 'model/x3d+vrml' to X3D classic encoding, |
| 163 |
or MimeType = 'model/x3d+xml' to X3D XML encoding. |
| 164 |
|
| 165 |
@param(Generator Optional name, or short description, of the application |
| 166 |
generating this file. This value is not interpreted in any way, |
| 167 |
it is simply a "metadata" information we may store in the resulting file. |
| 168 |
) |
| 169 |
|
| 170 |
@param(Source Optional name of the original file, if this file is a result of some |
| 171 |
conversion or transformation. This value is not interpreted in any way, |
| 172 |
it is simply a "metadata" information we may store in the resulting file. |
| 173 |
) |
| 174 |
} |
| 175 |
procedure SaveNode(const Node: TX3DRootNode; |
| 176 |
const Url: String; |
| 177 |
const Generator: String = ''; |
| 178 |
const Source: String = ''); overload; |
| 179 |
procedure SaveNode(const Node: TX3DRootNode; |
| 180 |
const Stream: TStream; const MimeType: String; |
| 181 |
const Generator: String = ''; |
| 182 |
const Source: String = ''); overload; |
| 183 |
|
| 184 |
{ File filters for files loaded by @link(TCastleSceneCore.Load) and @link(LoadNode). |
| 185 |
Suitable for TFileFilterList.AddFiltersFromString and TCastleWindow.FileDialog. } |
| 186 |
function LoadScene_FileFilters: String; |
| 187 |
|
| 188 |
{ File filters for files saved by @link(SaveNode). |
| 189 |
Suitable for TFileFilterList.AddFiltersFromString and TCastleWindow.FileDialog. } |
| 190 |
function SaveNode_FileFilters: String; |
| 191 |
|
| 192 |
type |
| 193 |
TModelLoadEvent = function (const Stream: TStream; const BaseUrl: String): |
| 194 |
TX3DRootNode; |
| 195 |
TModelSaveEvent = procedure (const Node: TX3DRootNode; const Stream: TStream; |
| 196 |
const Generator: String; const Source: String); |
| 197 |
|
| 198 |
{ Information about a model format, used with @link(RegisterModelFormat). } |
| 199 |
TModelFormat = class |
| 200 |
public |
| 201 |
{ How to load given model format (from TStream to TX3DRootNode). |
| 202 |
May be unassigned if we cannot load it. } |
| 203 |
OnLoad: TModelLoadEvent; |
| 204 |
|
| 205 |
{ Does the @link(OnLoad) event require a TStream within which we can |
| 206 |
freely seek. If @true, we will load it with soForceMemoryStream |
| 207 |
for @link(Download). } |
| 208 |
OnLoadForceMemoryStream: Boolean; |
| 209 |
|
| 210 |
{ How to save given model format (from TX3DRootNode to TStream). |
| 211 |
May be unassigned if we cannot save it. } |
| 212 |
OnSave: TModelSaveEvent; |
| 213 |
|
| 214 |
{ List of MIME types. At least one MIME type must be provided here, |
| 215 |
at the time you call @link(RegisterModelFormat). } |
| 216 |
MimeTypes: TCastleStringList; |
| 217 |
|
| 218 |
{ File filter name, like "X3D classic (*.x3dv)". |
| 219 |
Must be non-empty. |
| 220 |
|
| 221 |
It's your choice whether to show here extensions, |
| 222 |
and if yes -> it's your responsibility |
| 223 |
to make sure they match information in @link(Extensions) |
| 224 |
and map to one of the MIME types specified in @link(MimeTypes). |
| 225 |
|
| 226 |
To map extensions -> MIME types, add the map to @link(UriMimeExtensions). } |
| 227 |
FileFilterName: String; |
| 228 |
|
| 229 |
{ List of file extensions (including the leading dot) like '.x3dv'. |
| 230 |
Must be non-empty, that is: at least one extension must be provided here. |
| 231 |
|
| 232 |
If the model filenames contains multiple extensions, you can specify them |
| 233 |
here, e.g. ".x3dv.gz" is a valid extension on this list. |
| 234 |
It is common to pack X3D files in gzip and use ".x3dv.gz" extension, |
| 235 |
so we handle it here. |
| 236 |
|
| 237 |
It's your responsibility to make sure that all extensions here |
| 238 |
map to one of the MIME types specified in @link(MimeTypes). |
| 239 |
|
| 240 |
To map extensions -> MIME types, add the map to @link(UriMimeExtensions). } |
| 241 |
Extensions: TCastleStringList; |
| 242 |
|
| 243 |
constructor Create; |
| 244 |
destructor Destroy; override; |
| 245 |
end; |
| 246 |
|
| 247 |
(*Register given model format, to enable loading and/or saving it |
| 248 |
using @link(LoadNode), @link(SaveNode) and all routines on top of them, |
| 249 |
like @link(TCastleSceneCore.Load). |
| 250 |
|
| 251 |
The ModelFormat instance given here becomes owned by the internal list |
| 252 |
in this unit. Do not free it, do not modify it after registering it. |
| 253 |
|
| 254 |
Here's an example how to register a new model format, USD. |
| 255 |
This example assumes you want to register the new model format |
| 256 |
in the @code(initialization) section of a unit, which is the most common place, |
| 257 |
as it ensures that the format is registered for any future use in the application. |
| 258 |
|
| 259 |
@longCode(# |
| 260 |
function LoadUSD(const Stream: TStream; const BaseUrl: String): TX3DRootNode; |
| 261 |
begin |
| 262 |
Result := TX3DRootNode.Create; |
| 263 |
// TODO: Load USD here |
| 264 |
end; |
| 265 |
|
| 266 |
var |
| 267 |
ModelFormat: TModelFormat; |
| 268 |
initialization |
| 269 |
ModelFormat := TModelFormat.Create; |
| 270 |
ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadUSD; |
| 271 |
ModelFormat.MimeTypes.Add('model/vnd.usda'); |
| 272 |
ModelFormat.MimeTypes.Add('model/vnd.usdz+zip'); |
| 273 |
ModelFormat.FileFilterName := 'Universal Scene Description'; |
| 274 |
ModelFormat.Extensions.Add('.usd'); |
| 275 |
ModelFormat.Extensions.Add('.usda'); |
| 276 |
ModelFormat.Extensions.Add('.usdc'); |
| 277 |
ModelFormat.Extensions.Add('.usdz'); |
| 278 |
RegisterModelFormat(ModelFormat); |
| 279 |
|
| 280 |
UriMimeExtensions['.usd'] := 'model/vnd.usda'; |
| 281 |
UriMimeExtensions['.usda'] := 'model/vnd.usda'; |
| 282 |
UriMimeExtensions['.usdc'] := 'model/vnd.usda'; |
| 283 |
UriMimeExtensions['.usdz'] := 'model/vnd.usdz+zip'; |
| 284 |
end. |
| 285 |
#) *) |
| 286 |
procedure RegisterModelFormat(const ModelFormat: TModelFormat); |
| 287 |
|
| 288 |
implementation |
| 289 |
|
| 290 |
uses Generics.Collections, |
| 291 |
CastleClassUtils, CastleImages, CastleUriUtils, |
| 292 |
X3DLoadInternalGEO, X3DLoadInternal3DS, X3DLoadInternalOBJ, |
| 293 |
X3DLoadInternalCollada, X3DLoadInternalSpine, X3DLoadInternalSTL, |
| 294 |
X3DLoadInternalMD3, X3DLoadInternalGLTF, X3DLoadInternalImage, |
| 295 |
X3DLoadInternalCocos2d, CastleInternalNodeInterpolator, |
| 296 |
CastleInternalSpritesheet, CastleDownload, X3DLoadInternalTiledMap; |
| 297 |
|
| 298 |
{ declare FRegisteredModelFormats early ------------------------------------- } |
| 299 |
|
| 300 |
type |
| 301 |
TModelFormatList = class({$ifdef FPC}specialize{$endif} TObjectList<TModelFormat>) |
| 302 |
function FindMimeType(const MimeType: string): TModelFormat; |
| 303 |
end; |
| 304 |
|
| 305 |
var |
| 306 |
FRegisteredModelFormats: TModelFormatList; |
| 307 |
|
| 308 |
{ loading -------------------------------------------------------------------- } |
| 309 |
|
| 310 |
{ Load a sequence of nodes to an animation suitable for TNodeInterpolator. |
| 311 |
Allows to read sequence of static models as an animation, |
| 312 |
e.g. Blender can export Wavefront OBJ like that. } |
| 313 |
function LoadSequenceUsingCounter(const Url: String): TX3DRootNode; |
| 314 |
|
| 315 |
function LoadAnimationUsingCounter(const Url: String): TNodeInterpolator.TAnimationList; |
| 316 |
const |
| 317 |
FramesPerSecond = 30; |
| 318 |
var |
| 319 |
FrameIndex, FirstFrameIndex: Integer; |
| 320 |
Animation: TNodeInterpolator.TAnimation; |
| 321 |
FrameUrl: String; |
| 322 |
begin |
| 323 |
Result := TNodeInterpolator.TAnimationList.Create(true); |
| 324 |
try |
| 325 |
Animation := TNodeInterpolator.TAnimation.Create; |
| 326 |
Result.Add(Animation); |
| 327 |
Animation.Name := TNodeInterpolator.DefaultAnimationName; |
| 328 |
Animation.ScenesPerTime := TNodeInterpolator.DefaultScenesPerTime; |
| 329 |
Animation.Epsilon := TNodeInterpolator.DefaultEpsilon; |
| 330 |
Animation.Loop := false; |
| 331 |
Animation.Backwards := false; |
| 332 |
|
| 333 |
FrameIndex := 0; |
| 334 |
FrameUrl := FormatNameCounter(Url, FrameIndex, false); |
| 335 |
if not UriFileExists(FrameUrl) then |
| 336 |
begin |
| 337 |
FrameIndex := 1; |
| 338 |
FrameUrl := FormatNameCounter(Url, FrameIndex, false); |
| 339 |
if not UriFileExists(FrameUrl) then |
| 340 |
raise Exception.CreateFmt('First model in a sequence ("%s" or "%s") cannot be found', [ |
| 341 |
FormatNameCounter(Url, 0, false), |
| 342 |
FormatNameCounter(Url, 1, false) |
| 343 |
]); |
| 344 |
end; |
| 345 |
|
| 346 |
FirstFrameIndex := FrameIndex; |
| 347 |
|
| 348 |
repeat |
| 349 |
Animation.KeyNodes.Add(LoadNode(FrameUrl)); |
| 350 |
Animation.KeyTimes.Add((FrameIndex - FirstFrameIndex) / FramesPerSecond); |
| 351 |
Inc(FrameIndex); |
| 352 |
FrameUrl := FormatNameCounter(Url, FrameIndex, false); |
| 353 |
until not UriFileExists(FrameUrl); |
| 354 |
except |
| 355 |
Result.FreeKeyNodesContents; |
| 356 |
FreeAndNil(Result); |
| 357 |
raise; |
| 358 |
end; |
| 359 |
end; |
| 360 |
|
| 361 |
var |
| 362 |
Animations: TNodeInterpolator.TAnimationList; |
| 363 |
begin |
| 364 |
Animations := LoadAnimationUsingCounter(Url); |
| 365 |
try |
| 366 |
Result := TNodeInterpolator.LoadToX3D(Animations); |
| 367 |
finally FreeAndNil(Animations) end; |
| 368 |
end; |
| 369 |
|
| 370 |
function LoadNode(const Url: String): TX3DRootNode; |
| 371 |
var |
| 372 |
MimeType, UrlWithoutAnchor: string; |
| 373 |
|
| 374 |
function ForceMemoryStream(const MimeType: String): Boolean; |
| 375 |
var |
| 376 |
ModelFormat: TModelFormat; |
| 377 |
begin |
| 378 |
if FRegisteredModelFormats = nil then |
| 379 |
raise Exception.Create('No model formats registered, you try to LoadNode too early, before initialization of Castle Game Engine units that register model formats'); |
| 380 |
|
| 381 |
ModelFormat := FRegisteredModelFormats.FindMimeType(MimeType); |
| 382 |
if ModelFormat = nil then |
| 383 |
raise Exception.CreateFmt('Unrecognized file type "%s" for scene with base URL "%s"', [ |
| 384 |
MimeType, |
| 385 |
UriDisplay(Url) |
| 386 |
]); |
| 387 |
|
| 388 |
Result := ModelFormat.OnLoadForceMemoryStream; |
| 389 |
end; |
| 390 |
|
| 391 |
function DownloadAndLoad(DownloadOptions: TStreamOptions): TX3DRootNode; |
| 392 |
var |
| 393 |
Stream: TStream; |
| 394 |
begin |
| 395 |
{ Some formats readers require seeking capability. |
| 396 |
Testcase: e.g. PasGLTF does seeking, |
| 397 |
and without soForceMemoryStream reading glTF from Android assets (TReadAssetStream) would fail. } |
| 398 |
|
| 399 |
if ForceMemoryStream(MimeType) then |
| 400 |
Include(DownloadOptions, soForceMemoryStream); |
| 401 |
|
| 402 |
Stream := Download(UrlWithoutAnchor, DownloadOptions); |
| 403 |
try |
| 404 |
Result := LoadNode(Stream, Url, MimeType); |
| 405 |
finally FreeAndNil(Stream) end; |
| 406 |
end; |
| 407 |
|
| 408 |
var |
| 409 |
Gzipped: boolean; |
| 410 |
begin |
| 411 |
{ We always download stripping anchor. |
| 412 |
Spine, sprite sheets (Starling, Cocos2d), images, Tiled all expect such anchor. |
| 413 |
Other model formats may support it as well in the future. } |
| 414 |
UrlWithoutAnchor := UriDeleteAnchor(Url); |
| 415 |
|
| 416 |
if HasNameCounter(Url, false) then |
| 417 |
begin |
| 418 |
Result := LoadSequenceUsingCounter(Url) |
| 419 |
end else |
| 420 |
begin |
| 421 |
MimeType := UriMimeType(Url, Gzipped); |
| 422 |
if Gzipped then |
| 423 |
begin |
| 424 |
Result := DownloadAndLoad([soGzip]) |
| 425 |
end else |
| 426 |
try |
| 427 |
Result := DownloadAndLoad([]) |
| 428 |
except |
| 429 |
{ Some readers (only X3D for now, but maybe more will join in future) |
| 430 |
detect that stream is gzip-compressed and raise EGzipCompressed. |
| 431 |
|
| 432 |
In this case we reopen the file, creating new stream. |
| 433 |
It's a simple and working solution in practice -- it allows us to read X3D files |
| 434 |
compressed by gzip but without indicating this by file extension. |
| 435 |
|
| 436 |
Other ideas to implement it: |
| 437 |
|
| 438 |
1. Pipe the output always by gzip decompression. |
| 439 |
|
| 440 |
But this means additional overhead always, |
| 441 |
even though in 99% cases the input is not gzip-compressed. |
| 442 |
We already filter the input through some streams anyway |
| 443 |
(we already wrap TFileStream in TBufferedReadStream in case of typical X3D). |
| 444 |
|
| 445 |
2. Rewind the stream and only pipe it conditionally. |
| 446 |
|
| 447 |
But this forces the stream to be freely "seekable", |
| 448 |
not all stream implementations allow it. } |
| 449 |
on EGzipCompressed do |
| 450 |
Result := DownloadAndLoad([soGzip]) |
| 451 |
end; |
| 452 |
end; |
| 453 |
end; |
| 454 |
|
| 455 |
function LoadNode(const Stream: TStream; |
| 456 |
BaseUrl: String; const MimeType: String): TX3DRootNode; |
| 457 |
var |
| 458 |
ModelFormat: TModelFormat; |
| 459 |
begin |
| 460 |
if FRegisteredModelFormats = nil then |
| 461 |
raise Exception.Create('No model formats registered, you try to LoadNode too early, before initialization of Castle Game Engine units that register model formats'); |
| 462 |
|
| 463 |
{ All internal loading functions may assume BaseUrl is absolute. |
| 464 |
|
| 465 |
E.g. from glTF loader: |
| 466 |
|
| 467 |
Absolute BaseUrl makes the later Document.RootPath calculation correct. |
| 468 |
Otherwise "InclPathDelim(ExtractFilePath(UriToFilenameSafe('my_file.gtlf')))" |
| 469 |
would result in '/' (accidentally making all TPasGLTF.TImage.Uri values |
| 470 |
relative to root directory on Unix). This was reproducible doing |
| 471 |
"castle-model-viewer my_file.gtlf" on the command-line. |
| 472 |
|
| 473 |
Also castle-model-converter assumes that passing "stdin.x3dv" means that "stdin.x3dv" |
| 474 |
file is in current working dir. Using AbsoluteUri(BaseUrl) correctly |
| 475 |
adds the current working dir to URL. } |
| 476 |
BaseUrl := AbsoluteUri(BaseUrl); |
| 477 |
|
| 478 |
ModelFormat := FRegisteredModelFormats.FindMimeType(MimeType); |
| 479 |
if ModelFormat = nil then |
| 480 |
raise Exception.CreateFmt('Unrecognized file type "%s" for scene with base URL "%s"', [ |
| 481 |
MimeType, |
| 482 |
UriDisplay(BaseUrl) |
| 483 |
]); |
| 484 |
|
| 485 |
if not Assigned(ModelFormat.OnLoad) then |
| 486 |
raise Exception.CreateFmt('Cannot load model format "%s"', [MimeType]); |
| 487 |
|
| 488 |
Result := ModelFormat.OnLoad(Stream, BaseUrl); |
| 489 |
|
| 490 |
Assert(Result <> nil); |
| 491 |
|
| 492 |
{ Fix names after loading (from any format -- X3D, glTF can have collisions in names), |
| 493 |
to have non-unique names for accessing everything, |
| 494 |
e.g. EXPORT statements should use correct (non-unique) names |
| 495 |
to be IMPORTed. |
| 496 |
Testcase: x3d-tests/gltf_inlined/avocado_and_exports/avocado_imported.x3dv . } |
| 497 |
Result.InternalFixNodeNames; |
| 498 |
end; |
| 499 |
|
| 500 |
{ saving -------------------------------------------------------------------- } |
| 501 |
|
| 502 |
procedure SaveNode(const Node: TX3DRootNode; |
| 503 |
const Url: String; |
| 504 |
const Generator: String; |
| 505 |
const Source: String); |
| 506 |
var |
| 507 |
Stream: TStream; |
| 508 |
begin |
| 509 |
Stream := UrlSaveStream(Url); |
| 510 |
try |
| 511 |
SaveNode(Node, Stream, UriMimeType(Url), Generator, Source); |
| 512 |
finally FreeAndNil(Stream) end; |
| 513 |
end; |
| 514 |
|
| 515 |
procedure SaveNode(const Node: TX3DRootNode; |
| 516 |
const Stream: TStream; const MimeType: String; |
| 517 |
const Generator: String; |
| 518 |
const Source: String); |
| 519 |
var |
| 520 |
ModelFormat: TModelFormat; |
| 521 |
begin |
| 522 |
if FRegisteredModelFormats = nil then |
| 523 |
raise Exception.Create('No model formats registered, you try to SaveNode too early, before initialization of Castle Game Engine units that register model formats'); |
| 524 |
|
| 525 |
ModelFormat := FRegisteredModelFormats.FindMimeType(MimeType); |
| 526 |
if ModelFormat = nil then |
| 527 |
raise Exception.CreateFmt('Unrecognized file type "%s" for saving scene', [ |
| 528 |
MimeType |
| 529 |
]); |
| 530 |
|
| 531 |
if not Assigned(ModelFormat.OnSave) then |
| 532 |
raise Exception.CreateFmt('Cannot save model format "%s"', [MimeType]); |
| 533 |
|
| 534 |
ModelFormat.OnSave(Node, Stream, Generator, Source); |
| 535 |
end; |
| 536 |
|
| 537 |
{ file filters -------------------------------------------------------------- } |
| 538 |
|
| 539 |
{ Common implementation of LoadScene_FileFilters and SaveNode_FileFilters. } |
| 540 |
function SaveLoad_FileFilters(const Load: boolean): String; |
| 541 |
|
| 542 |
function AllExtensions: String; |
| 543 |
var |
| 544 |
ModelFormat: TModelFormat; |
| 545 |
Ext: string; |
| 546 |
begin |
| 547 |
Result := ''; |
| 548 |
for ModelFormat in FRegisteredModelFormats do |
| 549 |
for Ext in ModelFormat.Extensions do |
| 550 |
Result := SAppendPart(Result, ';', '*' + Ext); |
| 551 |
end; |
| 552 |
|
| 553 |
function FormatExtensions(const ModelFormat: TModelFormat): String; |
| 554 |
var |
| 555 |
Ext: string; |
| 556 |
begin |
| 557 |
Result := ''; |
| 558 |
for Ext in ModelFormat.Extensions do |
| 559 |
Result := SAppendPart(Result, ';', '*' + Ext); |
| 560 |
end; |
| 561 |
|
| 562 |
var |
| 563 |
ModelFormat: TModelFormat; |
| 564 |
DefaultMark: String; |
| 565 |
begin |
| 566 |
if FRegisteredModelFormats = nil then |
| 567 |
raise Exception.Create('No model formats registered, you try to build filters list too early, before initialization of Castle Game Engine units that register model formats'); |
| 568 |
|
| 569 |
Result := 'All Files|*'; |
| 570 |
|
| 571 |
if Load then |
| 572 |
begin |
| 573 |
{ When loading, "All Scenes" is the default filter. } |
| 574 |
Result := Result + '|*All Scenes|' + AllExtensions; |
| 575 |
end; |
| 576 |
|
| 577 |
for ModelFormat in FRegisteredModelFormats do |
| 578 |
begin |
| 579 |
// exclude ModelFormat that cannot be loaded / saved |
| 580 |
if Load then |
| 581 |
begin |
| 582 |
if not Assigned(ModelFormat.OnLoad) then |
| 583 |
Continue; |
| 584 |
end else |
| 585 |
begin |
| 586 |
if not Assigned(ModelFormat.OnSave) then |
| 587 |
Continue; |
| 588 |
end; |
| 589 |
|
| 590 |
{ When saving, the default filter is X3D XML. } |
| 591 |
DefaultMark := Iff((not Load) and (ModelFormat.MimeTypes[0] = 'model/x3d+xml'), '*', ''); |
| 592 |
|
| 593 |
Result := Result + '|' + |
| 594 |
DefaultMark + |
| 595 |
ModelFormat.FileFilterName + '|' + FormatExtensions(ModelFormat); |
| 596 |
end; |
| 597 |
end; |
| 598 |
|
| 599 |
function LoadScene_FileFilters: String; |
| 600 |
begin |
| 601 |
Result := SaveLoad_FileFilters(true); |
| 602 |
end; |
| 603 |
|
| 604 |
function SaveNode_FileFilters: String; |
| 605 |
begin |
| 606 |
Result := SaveLoad_FileFilters(false); |
| 607 |
end; |
| 608 |
|
| 609 |
{ TModelFormat and friends -------------------------------------------------- } |
| 610 |
|
| 611 |
constructor TModelFormat.Create; |
| 612 |
begin |
| 613 |
inherited; |
| 614 |
MimeTypes := TCastleStringList.Create; |
| 615 |
MimeTypes.CaseSensitive := false; // makes TModelFormatList.FindMimeType ignore case |
| 616 |
Extensions := TCastleStringList.Create; |
| 617 |
end; |
| 618 |
|
| 619 |
destructor TModelFormat.Destroy; |
| 620 |
begin |
| 621 |
FreeAndNil(MimeTypes); |
| 622 |
FreeAndNil(Extensions); |
| 623 |
inherited; |
| 624 |
end; |
| 625 |
|
| 626 |
function TModelFormatList.FindMimeType(const MimeType: string): TModelFormat; |
| 627 |
begin |
| 628 |
for Result in Self do |
| 629 |
if Result.MimeTypes.IndexOf(MimeType) <> -1 then |
| 630 |
Exit; |
| 631 |
Result := nil; |
| 632 |
end; |
| 633 |
|
| 634 |
procedure RegisterModelFormat(const ModelFormat: TModelFormat); |
| 635 |
|
| 636 |
procedure CheckMimeTypesNotYetRegistered(const NewMimeTypes: TStrings); |
| 637 |
var |
| 638 |
NewMimeType: String; |
| 639 |
ExistingModelFormat: TModelFormat; |
| 640 |
begin |
| 641 |
for NewMimeType in NewMimeTypes do |
| 642 |
begin |
| 643 |
ExistingModelFormat := FRegisteredModelFormats.FindMimeType(NewMimeType); |
| 644 |
if ExistingModelFormat <> nil then |
| 645 |
raise Exception.CreateFmt('RegisterModelFormat: MIME type "%s" is already registered', [NewMimeType]); |
| 646 |
end; |
| 647 |
end; |
| 648 |
|
| 649 |
var |
| 650 |
Ext: string; |
| 651 |
begin |
| 652 |
// validate |
| 653 |
if ModelFormat.MimeTypes.Count = 0 then |
| 654 |
raise Exception.Create('RegisterModelFormat: ModelFormat.MimeTypes must be non-empty at registration'); |
| 655 |
if ModelFormat.FileFilterName = '' then |
| 656 |
raise Exception.Create('RegisterModelFormat: ModelFormat.FileFilters must be non-empty at registration'); |
| 657 |
if ModelFormat.Extensions.Count = 0 then |
| 658 |
raise Exception.Create('RegisterModelFormat: ModelFormat.Extensions must be non-empty at registration'); |
| 659 |
for Ext in ModelFormat.Extensions do |
| 660 |
if not IsPrefix('.', Ext, false) then |
| 661 |
raise Exception.CreateFmt('RegisterModelFormat: ModelFormat.Extensions must start with a dot, but "%s" does not', [Ext]); |
| 662 |
|
| 663 |
if FRegisteredModelFormats = nil then |
| 664 |
FRegisteredModelFormats := TModelFormatList.Create(true); |
| 665 |
CheckMimeTypesNotYetRegistered(ModelFormat.MimeTypes); |
| 666 |
FRegisteredModelFormats.Add(ModelFormat); |
| 667 |
end; |
| 668 |
|
| 669 |
initialization |
| 670 |
finalization |
| 671 |
FreeAndNil(FRegisteredModelFormats); |
| 672 |
end. |