Debian Codegraph @

src/files/castlecomponentserialize.pas

raw
1 {
2 Copyright 2018-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Reading and writing a hierachy of CGE components to/from files.
17 This is used by CGE editor to read/write components,
18 and it can be used at runtime by games to instantiate components designed
19 in the CGE editor.
20
21 Most code should use @link(UserInterfaceLoad),
22 @link(UserInterfaceSave), @link(TransformLoad), @link(TransformSave)
23 which are defined in other units, that rely on this unit for base
24 @link(ComponentLoad), @link(ComponentSave) implementation. }
25 unit CastleComponentSerialize;
26
27 {$I castleconf.inc}
28
29 interface
30
31 uses SysUtils, Classes, FpJson, FpJsonRtti, Generics.Collections, TypInfo,
32 CastleClassUtils;
33
34 type
35 EInvalidComponentFile = class(Exception);
36
37 { Save / load TComponent (or any descendant)
38 to a .castle-component, .castle-user-interface or .castle-transform file.
39
40 If you have a TCastleUserInterface or TCastleTransform then it is advised
41 to use instead stronger typed
42 @link(UserInterfaceSave), @link(UserInterfaceLoad),
43 @link(TransformSave), @link(TransformLoad). }
44 procedure ComponentSave(const C: TComponent; const Url: String);
45 function ComponentLoad(const Url: String; const Owner: TComponent): TComponent;
46
47 { Save / load TComponent (or descendant) to a string.
48 The string contents have the same format
49 as a .castle-component, .castle-user-interface or .castle-transform file. }
50 function ComponentToString(const C: TComponent): String;
51 function StringToComponent(const Contents: String; const Owner: TComponent): TComponent;
52
53 type
54 { Additional loading configuration for InternalStringToComponent.
55 @exclude }
56 TInternalComponentLoadInfo = class
57 { Allows viewports to preserve design-time camera/navigation across CGE editor undo. }
58 PreserveDataAcrossUndo: TComponent;
59 { If ChangeClassName is non-empty, at loading we change class of given component to this. }
60 ChangeClassName: String;
61 ChangeClassClass: TComponentClass;
62 end;
63
64 { Like StringToComponent but takes additional TInternalComponentLoadInfo
65 that adds some possibilities. LoadInfo may be @nil (making this equivalent
66 to just StringToComponent).
67 @exclude }
68 function InternalStringToComponent(const Contents: String;
69 const Owner: TComponent;
70 const LoadInfo: TInternalComponentLoadInfo): TComponent;
71
72 type
73 { Describes a component registered using @link(RegisterSerializableComponent),
74 enumerated using @link(RegisteredComponents) list. }
75 TRegisteredComponent = class
76 public
77 { Class of the component. Never leave this @nil. }
78 ComponentClass: TComponentClass;
79 { Nice caption to show user in the editor. }
80 Caption: array of String;
81 { Called by the editor always after creating this component. }
82 OnCreate: TNotifyEvent;
83 { Should correspond to whether class is declared as "deprecated" in Pascal
84 (we cannot get it using RTTI for now). }
85 IsDeprecated: Boolean;
86 end;
87 TRegisteredComponents = {$ifdef FPC}specialize{$endif} TObjectList<TRegisteredComponent>;
88
89 { Register a component that can be serialized and edited using CGE editor.
90
91 In case of the overloaded version that gets TRegisteredComponent instance,
92 the TRegisteredComponent instance becomes internally owned in this unit
93 (do not free it yourself). }
94 procedure RegisterSerializableComponent(const ComponentClass: TComponentClass;
95 const Caption: array of String); overload;
96 procedure RegisterSerializableComponent(const ComponentClass: TComponentClass;
97 const CaptionOnePart: String); overload;
98 procedure RegisterSerializableComponent(const C: TRegisteredComponent); overload;
99
100 { Read-only list of currently registered
101 (using @link(RegisterSerializableComponent)) components. }
102 function RegisteredComponents: TRegisteredComponents;
103
104 type
105 EComponentNotFound = class(Exception);
106
107 TComponentHelper = class helper for TComponent
108 { Find a child component that is owned by this component.
109 This is just like standard TComponent.FindComponent
110 (see https://www.freepascal.org/docs-html/rtl/classes/tcomponent.findcomponent.html )
111 but it makes an exception if component could not be found.
112 @raises EComponentNotFound If child component with given name could not be found.
113 }
114 function FindRequiredComponent(const AName: String): TComponent;
115 end;
116
117 { Load a serialized component (from a design file, like .castle-user-interface,
118 .castle-transform, .castle-component) and instantiate it multiple times.
119
120 Set @link(Url) or call @link(LoadFromStream) to load the design.
121
122 Then instantiate it (multiple times if needed)
123 using @link(ComponentLoad). }
124 TCastleComponentFactory = class(TCastleComponent)
125 strict private
126 FUrl, FTranslationGroupName: String;
127 JsonObject: TJsonObject;
128 procedure SetUrl(const Value: String);
129 private
130 function InternalComponentLoad(
131 const InstanceOwner: TComponent;
132 const AssociateReferences: TPersistent;
133 const LoadInfo: TInternalComponentLoadInfo): TComponent;
134 public
135 { Main constructor.
136 Does not load anything immediately.
137 Set @link(Url) or call @link(LoadFromStream) to load component. }
138 constructor Create(AOwner: TComponent); overload; override;
139
140 // Avoid Delphi warnings about constructor hiding.
141 // In the long-run, these deprecated constructors should be removed,
142 // once everyone got chance to migrate.
143 {$warnings off}
144 constructor Create(const AUrl: String); overload;
145 deprecated 'use Create(AOwner) overload, then set Url to load';
146 constructor Create(const Contents: TStream; const ATranslationGroupName: String); overload;
147 deprecated 'use Create(AOwner) overload, then LoadFromStream';
148 {$warnings on}
149
150 destructor Destroy; override;
151
152 { Load design from given URL.
153 Set to '' to clear the loaded component.
154
155 If you set up localization (see https://castle-engine.io/manual_text.php#section_localization_gettext ),
156 then upon loading, the design will be automatically localized using
157 the translation group derived from URL base name. E.g. loading
158 @code("castle-data:/foo/my_design.castle-user-interface") will use translation
159 group @code("my_design"). }
160 property Url: String read FUrl write SetUrl;
161
162 { Load design from given TStream.
163
164 If you set up localization (see https://castle-engine.io/manual_text.php#section_localization_gettext ),
165 then upon loading, the design will be automatically localized using
166 the translation group specified.
167 Just leave ATranslationGroupName = '' to not localize.
168
169 This @link(Url) value is unchanged by this. In most common case,
170 you don't really care about the @link(Url) value of this component,
171 if you load the contents from TStream. }
172 procedure LoadFromStream(const Contents: TStream; const ATranslationGroupName: String);
173
174 { Load given component as a template.
175 Effectively every TCastleComponentFactory.ComponentLoad
176 will create a deep clone of Template.
177
178 This is a way to clone ("deep copy") any TComponent using
179 serialization + deserialization underneath. Template is converted to
180 the JSON classes (though not JSON string)
181 and then deserialized back to a new component.
182 It is not the most efficient way to clone (since the intermeiate JSON
183 representation is created; though note that we don't save / parse
184 JSON as a string). But it is absolutely general and works out-of-the-box
185 on any TComponent, just like our serialization/deserialization. }
186 procedure LoadFromComponent(const Template: TComponent);
187
188 { Instantiate component.
189 Using this is similar to using global
190 @link(CastleComponentSerialize.ComponentLoad),
191 but it is much faster if you want to instantiate the same file many times.
192
193 Newly created component will be owned by InstanceOwner (it can be @nil,
194 in which case you have to free it manually).
195 Do not confuse this with the owner of this TCastleComponentFactory
196 -- which may be the same or different component.
197
198 If AssociateReferences is not @nil,
199 then published fields within AssociateReferences that match
200 the names of components within the loaded design will be set.
201
202 The @code(InstanceOwner) is useful for 2 things:
203
204 @orderedList(
205 @item(To manage memory (freeing the InstanceOwner will also free
206 the loaded component).)
207
208 @item(And to search for named components.
209 All the loaded components are owned by InstanceOwner
210 and you can query for them using @code(InstanceOwner.FindComponent)
211 or @code(InstanceOwner.FindRequiredComponent).
212
213 Note that loaded components are renamed,
214 if necessary, to be unique within InstanceOwner
215 --- this is important if your InstanceOwner owns other things as well.
216 If you want to reliably search for names, make sure to use
217 different InstanceOwner for each load. Or use @code(AssociateReferences)
218 instead.)
219 )
220
221 For example, this example creates an owner dedicated for refering to
222 names in the given instance of a Rock:
223
224 @longCode(#
225 procedure SpawnRock;
226 var
227 RockOwner: TComponent;
228 Rock: TCastleTransform;
229 RockRigidBody: TCastleRigidBody;
230 SceneToRotate: TCastleTransform;
231 begin
232 RockOwner := TComponent.Create(Self);
233 Rock := RockFactory.ComponentLoad(RockOwner) as TCastleTransform;
234 RockRigidBody := RockOwner.FindRequiredComponent('RockRigidBody') as TCastleRigidBody;
235 SceneToRotate := RockOwner.FindRequiredComponent('SceneToRotate') as TCastleTransform;
236 // here use RockRigidBody, SceneToRotate
237 end;
238 #)
239
240 The @code(AssociateReferences) is useful to connect, at load time,
241 the names of components within the loaded design to published fields
242 inside AssociateReferences.
243 Compared to using @code(InstanceOwner.FindComponent)
244 or @code(InstanceOwner.FindRequiredComponent) for the same purpose:
245
246 @unorderedList(
247 @item(It is simpler to use, because you don't need to manage
248 the InstanceOwner lifetime.
249
250 This matters in case you created InstanceOwner only for
251 the purpose of loading the given design.
252
253 The @code(AssociateReferences) instance can be freed immediately
254 after the load, and it will not affect the loaded components.
255 Or you can keep it existing for a longer time, and reuse
256 for loading all components -- it will not mess anything,
257 as loaded components are not renamed to be unique within it.
258 )
259
260 @item(
261 Associates the original component names, regardless of whether
262 they later required renaming to be unique within InstanceOwner.
263
264 This matters in case your InstanceOwner owns many other things.
265 )
266
267 @item(Note also one disadvantage of @code(AssociateReferences):
268 It doesn't change that field type matches.)
269 )
270
271 For example:
272
273 @longCode(#
274 type
275 TRockDesign = class(TPersistent)
276 published
277 SceneToRotate: TCastleTransform;
278 RockRigidBody: TCastleRigidBody;
279 end;
280
281 procedure SpawnRock;
282 var
283 Rock: TCastleTransform;
284 RockDesign: TRockDesign;
285 begin
286 RockDesign := TRockDesign.Create;
287 try
288 Rock := RockFactory.ComponentLoad(Self, RockDesign) as TCastleTransform;
289 // here use RockDesign.RockRigidBody, RockDesign.SceneToRotate
290 finally FreeAndNil(RockDesign) end;
291 end;
292 #) }
293 function ComponentLoad(const InstanceOwner: TComponent;
294 const AssociateReferences: TPersistent = nil): TComponent;
295 end;
296
297 TSerializedComponent = TCastleComponentFactory deprecated 'use TCastleComponentFactory';
298
299 { Internal, used by TranslateAllDesigns. @exclude }
300 TInternalTranslateDesignCallback = procedure (const C: TComponent; const GroupName: String);
301
302 var
303 { Internal, used by TranslateAllDesigns.
304 @exclude }
305 OnInternalTranslateDesign: TInternalTranslateDesignCallback;
306
307 var
308 { Non-empty only in custom editor builds.
309 Indicates project name corresponding to this editor.
310 Set by custom editor template (used when project defines editor_units).
311 @exclude }
312 InternalCustomComponentsForProject: String;
313
314 { Are we inside ComponentLoad.
315 Prefer to instead look at component property TCastleComponent.IsLoading,
316 this variable is really only a hack for exceptional situations.
317 @exclude }
318 InternalLoadingComponent: Cardinal;
319
320 { Copy the properties of Source to Destination using the serialization to JSON.
321 This has a nice advantage that you don't need to implement field-by-field
322 assignment manually (e.g. overriding TPersistent.Assign).
323
324 It has however problems:
325
326 - It works correctly only when Destination is in completely default state
327 (right after constructor).
328 Or, at least, the properties of Source that are in default state
329 are also already in default state in Destination.
330 That's because these properties are not serialized, and thus will not be modified
331 in Destination.
332
333 - It's inefficient, doing serializing + deserializing.
334 While this doesn't actually serialize JSON to string,
335 it only uses in-memory JSON classes,
336 still there's a lot of unnecessary creation of temporary structures and copying
337 compared to traditional approach of overriding TPersistent.Assign.
338
339 For these 2 reasons, this remains an internal "hack",
340 and not something we advise you to use.
341 @exclude
342 }
343 procedure InternalAssignUsingSerialization(const Destination, Source: TComponent);
344
345 { Create a clone ("deep copy") of given component.
346 Works out-of-the-box on any TComponent,
347 just like our serialization / deserialization system, copying the "published"
348 members of the component.
349
350 Copies the given component, as well as anything that our serialization
351 system considers to be contained within it. Like TCastleTransform children,
352 TCastleTransform behaviors, TCastleUserInterface children, non-visual components
353 in @link(TCastleComponent.NonVisualComponents).
354
355 The new component hierarchy will have all new components owned by
356 the NewComponentOwner.
357
358 This is similar to TCastleFactoryComponent.LoadFromComponent
359 followed by the TCastleFactoryComponent.ComponentLoad, but it is easier
360 to use if you only want to create a single clone of the component.
361 If you want to create multiple clones, better use TCastleFactoryComponent,
362 as then you can call TCastleFactoryComponent.LoadFromComponent once,
363 and call TCastleFactoryComponent.ComponentLoad multiple times -- this will
364 be more efficient. Like this:
365
366 @longCode(#
367 // unoptimal
368 NewComponent1 := ComponentClone(Template, NewComponentOwner);
369 NewComponent2 := ComponentClone(Template, NewComponentOwner);
370 NewComponent3 := ComponentClone(Template, NewComponentOwner);
371
372 // equivalent, but more efficient
373 Factory := TCastleFactoryComponent.Create(nil);
374 try
375 Factory.LoadFromComponent(Template);
376 NewComponent1 := Factory.ComponentLoad(NewComponentOwner);
377 NewComponent2 := Factory.ComponentLoad(NewComponentOwner);
378 NewComponent3 := Factory.ComponentLoad(NewComponentOwner);
379 finally FreeAndNil(Factory) end;
380 #)
381
382 This is a way to clone ("deep copy") any TComponent using
383 serialization + deserialization underneath. Template is converted to
384 the JSON classes (though not JSON string)
385 and then deserialized back to a new component.
386 It is not the most efficient way to clone (since the intermeiate JSON
387 representation is created; though note that we don't save / parse
388 JSON as a string). But it is absolutely general and works out-of-the-box
389 on any TComponent. }
390 function ComponentClone(const C: TComponent; const NewComponentOwner: TComponent): TComponent;
391
392 implementation
393
394 uses JsonParser, RtlConsts, StrUtils,
395 CastleFilesUtils, CastleUtils, CastleLog, CastleStringUtils,
396 CastleUriUtils, CastleVectors, CastleColors, CastleInternalRttiUtils,
397 CastleDownload;
398
399 function ComponentToJson(const C: TComponent): TJsonObject; forward;
400
401 { component registration ----------------------------------------------------- }
402
403 var
404 FRegisteredComponents: TRegisteredComponents;
405
406 function RegisteredComponents: TRegisteredComponents;
407 begin
408 if FRegisteredComponents = nil then
409 FRegisteredComponents := TRegisteredComponents.Create(true);
410 Result := FRegisteredComponents;
411 end;
412
413 procedure RegisterSerializableComponent(const ComponentClass: TComponentClass;
414 const Caption: array of String);
415 var
416 R: TRegisteredComponent;
417 I: Integer;
418 begin
419 R := TRegisteredComponent.Create;
420 R.ComponentClass := ComponentClass;
421 SetLength(R.Caption, High(Caption) + 1);
422 for I := 0 to High(Caption) do
423 R.Caption[I] := Caption[I];
424 RegisteredComponents.Add(R);
425 end;
426
427 procedure RegisterSerializableComponent(const ComponentClass: TComponentClass;
428 const CaptionOnePart: String);
429 var
430 R: TRegisteredComponent;
431 begin
432 R := TRegisteredComponent.Create;
433 R.ComponentClass := ComponentClass;
434 R.Caption := [CaptionOnePart];
435 RegisteredComponents.Add(R);
436 end;
437
438 procedure RegisterSerializableComponent(const C: TRegisteredComponent);
439
440 function InsertSpacesBeforeUpperLetters(const S: String): String;
441 var
442 StrBuild: TStringBuilder;
443 I: Integer;
444 begin
445 StrBuild := TStringBuilder.Create;
446 try
447 for I := 1 to Length(S) do
448 begin
449 if (I > 1) and (S[I] in ['A'..'Z']) then
450 StrBuild.Append(' ');
451 StrBuild.Append(S[I]);
452 end;
453 Result := StrBuild.ToString;
454 finally FreeAndNil(StrBuild) end;
455 end;
456
457 var
458 GuessedCaption: String;
459 begin
460 if C.ComponentClass = nil then
461 raise Exception.Create('RegisterSerializableComponent: ComponentClass not assigned');
462
463 if (Length(C.Caption) = 0) or (C.Caption[0] = '') then
464 begin
465 GuessedCaption := InsertSpacesBeforeUpperLetters(
466 PrefixRemove('Castle', PrefixRemove('T', C.ComponentClass.ClassName, true), true));
467 C.Caption := [GuessedCaption];
468 WritelnWarning('RegisterSerializableComponent: component Caption at registration cannot be empty, setting a placeholder "%s"', [
469 GuessedCaption
470 ]);
471 end;
472
473 RegisteredComponents.Add(C);
474 end;
475
476 function FindComponentClass(const AClassName: string): TComponentClass;
477 var
478 R: TRegisteredComponent;
479 begin
480 for R in RegisteredComponents do
481 if R.ComponentClass.ClassName = AClassName then
482 Exit(R.ComponentClass);
483 WritelnWarning('Cannot find component class "' + AClassName + '", (de)serialization of it will fail');
484 Result := nil;
485 end;
486
487 { loading from JSON ---------------------------------------------------------- }
488
489 type
490 TCastleJsonReader = class
491 private
492 type
493 TMyJsonDeStreamer = class(TJsonDeStreamer)
494 private
495 Reader: TCastleJsonReader;
496 end;
497 var
498 ComponentNames: TStringList;
499 { Events called by FJsonDeStreamer }
500 procedure GetObject(AObject: TObject; Info: PPropInfo;
501 AData: TJsonObject; DataName: TJsonStringType; var AValue: TObject);
502 strict private
503 type
504 TResolveObjectProperty = class
505 Instance: TObject;
506 InstanceProperty: PPropInfo;
507 PropertyValue: String;
508 end;
509 TResolveObjectPropertyList = {$ifdef FPC}specialize{$endif} TObjectList<TResolveObjectProperty>;
510
511 { Handle reading custom things during TCastleComponent.CustomSerialization. }
512 TSerializationProcessReader = class(TSerializationProcess)
513 public
514 Reader: TCastleJsonReader;
515 CurrentlyReading: TJsonObject;
516 procedure ReadWriteInteger(const Key: String; var Value: Integer; const IsStored: Boolean);
517 overload; override;
518 procedure ReadWriteBoolean(const Key: String; var Value: Boolean; const IsStored: Boolean);
519 overload; override;
520 procedure ReadWriteString(const Key: String; var Value: String; const IsStored: Boolean);
521 overload; override;
522 procedure ReadWriteSingle(const Key: String; var Value: Single; const IsStored: Boolean);
523 overload; override;
524 procedure ReadWriteSubComponent(const Key: String; const Value: TComponent;
525 const IsStored: Boolean); override;
526 procedure ReadWriteList(const Key: String;
527 const ListEnumerate: TSerializationProcess.TListEnumerateEvent; const ListAdd: TSerializationProcess.TListAddEvent;
528 const ListClear: TSerializationProcess.TListClearEvent); override;
529 end;
530 TSerializationProcessReaderList = {$ifdef FPC}specialize{$endif} TObjectList<TSerializationProcessReader>;
531
532 var
533 FDeStreamer: TMyJsonDeStreamer;
534 ResolveObjectProperties: TResolveObjectPropertyList;
535 SerializationProcessPool: TSerializationProcessReaderList;
536 SerializationProcessPoolUsed: Integer;
537
538 { Find component name in ComponentNames.
539
540 Note: Do not use Owner.FindComponent(FindName) to resolve names
541 during deserialization.
542 Reason: Owner may already have some existing
543 components before new ones have been deserialized into it
544 (e.g. if duplicating viewport+camera into an existing
545 design) with conflicting names. We do not want to link to these
546 existing components.
547
548 See TTestCastleComponentSerialize.TestPastePreserveReferences
549 for testcase why this is important. Thanks to ComponentNames
550 e.g. copy-paste (in editor) of viewport + camera into
551 the same design works correctly.
552
553 Note that having ComponentNames with fallback on Owner.FindComponent
554 would also be bad: since the name reference may be found in design
555 before the object is defined, e.g. viewport with
556 propery "Camera": "Camera1" may be specified before Camera1 is defined.
557 We should then wait for Camera1 (not reuse unrelated Camera1 from existing
558 Owner).
559 So instead, FindComponentName looks *only* in ComponentNames. }
560 function FindComponentName(const FindName: String): TComponent;
561
562 { Events called by DeStreamer }
563 procedure BeforeReadObject(Sender: TObject; AObject: TObject; Json: TJsonObject);
564 procedure AfterReadObject(Sender: TObject; AObject: TObject; Json: TJsonObject);
565 procedure RestoreProperty(Sender: TObject; AObject: TObject; Info: PPropInfo; AValue: TJsonData; var Handled: Boolean);
566 private
567 LoadInfo: TInternalComponentLoadInfo;
568 FOwner: TComponent;
569 (*Resolve hanging references, when JSON referred to some component name
570 before this component was actually defined.
571 Like when Viewport references a camera in Viewport.Camera,
572 but the camera is only defined later while reading Viewport.Items,
573 like
574
575 "Camera": "Camera1",
576 "Items" {
577 ...
578 {
579 Name: "Camera1",
580 }
581 }
582 *)
583 procedure FinishResolvingComponentProperties;
584
585 { Like FinishResolvingComponentProperties, but only resolves references to C,
586 so it is much faster, and doesn't warn about other references remaining
587 unsolved. }
588 procedure ResolveComponentReferences(const C: TComponent);
589 public
590 constructor Create;
591 destructor Destroy; override;
592
593 function DeStreamer: TJsonDeStreamer;
594 { Will own all deserialized components. }
595 property Owner: TComponent read FOwner;
596 end;
597
598 { Read and create suitable component class from JSON. }
599 function CreateComponentFromJson(const JsonObject: TJsonObject;
600 const Owner: TComponent;
601 const LoadInfo: TInternalComponentLoadInfo): TComponent;
602 var
603 ResultClassName: String;
604 ResultClass: TComponentClass;
605 begin
606 if Owner = nil then
607 raise Exception.Create('You must provide non-nil Owner when deserializing a component. Without an Owner, it is not possible to free the component hierarchy easily, and you will most likely have memory leaks.');
608
609 if (LoadInfo <> nil) and
610 (LoadInfo.ChangeClassName <> '') and // early exit in the usual case
611 (LoadInfo.ChangeClassName = JsonObject.Strings['Name']) then
612 begin
613 ResultClass := LoadInfo.ChangeClassClass;
614 end else
615 begin
616 if JsonObject.Find('$$ClassName') <> nil then
617 ResultClassName := JsonObject.Strings['$$ClassName']
618 else
619 if JsonObject.Find('$ClassName') <> nil then
620 ResultClassName := JsonObject.Strings['$ClassName'] // handle older format
621 else
622 ResultClassName := JsonObject.Strings['_ClassName']; // handle older format
623
624 { Initially we did here
625 JsonObject.Delete('_ClassName');
626 to not confuse TJsonDeStreamer with extra _ClassName property.
627 But later: it is better to leave JSON structure unmodified
628 (allows to read it multiple times, if needed). }
629
630 ResultClass := FindComponentClass(ResultClassName);
631 end;
632
633 if ResultClass = nil then
634 raise EInvalidComponentFile.CreateFmt('Component JSON file references an unrecognized class "%s".' + NL + NL +
635 Iff(CastleDesignMode,
636 'As you see this in the editor: the most likely cause is that this project uses custom components, and you did not make a custom editor build. Use the menu item "Project -> Restart Editor (With Custom Components)" to build and run correct editor.',
637 'Add the unit that registers "%s" to the "uses" clause of any unit in the application. E.g. add "CastleTiledMap" to some uses clause, if you use "TCastleTiledMap" in the design.'),
638 [ResultClassName, ResultClassName]);
639 Result := ResultClass.Create(Owner);
640 end;
641
642 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteInteger(
643 const Key: String; var Value: Integer; const IsStored: Boolean);
644 var
645 JsonData: TJsonData;
646 begin
647 JsonData := CurrentlyReading.Find(Key) as TJsonData;
648 if JsonData <> nil then
649 Value := JsonData.AsInteger;
650 end;
651
652 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteBoolean(
653 const Key: String; var Value: Boolean; const IsStored: Boolean);
654 var
655 JsonData: TJsonData;
656 begin
657 JsonData := CurrentlyReading.Find(Key) as TJsonData;
658 if JsonData <> nil then
659 Value := JsonData.AsBoolean;
660 end;
661
662 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteString(
663 const Key: String; var Value: String; const IsStored: Boolean);
664 var
665 JsonData: TJsonData;
666 begin
667 JsonData := CurrentlyReading.Find(Key) as TJsonData;
668 if JsonData <> nil then
669 Value := JsonData.AsString;
670 end;
671
672 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteSingle(
673 const Key: String; var Value: Single; const IsStored: Boolean);
674 var
675 JsonData: TJsonData;
676 begin
677 JsonData := CurrentlyReading.Find(Key) as TJsonData;
678 if JsonData <> nil then
679 Value := JsonData.AsFloat;
680 end;
681
682 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteSubComponent(
683 const Key: String; const Value: TComponent; const IsStored: Boolean);
684 var
685 JsonData: TJsonData;
686 begin
687 Assert(Value <> nil);
688 JsonData := CurrentlyReading.Find(Key) as TJsonData;
689 if (JsonData <> nil) and (JsonData.JsonType = jtObject) then
690 Reader.FDeStreamer.JsonToObject(JsonData as TJsonObject, Value);
691 end;
692
693 procedure TCastleJsonReader.TSerializationProcessReader.ReadWriteList(const Key: String;
694 const ListEnumerate: TSerializationProcess.TListEnumerateEvent; const ListAdd: TSerializationProcess.TListAddEvent;
695 const ListClear: TSerializationProcess.TListClearEvent);
696 var
697 JsonChildren: TJsonArray;
698 JsonChild: TJsonObject;
699 I: Integer;
700 Child: TComponent;
701 begin
702 ListClear;
703 JsonChildren := CurrentlyReading.Find('$' + Key, jtArray) as TJsonArray;
704
705 { backward compatibily for reading old children in JSON }
706 if (Key = 'Children') and (JsonChildren = nil) then
707 JsonChildren := CurrentlyReading.Find('_Children', jtArray) as TJsonArray;
708
709 if JsonChildren <> nil then
710 begin
711 for I := 0 to JsonChildren.Count - 1 do
712 begin
713 JsonChild := JsonChildren.Objects[I];
714 if JsonChild = nil then
715 raise EInvalidComponentFile.Create('$' + Key + ' must be an array of JSON objects');
716 Child := CreateComponentFromJson(JsonChild, Reader.Owner, Reader.LoadInfo);
717 Reader.DeStreamer.JsonToObject(JsonChild, Child);
718 ListAdd(Child);
719 end;
720 end;
721 end;
722
723 procedure TCastleJsonReader.BeforeReadObject(
724 Sender: TObject; AObject: TObject; Json: TJsonObject);
725 var
726 C: TCastleComponent;
727 begin
728 if AObject is TCastleComponent then
729 begin
730 C := TCastleComponent(AObject);
731 C.InternalLoading; // set C.IsLoading := true, (FPC only) add csLoading flag to ComponentState
732 end;
733 end;
734
735 procedure TCastleJsonReader.AfterReadObject(
736 Sender: TObject; AObject: TObject; Json: TJsonObject);
737
738 { Because of our TCastleJsonReader.RestoreProperty changing
739 Name to be unique, we may have desynchronized Name with InternalText.
740 Synchronize it again. }
741 procedure SynchronizeNameWithInternalText(const C: TCastleComponent);
742 begin
743 if (C.InternalOriginalName <> '') and
744 (C.InternalOriginalName = C.InternalText) then
745 C.InternalText := C.Name;
746 end;
747
748 { Call C.CustomSerialization(SerializationProcess) }
749 procedure CustomSerializationWithSerializationProcess(const C: TCastleComponent;
750 const SerializationProcess: TSerializationProcessReader);
751 begin
752 SerializationProcess.CurrentlyReading := Json;
753 SerializationProcess.Reader := Self;
754 if LoadInfo <> nil then
755 SerializationProcess.InternalPreserveDataAcrossUndo := LoadInfo.PreserveDataAcrossUndo
756 else
757 SerializationProcess.InternalPreserveDataAcrossUndo := nil;
758 C.CustomSerialization(SerializationProcess);
759 end;
760
761 { Call C.CustomSerialization }
762 procedure CustomSerialization(const C: TCastleComponent);
763 var
764 SerializationProcess: TSerializationProcessReader;
765 begin
766 if SerializationProcessPoolUsed < SerializationProcessPool.Count then
767 // faster: use ready SerializationProcess from pool
768 SerializationProcess := SerializationProcessPool[SerializationProcessPoolUsed]
769 else
770 begin
771 // slower: create new SerializationProcess,
772 // and add it to pool for future use from the same reader
773 SerializationProcess := TSerializationProcessReader.Create;
774 SerializationProcessPool.Add(SerializationProcess);
775 end;
776 Assert(SerializationProcessPoolUsed < SerializationProcessPool.Count);
777
778 Inc(SerializationProcessPoolUsed);
779 try
780 CustomSerializationWithSerializationProcess(C, SerializationProcess);
781 finally Dec(SerializationProcessPoolUsed) end;
782 end;
783
784 var
785 C: TCastleComponent;
786 begin
787 if AObject is TCastleComponent then
788 begin
789 C := TCastleComponent(AObject);
790 SynchronizeNameWithInternalText(C);
791 CustomSerialization(C);
792 C.InternalLoaded; // set IsLoading = false, (FPC only) remove csLoading flag from ComponentState, calls Loaded virtual method
793 end;
794
795 if AObject is TComponent then
796 { Resolve references to this object, as soon as this object is read
797 (without waiting for final FinishResolvingComponentProperties).
798
799 This is necessary for TCastleViewport.Loaded to function correctly,
800 it assumes that Camera inside has the same owner as Viewport,
801 which means that it is not a "dummy" instance created by FpRttiJson
802 when property was nil. }
803 ResolveComponentReferences(TComponent(AObject));
804 end;
805
806 function TCastleJsonReader.FindComponentName(const FindName: String): TComponent;
807 var
808 NameIndex: Integer;
809 begin
810 NameIndex := ComponentNames.IndexOf(FindName);
811 if NameIndex <> -1 then
812 begin
813 Result := ComponentNames.Objects[NameIndex] as TComponent;
814 Assert(Result <> nil); // all object on this list should be non-nil
815 Exit;
816 end;
817
818 Result := nil;
819 end;
820
821 procedure TCastleJsonReader.RestoreProperty(Sender: TObject; AObject: TObject;
822 Info: PPropInfo; AValue: TJsonData; var Handled: Boolean);
823
824 function RenameUniquely(const Owner: TComponent; const NewName: String): String;
825 var
826 NameWithoutNumber: String;
827 Number: Int64;
828 P: Integer;
829 begin
830 // calculate P (position of last digit)
831 P := Length(NewName) + 1;
832 while (P > 1) and CharInSet(NewName[P - 1], ['0'..'9']) do
833 Dec(P);
834
835 // calculate NameWithoutNumber, Number
836 NameWithoutNumber := Copy(NewName, 1, P - 1);
837 try
838 if P <= Length(NewName) then
839 Number := StrToInt(SEnding(NewName, P))
840 else
841 Number := 0;
842 except
843 on EConvertError do
844 begin
845 // StrToInt can fail e.g. if you supply 'Blah99999999999999999999999999'.
846 NameWithoutNumber := NewName;
847 Number := 0;
848 end;
849 end;
850
851 repeat
852 Inc(Number);
853 Result := NameWithoutNumber + IntToStr(Number);
854 { Using Owner.FindComponent, not FindComponentName:
855 because we rename based on what exists in Owner, not ComponentNames. }
856 until Owner.FindComponent(Result) = nil;
857 end;
858
859 var
860 TI: PTypeInfo;
861 NewName: TJsonStringType;
862 begin
863 TI := Info^.PropType{$ifndef FPC}^{$endif};
864 if (TI^.Kind in [{$ifdef FPC} tkSString, tkLString, tkAString {$else} tkUString {$endif}]) and
865 (Info^.Name = 'Name') then
866 begin
867 { We handle setting Name ourselves, this way we can change the Name
868 to avoid conflicts. This way we can safely add new components into
869 existing hierarchy (with some names already reserved in Owner).
870 This way:
871
872 - We can make Copy+Paste in CGE editor, by just pasting the components
873 into existing owner.
874
875 - In general, code can safely instantiate designs,
876 without worrying that owner may have some names already reserved
877 (which would otherwise cause exception when trying to add new children
878 with the same name).
879
880 - Even invalid old designs can be read: in old designs, you could have
881 multiple camera components named 'Camera'. This was not a problem,
882 as camera was a subcomponent owned by each viewport.
883 In new designs, these cameras are all owned by a single DesignOwner,
884 Thanks to this mechanism, these cameras will be renamed as necessary,
885 to not conflict. (While TCastleViewport.Loaded also does renaming,
886 but only in CastleDesignMode; if you load old design at runtime,
887 then the mechanism below kicks-in.)
888 }
889 NewName := AValue.AsString;
890 ComponentNames.AddObject(NewName, AObject);
891
892 { Using Owner.FindComponent, not FindComponentName:
893 because we rename based on what exists in Owner, not ComponentNames. }
894 if Owner.FindComponent(NewName) <> nil then
895 begin
896 if AObject is TCastleComponent then
897 TCastleComponent(AObject).InternalOriginalName := NewName;
898 NewName := RenameUniquely(Owner, NewName);
899 end;
900
901 SetStrProp(AObject, Info, NewName);
902 Handled := true;
903 end;
904 end;
905
906 procedure TCastleJsonReader.GetObject(AObject: TObject; Info: PPropInfo;
907 AData: TJsonObject; DataName: TJsonStringType; var AValue: TObject);
908 var
909 R: TResolveObjectProperty;
910 ValueClass: TClass;
911 begin
912 if (DataName = '') and (Info <> nil) then
913 begin
914 (*This happens when JSON wants to set object property that is currently nil,
915 but it has some content in JSON.
916 In theory it should not happen -- such properties should be a non-nil
917 subcomponent. But in practice it is possible for backward-compatibility.
918 This is possible in old designs:
919
920 "Camera": { Name: "Camera1", ... }
921
922 The default implementation in TJSONDeStreamer.GetObject
923 does *almost* what we want... except the owner is then wrong
924 (it creates new object, with owner from containing object).
925 *)
926
927 ValueClass := GetTypeData(Info^.PropType {$ifndef FPC}^{$endif})^.ClassType;
928 if ValueClass.InheritsFrom(TComponent) then
929 AValue := TComponentClass(ValueClass).Create(Owner);
930 end;
931
932 if (DataName <> '') and (Info <> nil) then
933 begin
934 { This happens when JSON wants to set object property using a name
935 of some existing instance. Like
936 "Camera": "Camera1"
937 }
938 AValue := FindComponentName(DataName);
939
940 if AValue = nil then
941 begin
942 { In this case TJsonDeStreamer.GetObject will create a new instance,
943 that is useless (we will want to throw it away later),
944 but we cannot avoid this creation in TJsonDeStreamer.GetObject.
945
946 But at least rememeber to finalize this property later. }
947
948 R := TResolveObjectProperty.Create;
949 R.Instance := AObject;
950 R.InstanceProperty := Info;
951 R.PropertyValue := DataName;
952 ResolveObjectProperties.Add(R);
953 // This is too verbose (and alarming) for normal user. Everything is OK when you see this log.
954 // WritelnLog('Delaying resolving of component name "%s" (we will create a new empty instance, and resolve it at the end of loading)', [
955 // DataName
956 // ]);
957 end;
958 end;
959 end;
960
961 procedure TCastleJsonReader.ResolveComponentReferences(const C: TComponent);
962 var
963 R: TResolveObjectProperty;
964 OldPropertyValue: TObject;
965 I: Integer;
966 begin
967 if C.Name = '' then Exit; // nothing to resolve for unnamed component
968
969 for I := ResolveObjectProperties.Count - 1 downto 0 do
970 begin
971 R := ResolveObjectProperties[I];
972 if R.PropertyValue = C.Name then
973 begin
974 // free previous property value, in the safest way possible
975 OldPropertyValue := GetObjectProp(R.Instance, R.InstanceProperty);
976 SetObjectProp(R.Instance, R.InstanceProperty, nil);
977 FreeAndNil(OldPropertyValue);
978
979 // set new property value
980 SetObjectProp(R.Instance, R.InstanceProperty, C);
981
982 ResolveObjectProperties.Delete(I);
983 end;
984 end;
985 end;
986
987 procedure TCastleJsonReader.FinishResolvingComponentProperties;
988 var
989 R: TResolveObjectProperty;
990 PropertyValueAsObject, OldPropertyValue: TObject;
991 begin
992 for R in ResolveObjectProperties do
993 begin
994 PropertyValueAsObject := FindComponentName(R.PropertyValue);
995 { As a fallback, try to resolve using Owner, in case serialized
996 hierarchy references components that were not serialized,
997 but exist in Owner.
998 See TTestCastleComponentSerialize.TestPastePreserveReferencesOutsideCopied
999 for example. }
1000 if PropertyValueAsObject = nil then
1001 PropertyValueAsObject := Owner.FindComponent(R.PropertyValue);
1002 if PropertyValueAsObject = nil then
1003 begin
1004 { In case we cannot resolve the component name, it is better to set
1005 the property to nil than to leave the empty (unnamed) placeholder
1006 instance created by FpJson.
1007 That is because having an unnamed component would cause further troubles:
1008 - If you save it again, we will save a component with name='' and a reference
1009 to it using empty name.
1010 - Opening it, we could not resolve the empty name (because empty name never
1011 matches in FindComponent) and we would create a new empty component...
1012
1013 This is actually possible:
1014 - Save with "Save Selected" a subset of hierarchy that doesn't include
1015 some referenced component.
1016 For example, make TCastleViewport.Camera reference a TCastleCamera instance
1017 defined *outside of this TCastleViewport* (on another viewport) called
1018 'CameraOutside'.
1019 - Saving it with "Save Selected" for now just makes a design with broken link.
1020 The Camera="CameraOutside" reference in viewport cannot be resolved.
1021 If we convert it to nil on load, that's just a warning and we can continue OK.
1022 - If we leave the TCastleCamera placeholder instance, next save of this will save
1023 to JSON TCastleCamera with Name='', and Camera="" reference in viewport.
1024 - On load, we will fail to resolve Camera="".
1025 Saving and loading will create more and more unnamed TCastleCamera instances...
1026 }
1027 WritelnWarning('Cannot resolve component name "%s", it will be set to nil', [
1028 R.PropertyValue
1029 ]);
1030 end;
1031
1032 // free previous property value, in the safest way possible
1033 OldPropertyValue := GetObjectProp(R.Instance, R.InstanceProperty);
1034 SetObjectProp(R.Instance, R.InstanceProperty, nil);
1035 FreeAndNil(OldPropertyValue);
1036
1037 // set new property value
1038 SetObjectProp(R.Instance, R.InstanceProperty, PropertyValueAsObject);
1039 end;
1040
1041 ResolveObjectProperties.Clear;
1042 end;
1043
1044 { This is a global routine because TJsonDeStreamer.OnGetObject requires global.
1045 We just call Reader.GetObject method. }
1046 procedure ReaderGetObject(Sender: TObject; AObject: TObject; Info: PPropInfo;
1047 AData: TJsonObject; DataName: TJsonStringType; var AValue: TObject);
1048 var
1049 SenderDeStreamer: TCastleJsonReader.TMyJsonDeStreamer;
1050 begin
1051 SenderDeStreamer := Sender as TCastleJsonReader.TMyJsonDeStreamer;
1052 SenderDeStreamer.Reader.GetObject(AObject, Info, AData, DataName, AValue);
1053 end;
1054
1055 constructor TCastleJsonReader.Create;
1056 begin
1057 inherited;
1058
1059 { Do this early, so that destructor can just rely that it was for sure done,
1060 even if there's exception from constructor. }
1061 Inc(InternalLoadingComponent);
1062
1063 FDeStreamer := TMyJsonDeStreamer.Create(nil);
1064 FDeStreamer.Reader := Self;
1065 FDeStreamer.BeforeReadObject := {$ifdef FPC}@{$endif}BeforeReadObject;
1066 FDeStreamer.AfterReadObject := {$ifdef FPC}@{$endif}AfterReadObject;
1067 FDeStreamer.OnRestoreProperty := {$ifdef FPC}@{$endif}RestoreProperty;
1068 FDeStreamer.OnGetObject := {$ifdef FPC}@{$endif}ReaderGetObject;
1069 // read property like Url (TCastleScene.Url) from URL
1070 FDeStreamer.Options := FDeStreamer.Options + [jdoCaseInsensitive];
1071
1072 ResolveObjectProperties := TResolveObjectPropertyList.Create(true);
1073
1074 SerializationProcessPool := TSerializationProcessReaderList.Create(true);
1075
1076 ComponentNames := TStringList.Create;
1077 ComponentNames.CaseSensitive := false;
1078 ComponentNames.Duplicates := dupError;
1079 end;
1080
1081 destructor TCastleJsonReader.Destroy;
1082 begin
1083 FreeAndNil(ResolveObjectProperties);
1084 FreeAndNil(FDeStreamer);
1085 FreeAndNil(SerializationProcessPool);
1086 FreeAndNil(ComponentNames);
1087 Dec(InternalLoadingComponent);
1088 inherited;
1089 end;
1090
1091 function TCastleJsonReader.DeStreamer: TJsonDeStreamer;
1092 begin
1093 Result := FDeStreamer;
1094 end;
1095
1096 { TCastleComponentFactory ------------------------------------------------------- }
1097
1098 constructor TCastleComponentFactory.Create(AOwner: TComponent);
1099 begin
1100 inherited;
1101 end;
1102
1103 constructor TCastleComponentFactory.Create(const AUrl: String);
1104 begin
1105 Create(nil);
1106 Url := AUrl;
1107 end;
1108
1109 constructor TCastleComponentFactory.Create(const Contents: TStream;
1110 const ATranslationGroupName: String);
1111 begin
1112 Create(nil);
1113 LoadFromStream(Contents, ATranslationGroupName);
1114 end;
1115
1116 destructor TCastleComponentFactory.Destroy;
1117 begin
1118 FreeAndNil(JsonObject);
1119 inherited;
1120 end;
1121
1122 procedure TCastleComponentFactory.SetUrl(const Value: String);
1123 var
1124 Contents: TStream;
1125 begin
1126 if FUrl <> Value then
1127 begin
1128 FUrl := Value;
1129
1130 // free previously loaded, if any
1131 FreeAndNil(JsonObject);
1132 FTranslationGroupName := '';
1133
1134 // load new, if set
1135 if Value <> '' then
1136 begin
1137 Contents := Download(Value);
1138 try
1139 LoadFromStream(Contents, DeleteURIExt(ExtractURIName(Value)));
1140 finally FreeAndNil(Contents) end;
1141 end;
1142 end;
1143 end;
1144
1145 procedure TCastleComponentFactory.LoadFromStream(const Contents: TStream;
1146 const ATranslationGroupName: String);
1147 var
1148 JsonData: TJsonData;
1149 begin
1150 FTranslationGroupName := ATranslationGroupName;
1151
1152 JsonData := GetJson(Contents, true);
1153 if not (JsonData is TJsonObject) then
1154 raise EInvalidComponentFile.Create('Component JSON file should contain an object');
1155 JsonObject := JsonData as TJsonObject;
1156 end;
1157
1158 procedure TCastleComponentFactory.LoadFromComponent(const Template: TComponent);
1159 begin
1160 FTranslationGroupName := ''; // set it, like other LoadFrom* methods do
1161 JsonObject := ComponentToJson(Template);
1162 end;
1163
1164 function TCastleComponentFactory.ComponentLoad(const InstanceOwner: TComponent;
1165 const AssociateReferences: TPersistent): TComponent;
1166 begin
1167 Result := InternalComponentLoad(InstanceOwner, AssociateReferences, nil);
1168 end;
1169
1170 function TCastleComponentFactory.InternalComponentLoad(
1171 const InstanceOwner: TComponent;
1172 const AssociateReferences: TPersistent;
1173 const LoadInfo: TInternalComponentLoadInfo): TComponent;
1174
1175 { Set AssociateReferences fields matching component names in ComponentNames. }
1176 procedure MakeAssociateReferences(const ComponentNames: TStringList);
1177 var
1178 I: Integer;
1179 FieldAddr: ^TComponent;
1180 begin
1181 for I := 0 to ComponentNames.Count - 1 do
1182 begin
1183 FieldAddr := AssociateReferences.FieldAddress(ComponentNames[I]);
1184 if FieldAddr <> nil then
1185 begin
1186 //Assert(FieldAddr^ = nil); // may not be true, user can reuse AssociateReferences
1187 Assert(ComponentNames.Objects[I] is TComponent); // also checks ComponentNames.Objects[I] <> nil
1188 FieldAddr^ := ComponentNames.Objects[I] as TComponent;
1189 end;
1190 end;
1191 end;
1192
1193 var
1194 Reader: TCastleJsonReader;
1195 begin
1196 Reader := TCastleJsonReader.Create;
1197 try
1198 Reader.FOwner := InstanceOwner;
1199 Reader.LoadInfo := LoadInfo;
1200
1201 { create Result with appropriate class }
1202 Result := CreateComponentFromJson(JsonObject, InstanceOwner, LoadInfo);
1203
1204 { read Result contents from JSON }
1205 Reader.DeStreamer.JsonToObject(JsonObject, Result);
1206
1207 Reader.FinishResolvingComponentProperties;
1208
1209 if AssociateReferences <> nil then
1210 MakeAssociateReferences(Reader.ComponentNames);
1211
1212 if Assigned(OnInternalTranslateDesign) and (FTranslationGroupName <> '') then
1213 OnInternalTranslateDesign(Result, FTranslationGroupName);
1214 finally
1215 FreeAndNil(Reader);
1216 end;
1217 end;
1218
1219 { routines ----------------------------------------------------------------- }
1220
1221 function StringToComponent(const Contents: String; const Owner: TComponent): TComponent;
1222 begin
1223 Result := InternalStringToComponent(Contents, Owner, nil);
1224 end;
1225
1226 function InternalStringToComponent(const Contents: String;
1227 const Owner: TComponent;
1228 const LoadInfo: TInternalComponentLoadInfo): TComponent;
1229 var
1230 Factory: TCastleComponentFactory;
1231 ContentsStringStream: TStringStream;
1232 begin
1233 ContentsStringStream := TStringStream.Create(Contents);
1234 try
1235 Factory := TCastleComponentFactory.Create(nil);
1236 try
1237 Factory.LoadFromStream(ContentsStringStream, '');
1238 Result := Factory.InternalComponentLoad(Owner, nil, LoadInfo);
1239 finally FreeAndNil(Factory) end;
1240 finally FreeAndNil(ContentsStringStream) end;
1241 end;
1242
1243 function ComponentLoad(const Url: String; const Owner: TComponent): TComponent;
1244
1245 { We could use StringToComponent now, but then TCastleComponentFactory
1246 would not know Url, so TCastleComponentFactory.FTranslationGroupName
1247 would be empty and TranslateAllDesigns would not work.
1248
1249 begin
1250 Result := StringToComponent(FileToString(Url), Owner);
1251 end;}
1252
1253 var
1254 Factory: TCastleComponentFactory;
1255 begin
1256 Factory := TCastleComponentFactory.Create(nil);
1257 try
1258 Factory.Url := Url;
1259 Result := Factory.ComponentLoad(Owner);
1260 finally FreeAndNil(Factory) end;
1261 end;
1262
1263 function ComponentClone(const C: TComponent; const NewComponentOwner: TComponent): TComponent;
1264 var
1265 Factory: TCastleComponentFactory;
1266 begin
1267 Factory := TCastleComponentFactory.Create(nil);
1268 try
1269 Factory.LoadFromComponent(C);
1270 Result := Factory.ComponentLoad(NewComponentOwner);
1271 finally FreeAndNil(Factory) end;
1272 end;
1273
1274 { saving to JSON ------------------------------------------------------------- }
1275
1276 type
1277 TCastleJsonWriter = class
1278 strict private
1279 type
1280 { Handle writing custom things during TCastleComponent.CustomSerialization. }
1281 TSerializationProcessWriter = class(TSerializationProcess)
1282 strict private
1283 CurrentlyWritingArray: TJsonArray;
1284 Key: String;
1285 procedure WriteItem(C: TComponent);
1286 public
1287 Writer: TCastleJsonWriter;
1288 CurrentlyWriting: TJsonObject;
1289 procedure ReadWriteInteger(const AKey: String; var Value: Integer; const IsStored: Boolean);
1290 overload; override;
1291 procedure ReadWriteBoolean(const AKey: String; var Value: Boolean; const IsStored: Boolean);
1292 overload; override;
1293 procedure ReadWriteString(const AKey: String; var Value: String; const IsStored: Boolean);
1294 overload; override;
1295 procedure ReadWriteSingle(const AKey: String; var Value: Single; const IsStored: Boolean);
1296 overload; override;
1297 procedure ReadWriteSubComponent(const AKey: String; const Value: TComponent;
1298 const IsStored: Boolean); override;
1299 procedure ReadWriteList(const AKey: String;
1300 const ListEnumerate: TSerializationProcess.TListEnumerateEvent;
1301 const ListAdd: TSerializationProcess.TListAddEvent;
1302 const ListClear: TSerializationProcess.TListClearEvent); override;
1303 end;
1304 TSerializationProcessWriterList = {$ifdef FPC}specialize{$endif} TObjectList<TSerializationProcessWriter>;
1305
1306 var
1307 FStreamer: TJsonStreamer;
1308 { Using just one TSerializationProcessWriter instance is not enough,
1309 as C.CustomSerialization calls may happen recursively. }
1310 SerializationProcessPool: TSerializationProcessWriterList;
1311 SerializationProcessPoolUsed: Integer;
1312
1313 procedure BeforeStreamObject(Sender: TObject; AObject: TObject; Json: TJsonObject);
1314 procedure AfterStreamObject(Sender: TObject; AObject: TObject; Json: TJsonObject);
1315 procedure StreamProperty(Sender: TObject; AObject: TObject; Info: PPropInfo; var Res: TJsonData);
1316 public
1317 constructor Create;
1318 destructor Destroy; override;
1319 property Streamer: TJsonStreamer read FStreamer;
1320 end;
1321
1322 procedure TCastleJsonWriter.TSerializationProcessWriter.WriteItem(C: TComponent);
1323 begin
1324 // create JSON array only when the list is non-empty, this way JSON is simpler.
1325 if CurrentlyWritingArray = nil then
1326 begin
1327 CurrentlyWritingArray := TJsonArray.Create;
1328 CurrentlyWriting.Add('$' + Key, CurrentlyWritingArray);
1329 end;
1330
1331 CurrentlyWritingArray.Add(Writer.Streamer.ObjectToJson(C));
1332 end;
1333
1334 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteInteger(
1335 const AKey: String; var Value: Integer; const IsStored: Boolean);
1336 begin
1337 if IsStored then
1338 begin
1339 CurrentlyWriting.Add(AKey, TJsonIntegerNumber.Create(Value));
1340 end;
1341 end;
1342
1343 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteBoolean(
1344 const AKey: String; var Value: Boolean; const IsStored: Boolean);
1345 begin
1346 if IsStored then
1347 begin
1348 CurrentlyWriting.Add(AKey, TJsonBoolean.Create(Value));
1349 end;
1350 end;
1351
1352 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteString(
1353 const AKey: String; var Value: String; const IsStored: Boolean);
1354 begin
1355 if IsStored then
1356 begin
1357 CurrentlyWriting.Add(AKey, TJsonString.Create(Value));
1358 end;
1359 end;
1360
1361 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteSingle(
1362 const AKey: String; var Value: Single; const IsStored: Boolean);
1363 begin
1364 if IsStored then
1365 begin
1366 CurrentlyWriting.Add(AKey, TJsonFloatNumber.Create(Value));
1367 end;
1368 end;
1369
1370 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteSubComponent(
1371 const AKey: String; const Value: TComponent; const IsStored: Boolean);
1372 begin
1373 if IsStored then
1374 begin
1375 CurrentlyWriting.Add(AKey, Writer.Streamer.ObjectToJson(Value));
1376 end;
1377 end;
1378
1379 procedure TCastleJsonWriter.TSerializationProcessWriter.ReadWriteList(const AKey: String;
1380 const ListEnumerate: TSerializationProcess.TListEnumerateEvent;
1381 const ListAdd: TSerializationProcess.TListAddEvent;
1382 const ListClear: TSerializationProcess.TListClearEvent);
1383 begin
1384 CurrentlyWritingArray := nil; // will be created on-demand
1385 Key := AKey;
1386 ListEnumerate({$ifdef FPC}@{$endif}WriteItem);
1387 end;
1388
1389 constructor TCastleJsonWriter.Create;
1390 begin
1391 inherited Create;
1392
1393 FStreamer := TJsonStreamer.Create(nil);
1394 Streamer.Options := [
1395 // We no longer use it. Our CustomSerialization fills this use-case in more flexible manner.
1396 // jsoStreamChildren,
1397 { Otherwise TStrings (like TCastleLabel.Text) is written
1398 as a single String, and newlines are written as "\n" or "\r\n"
1399 depending on OS used to write the file.
1400 This causes needless differences in version control later. }
1401 jsoTStringsAsArray,
1402 { Makes TDateTime more readable }
1403 jsoDateTimeAsString,
1404 jsoCheckEmptyDateTime
1405 ];
1406 Streamer.BeforeStreamObject := {$ifdef FPC}@{$endif}BeforeStreamObject;
1407 Streamer.AfterStreamObject := {$ifdef FPC}@{$endif}AfterStreamObject;
1408 Streamer.OnStreamProperty := {$ifdef FPC}@{$endif}StreamProperty;
1409
1410 SerializationProcessPool := TSerializationProcessWriterList.Create(true);
1411 end;
1412
1413 destructor TCastleJsonWriter.Destroy;
1414 begin
1415 FreeAndNil(FStreamer);
1416 FreeAndNil(SerializationProcessPool);
1417 inherited;
1418 end;
1419
1420 procedure TCastleJsonWriter.BeforeStreamObject(
1421 Sender: TObject; AObject: TObject; Json: TJsonObject);
1422 begin
1423 { set $$ClassName string, our reader depends on it.
1424 Uses 2 $, to differentiate from stuff written by TSerializationProcess.ReadWrite.
1425 We do this in BeforeStreamObject (not AfterStreamObject) only because this way
1426 resulting JSON is easier to read by humans ($$ClassName is at the beginning). }
1427 Json.Strings['$$ClassName'] := AObject.ClassName;
1428 end;
1429
1430 procedure TCastleJsonWriter.AfterStreamObject(
1431 Sender: TObject; AObject: TObject; Json: TJsonObject);
1432
1433 { Call C.CustomSerialization(SerializationProcess) }
1434 procedure CustomSerializationWithSerializationProcess(const C: TCastleComponent;
1435 const SerializationProcess: TSerializationProcessWriter);
1436 begin
1437 SerializationProcess.CurrentlyWriting := Json;
1438 SerializationProcess.Writer := Self;
1439 C.CustomSerialization(SerializationProcess);
1440 end;
1441
1442 { Call C.CustomSerialization }
1443 procedure CustomSerialization(const C: TCastleComponent);
1444 var
1445 SerializationProcess: TSerializationProcessWriter;
1446 begin
1447 if SerializationProcessPoolUsed < SerializationProcessPool.Count then
1448 // faster: use ready SerializationProcess from pool
1449 SerializationProcess := SerializationProcessPool[SerializationProcessPoolUsed]
1450 else
1451 begin
1452 // slower: create new SerializationProcess,
1453 // and add it to pool for future use from the same reader
1454 SerializationProcess := TSerializationProcessWriter.Create;
1455 SerializationProcessPool.Add(SerializationProcess);
1456 end;
1457 Assert(SerializationProcessPoolUsed < SerializationProcessPool.Count);
1458
1459 Inc(SerializationProcessPoolUsed);
1460 try
1461 CustomSerializationWithSerializationProcess(C, SerializationProcess);
1462 finally Dec(SerializationProcessPoolUsed) end;
1463 end;
1464
1465 var
1466 C: TCastleComponent;
1467 begin
1468 if AObject is TCastleComponent then
1469 begin
1470 C := TCastleComponent(AObject);
1471 CustomSerialization(C);
1472 end;
1473 end;
1474
1475 procedure TCastleJsonWriter.StreamProperty(Sender: TObject;
1476 AObject: TObject; Info: PPropInfo; var Res: TJsonData);
1477
1478 { Serialize to JSON a set of values from 0 to Highest. }
1479 function SerializeSet(
1480 { Note that GetOrdProp result type for each compiler is different:
1481 - Int64 https://www.freepascal.org/docs-html/rtl/typinfo/getordprop.html
1482 - NativeInt https://docwiki.embarcadero.com/Libraries/Sydney/en/System.TypInfo.GetOrdProp
1483 It seems we can reliably handle at most 32 bits.
1484 Actually TCastleTiledMap.TLayerIndex limits itself to 31 bits for now,
1485 to avoid worrying about whether negative values are passed through the API OK.
1486 }
1487 const ValueOfSet: UInt32;
1488 const Highest: Integer): TJsonArray;
1489 type
1490 TIntegerSet = set of 0..31;
1491 var
1492 I: Integer;
1493 begin
1494 Result := TJSONArray.Create;
1495 for I := 0 to Highest do
1496 if I in TIntegerSet(ValueOfSet) then
1497 TJSONArray(Result).Add(I);
1498 end;
1499
1500 begin
1501 if Info^.Name = 'Name' then
1502 begin
1503 if (AObject is TComponent) and
1504 (csSubComponent in TComponent(AObject).ComponentStyle) then
1505 begin
1506 { Do not stream names of subcomponents, like
1507 - TCastlePerspective (their names are internal, not really supposed to be edited by user -- no point)
1508 - TCastleVector3Persistent (their names are internal, not really supposed to be edited by user -- no point, and always empty)
1509
1510 This is consistent with TDesignFrame.InspectorFilter that hides such names.
1511 Although here we cannot detect them by "Owner is different than DesignOwner",
1512 because when serializing we don't know the DesignOwner. }
1513 //WritelnLog('Not serializing ' + AObject.ClassName + '.' + Info^.Name + ' because it is a subcomponent name');
1514 FreeAndNil(Res);
1515 end;
1516
1517 { Otherwise (for not subcomponents) serialize 'Name' always,
1518 ignore the rest of the checks (they would reject serializing Name). }
1519 Exit;
1520 end;
1521
1522 // do not stream null values, as reader makes errors on them
1523 if Res is TJsonNull then
1524 begin
1525 FreeAndNil(Res);
1526 Exit;
1527 end;
1528
1529 // do not stream properties with stored=false
1530 if not IsStoredProp(AObject as TPersistent, Info) then
1531 begin
1532 //WritelnLog('Not serializing ' + AObject.ClassName + '.' + Info^.Name + ' because stored function answers false');
1533 FreeAndNil(Res);
1534 Exit;
1535 end;
1536
1537 // do not store properties with default values
1538 if PropertyHasDefaultValue(AObject, Info) then
1539 begin
1540 //WritelnLog('Not serializing ' + AObject.ClassName + '.' + Info^.Name + ' because it has default value');
1541 FreeAndNil(Res);
1542 Exit;
1543 end;
1544
1545 { Custom support for sets of integers (T3DCoords, TLayers) serialization.
1546
1547 By default FpJsonRtti has a bug in this case:
1548 It tries to do "GetEnumName" on integers 0..max, and serializes weird thing
1549
1550 "LockRotation" : [
1551 "\u0000",
1552 ""
1553 ]
1554
1555 .. that it cannot deserialize back.
1556 The code below does serialization as if "jsoSetEnumeratedAsInteger in Options"
1557 but only for this type. We don't want to change serialization of sets of enums.
1558 }
1559 if (Info^.PropType^.Kind = tkSet) and (Info^.PropType^.Name = 'T3DCoords') then
1560 begin
1561 FreeAndNil(Res);
1562 Res := SerializeSet(GetOrdProp(AObject, Info), 2 { manually synchronized with T3DCoord });
1563 end;
1564 if (Info^.PropType^.Kind = tkSet) and (Info^.PropType^.Name = 'TLayers') then
1565 begin
1566 FreeAndNil(Res);
1567 Res := SerializeSet(GetOrdProp(AObject, Info), 30 { manually synchronized with TCastleTiledMap.TLayerIndex });
1568 end;
1569 if (Info^.PropType^.Kind = tkSet) and (Info^.PropType^.Name = 'TColorChannels') then
1570 begin
1571 FreeAndNil(Res);
1572 Res := SerializeSet(GetOrdProp(AObject, Info), 3 { manually synchronized with TColorChannel });
1573 end;
1574 end;
1575
1576 function ComponentToJson(const C: TComponent): TJsonObject;
1577 var
1578 Writer: TCastleJsonWriter;
1579 begin
1580 Writer := TCastleJsonWriter.Create;
1581 try
1582 Result := Writer.Streamer.ObjectToJson(C);
1583 finally FreeAndNil(Writer) end;
1584 end;
1585
1586 function ComponentToString(const C: TComponent): String;
1587 var
1588 Json: TJsonObject;
1589 begin
1590 Json := ComponentToJson(C);
1591 try
1592 Result := Json.FormatJson;
1593 finally FreeAndNil(Json) end;
1594 end;
1595
1596 procedure ComponentSave(const C: TComponent; const Url: String);
1597 begin
1598 StringToFile(Url, ComponentToString(C));
1599 end;
1600
1601 procedure InternalAssignUsingSerialization(const Destination, Source: TComponent);
1602 var
1603 Json: TJsonObject;
1604 Reader: TCastleJsonReader;
1605 Writer: TCastleJsonWriter;
1606 begin
1607 { We check proper inheritance here,
1608 this way we don't need to later care about whether Json has proper
1609 Json.Strings['$$ClassName']
1610 recorded. }
1611 if not Destination.InheritsFrom(Source.ClassType) then
1612 raise Exception.CreateFmt('Cannot assign instance of %s (source) to %s (destination). Destination class should be equal or inherit from Source class.', [
1613 Source.ClassName,
1614 Destination.ClassName
1615 ]);
1616
1617 Writer := TCastleJsonWriter.Create;
1618 try
1619 Json := Writer.Streamer.ObjectToJson(Source);
1620 try
1621 Reader := TCastleJsonReader.Create;
1622 try
1623 Reader.FOwner := Destination;
1624
1625 { read Result contents from JSON }
1626 Reader.DeStreamer.JsonToObject(Json, Destination);
1627 Reader.FinishResolvingComponentProperties;
1628 finally FreeAndNil(Reader) end;
1629 finally FreeAndNil(Json) end;
1630 finally FreeAndNil(Writer) end;
1631 end;
1632
1633 { TComponentHelper ----------------------------------------------------------- }
1634
1635 function TComponentHelper.FindRequiredComponent(const AName: String): TComponent;
1636 begin
1637 Result := FindComponent(AName);
1638 if Result = nil then
1639 raise EComponentNotFound.CreateFmt('Cannot find component named "%s"', [AName]);
1640 end;
1641
1642 initialization
1643 // not useful: RegisterSerializableComponent(TComponent, 'Component (Basic)');
1644 RegisterSerializableComponent(TCastleComponent, 'Component (Group)');
1645 finalization
1646 FreeAndNil(FRegisteredComponents);
1647 end.