Debian Codegraph @

src/scene/x3d/x3dnodes_encoding_xml.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2008-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Global routines for parsing XML X3D encoding. }
18
19 {$ifdef read_interface}
20
21 const
22 LoadX3DXml_FileFilters =
23 'All files|*|' +
24 '*X3D XML (*.x3d, *.x3dz, *.x3d.gz)|*.x3d;*.x3dz;*.x3d.gz'
25 deprecated 'use LoadNode and LoadScene_FileFilters';
26
27 { Read X3D encoded in XML, and convert it to VRML/X3D nodes graph.
28
29 Overloaded version that takes Stream as a parameter expects that
30 reading the stream returns the uncompressed content (no longer gzip
31 compressed). This version also takes Url as a parameter,
32 but it is not used to load contents (these are inside Stream),
33 it it only used to resolve relative URLs inside content and for error messages.
34
35 @exclude
36
37 @groupBegin }
38 function LoadX3DXml(const Url: String; const Gzipped: boolean): TX3DRootNode; overload; deprecated 'use LoadNode';
39
40 { @exclude }
41 function LoadX3DXmlInternal(const Stream: TStream; const BaseUrl: String): TX3DRootNode; overload;
42
43 { @exclude }
44 function LoadX3DXmlInternal(const X3DElement: TDOMElement; const BaseUrl: String): TX3DRootNode; overload;
45
46 { @groupEnd }
47
48 {$endif read_interface}
49
50 {$ifdef read_implementation}
51
52 { Like "Element.AttributeString(AttributeName, Value)",
53 but also decoded the read string using DecodeX3DName. }
54 function XMLAttributeX3DName(const Element: TDOMElement;
55 const AttributeName: String; var Value: String): Boolean;
56 begin
57 Result := Element.AttributeString(AttributeName, Value);
58 if Result then
59 Value := DecodeX3DName(Value);
60 end;
61
62 type
63 EX3DXmlError = class(EX3DError);
64 EX3DXmlNotAllowedError = class(EX3DXmlError);
65
66 const
67 SAttrContainerField = 'containerField';
68 SAttrDEF = 'DEF';
69
70 function ParseXMLNode(const Element: TDOMElement;
71 out ContainerField: String; const Reader: TX3DReaderNames;
72 const NilIfUnresolvedUSE: boolean): TX3DNode; overload; forward;
73 function ParseXMLNode(const Element: TDOMElement;
74 out ContainerField: String; const Reader: TX3DReaderNames;
75 const NilIfUnresolvedUSE: Boolean;
76 const AllowNodeCycle: Boolean; var UsingNodeCycle: Boolean): TX3DNode; overload; forward;
77 function ParseStatements(Element: TDOMElement;
78 FileTopLevel: boolean;
79 X3DHeaderElement: TDOMElement; Reader: TX3DReaderNames): TX3DRootNode; overload; forward;
80
81 { Checks is Element a correct <connect> element, extracting
82 nodeField and protoField value. Returns @true if all Ok, otherwise
83 returns @false. }
84 function ParseConnectElement(Element: TDOMElement;
85 out NodeField, ProtoField: String): boolean;
86 begin
87 Result := false;
88
89 if Element.TagName <> 'connect' then
90 begin
91 WritelnWarning('X3D', 'Only <connect> elements are allowed inside <IS> element');
92 Exit;
93 end;
94
95 if not Element.AttributeString('nodeField', NodeField) then
96 begin
97 WritelnWarning('X3D', 'Missing "nodeField" inside <connect> element');
98 Exit;
99 end;
100
101 if not Element.AttributeString('protoField', ProtoField) then
102 begin
103 WritelnWarning('X3D', 'Missing "protoField" inside <connect> element');
104 Exit;
105 end;
106
107 Result := true;
108 end;
109
110 procedure ParseISStatement(Node: TX3DNode; ISElement: TDOMElement;
111 var PositionInParent: Integer);
112 var
113 I: TXMLElementIterator;
114 NodeField, ProtoField: String;
115 NodeFieldOrEvent: TX3DFieldOrEvent;
116 begin
117 I := ISElement.ChildrenIterator;
118 try
119 while I.GetNext do
120 if ParseConnectElement(I.Current, NodeField, ProtoField) then
121 begin
122 NodeFieldOrEvent := Node.FieldOrEvent(NodeField);
123 if NodeFieldOrEvent <> nil then
124 begin
125 NodeFieldOrEvent.IsClauseNamesAdd(ProtoField);
126 NodeFieldOrEvent.PositionInParent := PositionInParent;
127 Inc(PositionInParent);
128 end else
129 WritelnWarning('X3D', Format('<connect> element "nodeField" doesn''t indicate any known field/event name: "%s"', [NodeField]));
130 end;
131 finally FreeAndNil(I) end;
132 end;
133
134 (*
135 Parse VRML node. This parses normal node (with optional DEF),
136 or node with USE attribute.
137
138 It's somewhat similar to classic VRML ParseNode.
139 (Admittedly, it was even implemented by copying and modifying
140 classic ParseNode :) ).
141
142 If we will find USE clause but node name will be unknown, the normal
143 behavior (when NilIfUnresolvedUSE = @false, default) is to raise
144 EX3DXmlNotAllowedError (just like in case of many other errors).
145 However, this is a particular parsing error, because we can probably
146 pretty safely continue parsing, ignoring this error.
147 So if you pass NilIfUnresolvedUSE = @true, this function will do
148 WritelnWarning and simply return @nil.
149
150 @raises(EX3DXmlNotAllowedError On various not-allowed errors.)
151
152 @raises(EX3DXmlUnknownNodeNotAllowed On a special parsing error:
153 we got unknown node name, and AllowedNodes was @false.
154
155 We have a special error class for this, because in some cases
156 it means that actually the unknown node name could be also
157 unknown field / proto etc. name, so error message for the user should
158 be better.)
159 *)
160 function ParseXMLNode(const Element: TDOMElement;
161 out ContainerField: String; const Reader: TX3DReaderNames;
162 const NilIfUnresolvedUSE: Boolean;
163 const AllowNodeCycle: Boolean; var UsingNodeCycle: Boolean): TX3DNode;
164
165 procedure ParseNamedNode(const NodeName: String);
166 var
167 NodeClass: TX3DNodeClass;
168 X3DType: String;
169 ProtoName: String;
170 Proto: TX3DPrototypeBase;
171 ProtoIter: TXMLElementIterator;
172 FieldActualValue, FieldName: String;
173 FieldIndex: Integer;
174 PositionInParent: Integer;
175 begin
176 X3DType := Element.TagName8;
177
178 if X3DType = 'ProtoInstance' then
179 begin
180 if not Element.AttributeString('name', ProtoName) then
181 raise EX3DXmlError.Create('<ProtoInstance> doesn''t specify "name" of the prototype');
182
183 Proto := Reader.Prototypes.Bound(ProtoName);
184 if Proto = nil then
185 raise EX3DXmlError.CreateFmt('<ProtoInstance> specifies unknown prototype name "%s"', [ProtoName]);
186
187 if (Proto is TX3DExternalPrototype) and
188 (TX3DExternalPrototype(Proto).ReferencedClass <> nil) then
189 Result := TX3DExternalPrototype(Proto).ReferencedClass.Create(NodeName, Reader.BaseUrl) else
190 Result := TX3DPrototypeNode.CreatePrototypeNode(NodeName, Reader.BaseUrl, Proto);
191
192 Reader.Nodes.Bind(Result, false);
193
194 { parse field values from <fieldValue> elements }
195 ProtoIter := Element.ChildrenIterator;
196 try
197 PositionInParent := 0;
198
199 while ProtoIter.GetNext do
200 begin
201 if ProtoIter.Current.TagName = 'fieldValue' then
202 begin
203 if not ProtoIter.Current.AttributeString('name', FieldName) then
204 begin
205 WritelnWarning('X3D', 'X3D XML: missing "name" attribute for <fieldValue> element');
206 Continue;
207 end;
208
209 FieldIndex := Result.IndexOfField(FieldName);
210 if FieldIndex = -1 then
211 begin
212 WritelnWarning('X3D', Format('X3D XML: <fieldValue> element references unknown field name "%s"', [FieldName]));
213 Continue;
214 end;
215
216 if ProtoIter.Current.AttributeString('value', FieldActualValue) then
217 Result.Fields[FieldIndex].ParseXMLAttribute(FieldActualValue, Reader) else
218 Result.Fields[FieldIndex].ParseXMLElement(ProtoIter.Current, Reader);
219
220 Result.Fields[FieldIndex].PositionInParent := PositionInParent;
221 end else
222 if ProtoIter.Current.TagName = 'IS' then
223 begin
224 ParseISStatement(Result, ProtoIter.Current, PositionInParent);
225 end else
226 begin
227 WritelnWarning('X3D', Format('X3D XML: only <fieldValue> or <IS> elements expected in prototype instantiation, but "%s" found', [ProtoIter.Current.TagName]));
228 end;
229
230 Inc(PositionInParent);
231 end;
232 finally FreeAndNil(ProtoIter) end;
233
234 { If it was normal (non-external) prototype, then instantiate
235 it now (this sort-of expands prototype "macro" in place). }
236 if Result is TX3DPrototypeNode then
237 try
238 Result := TX3DPrototypeNode(Result).Instantiate;
239 except
240 on E: EX3DPrototypeInstantiateError do
241 { Just write E.Message and silence the exception.
242 Result will simply remain as TX3DPrototypeNode instance in this case. }
243 WritelnWarning('X3D', E.Message);
244 end;
245 end else
246 begin
247 NodeClass := NodesManager.X3DTypeToClass(X3DType, Reader.Version);
248 if NodeClass <> nil then
249 begin
250 Result := NodeClass.Create(NodeName, Reader.BaseUrl);
251 Reader.Nodes.Bind(Result, false);
252 Result.ParseXML(Element, Reader);
253 end else
254 begin
255 Result := TX3DUnknownNode.CreateUnknown(NodeName, Reader.BaseUrl, X3DType);
256
257 { In classic VRML parser, we had special TX3DUnknownNode.Parse
258 that performed the "magic" trick of
259 ParseIgnoreToMatchingCurlyBracket. This is not needed for
260 X3D XML, we can simply omit the node by not looking
261 at it's attributes. All we need to do is to make
262 WritelnWarning warning. }
263
264 WritelnWarning('X3D', 'Unknown X3D node type "' + X3DType + '"');
265 end;
266 end;
267
268 Reader.Nodes.Bind(Result, true);
269 end;
270
271 var
272 NodeName, S: String;
273 UsedNodeFinished: boolean;
274 begin
275 Result := nil;
276 try
277 if XMLAttributeX3DName(Element, 'USE', NodeName) then
278 begin
279 { get appropriate node }
280 Result := Reader.Bound(NodeName, UsedNodeFinished, true);
281 { When AllowNodeCycle, then UsedNodeFinished=false is not a problem.
282 Just flip UsingNodeCycle to true, caller can handle a loop in node definition. }
283 if (Result <> nil) and (not UsedNodeFinished) and AllowNodeCycle then
284 begin
285 UsingNodeCycle := true;
286 UsedNodeFinished := true;
287 end;
288 if (Result = nil) or (not UsedNodeFinished) then
289 begin
290 if Result = nil then
291 S := Format(SIncorrectUse, [NodeName]) else
292 begin
293 S := Format(SNodeUseCycle, [NodeName]);
294 Result := nil; { return nil in case of cycles }
295 end;
296 if NilIfUnresolvedUSE then
297 WritelnWarning('X3D', S)
298 else
299 raise EX3DXmlNotAllowedError.Create(S);
300 end;
301 end else
302 begin
303 if XMLAttributeX3DName(Element, SAttrDEF, NodeName) then
304 begin
305 ParseNamedNode(NodeName)
306 end else
307 ParseNamedNode('');
308 end;
309
310 { calculate ContainerField.
311
312 Note that we do not differentiate here between the case of <USE>
313 element and real node element --- because that's the intention
314 of X3D specification, in both situations element may have
315 containerField attribute.
316
317 We either use DefaultContainerField, or explicit containerField value.
318 Note that containerField doesn't have to be preserved
319 (see demo_models/x3d/container_field_def_use.x3d).
320 Each USE occurrence must specify suitable containerField or use class default. }
321 if Result <> nil then
322 ContainerField := Result.DefaultContainerFieldInContext(
323 Reader.Version, Reader.ParentNode as TX3DNode)
324 else
325 ContainerField := ''; { will not be used anyway }
326 Element.AttributeString(SAttrContainerField, ContainerField);
327
328 except FreeAndNil(Result); raise end;
329 end;
330
331 function ParseXMLNode(const Element: TDOMElement;
332 out ContainerField: String; const Reader: TX3DReaderNames;
333 const NilIfUnresolvedUSE: boolean): TX3DNode;
334 var
335 IgnoredUsingNodeCycle: Boolean;
336 begin
337 IgnoredUsingNodeCycle := false;
338 Result := ParseXMLNode(Element, ContainerField, Reader, NilIfUnresolvedUSE, false, IgnoredUsingNodeCycle);
339 end;
340
341 { This parses a sequence of X3D statements: any number of nodes,
342 (external) protypes, routes.
343 This is good to use to parse whole X3D file (when FileTopLevel = true),
344 or a (non-external) prototype content (when FileTopLevel = false).
345
346 It's somewhat similar to classic ParseStatements.
347 (Admittedly, it was even implemented by copying and modifying
348 classic ParseStatements :) ). }
349 function ParseStatements(Element: TDOMElement;
350 FileTopLevel: boolean;
351 X3DHeaderElement: TDOMElement; Reader: TX3DReaderNames): TX3DRootNode; overload;
352 var
353 PositionInParent: Integer;
354
355 { Create root group node. }
356 function CreateRootNode: TX3DRootNode;
357 begin
358 Result := TX3DRootNode.Create('', Reader.BaseUrl);
359 Result.HasForceVersion := true;
360 Result.ForceVersion := Reader.Version;
361 end;
362
363 procedure ParseProfile;
364 var
365 Profile: String;
366 begin
367 { parse "profile" attribute }
368 if X3DHeaderElement.AttributeString('profile', Profile) then
369 begin
370 Result.Profile := Profile;
371 end else
372 { We allow PROFILE to be omitted.
373 Actually, we do not use profile for anything right now. }
374 WritelnWarning('X3D', 'X3D "profile" attribute missing');
375 end;
376
377 procedure ParseHead;
378
379 procedure ParseMeta(Element: TDOMElement);
380 var
381 MetaName, MetaContent: String;
382 begin
383 MetaName := '';
384 MetaContent := '';
385 Element.AttributeString('name', MetaName);
386 Element.AttributeString('content', MetaContent);
387 Result.Meta[MetaName] := MetaContent;
388 end;
389
390 procedure ParseComponent(Element: TDOMElement);
391 var
392 ComponentName: String;
393 ComponentLevel: Integer;
394 begin
395 if Element.AttributeString('name', ComponentName) then
396 begin
397 if not Element.AttributeInteger('level', ComponentLevel) then
398 ComponentLevel := 1;
399 Result.Components[ComponentName] := ComponentLevel;
400 end else
401 WritelnWarning('X3D', Format('X3D XML: <component> element without required "name" attribute',
402 [Element.TagName]));
403 end;
404
405 procedure ParseUnit(Element: TDOMElement);
406 var
407 Category, Name: String;
408 ConversionFactor: Float;
409 begin
410 if not Element.AttributeString('category', Category) then
411 begin
412 WritelnWarning('X3D', 'Missing <unit> category');
413 Exit;
414 end;
415
416 if not Element.AttributeString('name', Name) then
417 begin
418 WritelnWarning('X3D', 'Missing <unit> category');
419 Exit;
420 end;
421
422 if not Element.AttributeFloat('conversionFactor', ConversionFactor) then
423 begin
424 WritelnWarning('X3D', 'Missing <unit> category');
425 Exit;
426 end;
427
428 Reader.UnitConversion(Category, Name, ConversionFactor);
429 end;
430
431 var
432 Head: TDOMElement;
433 I: TXMLElementIterator;
434 begin
435 Head := X3DHeaderElement.ChildElement('head', false);
436 if Head = nil then Exit;
437
438 I := Head.ChildrenIterator;
439 try
440 while I.GetNext do
441 begin
442 if I.Current.TagName = 'meta' then
443 ParseMeta(I.Current) else
444 if I.Current.TagName = 'component' then
445 ParseComponent(I.Current) else
446 if I.Current.TagName = 'unit' then
447 ParseUnit(I.Current) else
448 WritelnWarning('X3D', Format('X3D XML: unrecognized element "%s" in <head>',
449 [I.Current.TagName]));
450 end;
451 finally FreeAndNil(I) end;
452 Result.Scale := Reader.LengthConversionFactor;
453 end;
454
455 procedure ParseStatement(Element: TDOMElement);
456
457 { You can safely assume that Element.TagName
458 indicates proto or externproto. }
459 procedure ParseProtoStatement;
460 var
461 Proto: TX3DPrototypeBase;
462 begin
463 if Element.TagName = 'ProtoDeclare' then
464 Proto := TX3DPrototype.Create else
465 Proto := TX3DExternalPrototype.Create;
466
467 Proto.PositionInParent := PositionInParent;
468
469 Result.AddPrototype(Proto);
470
471 Proto.ParseXML(Element, Reader);
472 end;
473
474 procedure ParseRouteStatement;
475 var
476 Route: TX3DRoute;
477 begin
478 Route := TX3DRoute.Create;
479 Route.PositionInParent := PositionInParent;
480 Result.AddRoute(Route);
481 Route.ParseXML(Element, Reader);
482 end;
483
484 procedure ParseImportStatement;
485 var
486 Import: TX3DImport;
487 begin
488 Import := TX3DImport.Create;
489 Import.PositionInParent := PositionInParent;
490 Result.AddImport(Import);
491 Import.ParseXML(Element, Reader);
492 end;
493
494 procedure ParseExportStatement;
495 var
496 ExportItem: TX3DExport;
497 begin
498 ExportItem := TX3DExport.Create;
499 ExportItem.PositionInParent := PositionInParent;
500 Result.AddExport(ExportItem);
501 ExportItem.ParseXML(Element, Reader);
502 end;
503
504 procedure ParseNodeStatement;
505 var
506 NewNode: TX3DNode;
507 ContainerFieldDummy: String;
508 begin
509 NewNode := ParseXMLNode(Element, ContainerFieldDummy, Reader, false);
510 NewNode.PositionInParent := PositionInParent;
511 Result.AddRootNode(NewNode, FileTopLevel);
512 end;
513
514 begin
515 if (Element.TagName = 'ProtoDeclare') or
516 (Element.TagName = 'ExternProtoDeclare') then
517 ParseProtoStatement else
518 if Element.TagName = 'ROUTE' then
519 ParseRouteStatement else
520 if Element.TagName = 'IMPORT' then
521 ParseImportStatement else
522 if Element.TagName = 'EXPORT' then
523 ParseExportStatement else
524 ParseNodeStatement;
525 end;
526
527 var
528 I: TXMLElementIterator;
529 begin
530 Result := CreateRootNode;
531 try
532 if FileTopLevel then
533 begin
534 ParseProfile;
535 ParseHead;
536 end;
537
538 I := Element.ChildrenIterator;
539 try
540 PositionInParent := 0;
541
542 while I.GetNext do
543 begin
544 ParseStatement(I.Current);
545 Inc(PositionInParent);
546 end;
547 finally FreeAndNil(I) end;
548 except FreeAndNil(Result); raise end;
549 end;
550
551 function LoadX3DXml(const Url: String; const Gzipped: boolean): TX3DRootNode;
552 var
553 Stream: TStream;
554 StreamOptions: TStreamOptions;
555 begin
556 StreamOptions := [];
557 if Gzipped then
558 Include(StreamOptions, soGzip);
559 Stream := Download(Url, StreamOptions);
560 try
561 Result := LoadX3DXmlInternal(Stream, AbsoluteURI(Url));
562 finally
563 FreeAndNil(Stream);
564 end;
565 end;
566
567 function LoadX3DXmlInternal(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
568 var
569 Doc: TXMLDocument;
570 begin
571 Doc := nil;
572 try
573 { The ReadXMLFile receives BaseUrl only to produce nice error messages
574 in case of errors. }
575 { ReadXMLFile always sets TXMLDocument param (possibly to nil),
576 even in case of exception. So place it inside try..finally. }
577 ReadXMLFile(Doc, Stream, AbsoluteURI(BaseUrl));
578 Result := LoadX3DXmlInternal(Doc.DocumentElement, BaseUrl);
579 finally FreeAndNil(Doc); end;
580 end;
581
582 function LoadX3DXmlInternal(const X3DElement: TDOMElement; const BaseUrl: String): TX3DRootNode; overload;
583 var
584 SceneElement: TDOMElement;
585 VersionStr: String;
586 Version: TX3DVersion;
587 { TODO: each USE must occur after it's DEF,
588 does X3D XML encoding guarantee this? }
589 Reader: TX3DReaderNames;
590 begin
591 Check(X3DElement.TagName = 'X3D', 'Root element of X3D file must be <X3D>');
592
593 { parse "version" attribute }
594 if X3DElement.AttributeString('version', VersionStr) then
595 begin
596 DeFormat(VersionStr, '%d.%d', [@Version.Major, @Version.Minor]);
597 if Version.Major < 3 then
598 begin
599 WritelnWarning('X3D', Format('X3D version number too low (%d.%d)', [Version.Major, Version.Minor]));
600 Version := X3DVersion; { some sensible version number }
601 end;
602 end else
603 begin
604 Version := X3DVersion; { some sensible version number }
605 WritelnWarning('X3D', Format('Missing X3D version number, assuming %d.%d', [Version.Major, Version.Minor]));
606 end;
607
608 SceneElement := X3DElement.ChildElement('Scene', true);
609
610 { X3D XML requires AutoRemove = true below }
611 Reader := TX3DReaderNames.Create(true, BaseUrl, Version);
612 try
613 Result := ParseStatements(SceneElement, true, X3DElement, Reader);
614 Reader.ExtractNames(Result.FPrototypeNames, Result.FExportedNames, Result.FImportedNames);
615 finally FreeAndNil(Reader) end;
616 end;
617
618 {$endif read_implementation}