Debian Codegraph @

tools/build-tool/code/toolproject.pas

raw
1 {
2 Copyright 2014-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 { Project information (from CastleEngineManifest.xml) and operations. }
17 unit ToolProject;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections,
24 CastleFindFiles, CastleStringUtils, CastleUtils, CastleInternalTools,
25 ToolArchitectures, ToolCompile, ToolUtils, ToolServices, ToolAssocDocTypes,
26 ToolPackage, ToolManifest, ToolProcess, ToolPackageFormat;
27
28 type
29 ECannotGuessManifest = class(Exception);
30
31 TCastleProject = class
32 private
33 ManifestFile: string;
34 Manifest: TCastleManifest;
35 DeletedFiles: Cardinal; //< only for DeleteFoundFile
36 // Helpers only for ExtractTemplateFoundFile.
37 // @groupBegin
38 ExtractTemplateDestinationPath, ExtractTemplateDir: string;
39 ExtractTemplateOverrideExisting: Boolean;
40 // @groupEnd
41 { Use to define macros containing the Android architecture names.
42 Must be set by all commands that may use our macro system. }
43 AndroidCPUS: TCPUS;
44 IOSExportMethod: String; // set by DoPackage based on PackageFormat, otherwise ''
45 FLaunchImageStoryboardInitialized: Boolean;
46 FLaunchImageStoryboardWidth, FLaunchImageStoryboardHeight: Integer;
47 FGuidFromName: Boolean;
48
49 procedure DeleteFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
50 function PackageName(const OS: TOS; const CPU: TCPU; const PackageFormat: TPackageFormatNoDefault;
51 const PackageNameIncludeVersion: Boolean): string;
52 function SourcePackageName(const PackageNameIncludeVersion: Boolean;
53 const PackageFormatFinal: TPackageFormatNoDefault): string;
54 procedure ExtractTemplateFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
55
56 { Detect welcome file. Returns '' or a relative filename inside the project.
57
58 Right now it is only used to display in Delphi IDE
59 (specified in DPROJ, makes project look nice when it is opened,
60 esp. since CGE examples and templates recommend README.md and Delphi
61 handles Markdown nicely).
62 And right now it is only detected automatically.
63
64 In the future:
65 - We may use it for more things, e.g. display in CGE editor.
66 - We may allow to set it explicitly in CastleEngineManifest.xml. }
67 function WelcomePage: String;
68
69 { Convert Name to a valid Pascal identifier. }
70 function NamePascal: string;
71
72 { Extract a single file using the template system.
73 SourceFileName and DestinationFileName should be absolute filenames
74 of source and destination files.
75 DestinationRelativeFileName should be a relative version of DestinationFileName,
76 relative to the template root.
77
78 This is used internally by ExtractTemplateFoundFile, which is in turn used
79 by ExtractTemplate that can extract a whole template directory.
80
81 It can also be used directly to expand a single file. }
82 procedure ExtractTemplateFile(
83 const SourceFileName, DestinationFileName, DestinationRelativeFileName: string;
84 const OverrideExisting: boolean);
85
86 { Generate a Pascal file from template. }
87 procedure GeneratedSourceFile(
88 const TemplateRelativeUrl, TargetRelativePath, ErrorMessageMissingGameUnits: string;
89 const CreateIfNecessary: boolean;
90 out RelativeResult, AbsoluteResult: string);
91 procedure GeneratedSourceFile(
92 const TemplateRelativeUrl, TargetRelativePath, ErrorMessageMissingGameUnits: string;
93 const CreateIfNecessary: boolean);
94
95 function AndroidSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
96 function IOSSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
97 function NXSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
98 function StandaloneSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
99
100 { The standalone program filename that is generated by "castle-engine generate-program".
101
102 Unlike StandaloneSourceFile, this is explicit,
103 i.e. it never points to internal name in "castle-engine-output".
104 Also this method never creates the file, it merely calculates the filename.
105
106 The returned filename is relative. It is often without any path
107 (like "my_program_standalone.dpr") but it may contain a relative path
108 (like "code/my_program_standalone.dpr") if such path was specified
109 in CastleEngineManifest.xml. }
110 function ExplicitStandaloneFile(const Ext: String): String;
111
112 { Check the PackageFormat (looking at what is allowed for this Target/OS/CPU),
113 finalize the pfDefault to something more concrete. }
114 function PackageFormatFinalize(
115 const Target: TTarget; const OS: TOS; const CPU: TCPU;
116 const PackageFormat: TPackageFormat): TPackageFormatNoDefault;
117
118 procedure AddMacrosAndroid(const Macros: TStringStringMap);
119 procedure AddMacrosIOS(const Macros: TStringStringMap);
120 public
121 constructor Create;
122 constructor Create(const APath: string);
123 constructor CreateNewProject(const ParentDir,
124 ProjectName, TemplateName, ProjectCaption, MainView: String);
125 destructor Destroy; override;
126
127 { Commands on a project, used by the main program code. }
128 { }
129
130 procedure DoCreateManifest;
131 procedure DoCompile(const OverrideCompiler: TCompiler;
132 const Target: TTarget; const OS: TOS; const CPU: TCPU;
133 const Mode: TCompilationMode; const CompilerExtraOptions: TStrings = nil;
134 const AllowCache: Boolean = true);
135 procedure DoPackage(const Target: TTarget;
136 const OS: TOS; const CPU: TCPU; const Mode: TCompilationMode;
137 const PackageFormat: TPackageFormat;
138 const PackageNameIncludeVersion, UpdateOnlyCode: Boolean);
139 procedure DoInstall(const Target: TTarget; const OS: TOS; const CPU: TCPU;
140 const Mode: TCompilationMode;
141 const PackageFormat: TPackageFormat;
142 const PackageNameIncludeVersion: Boolean);
143 procedure DoRun(const Target: TTarget; const OS: TOS; const CPU: TCPU;
144 const Params: TCastleStringList);
145 procedure DoPackageSource(
146 const PackageFormat: TPackageFormat;
147 const PackageNameIncludeVersion: Boolean);
148 procedure DoClean;
149 procedure DoAutoGenerateTextures;
150 procedure DoAutoGenerateClean(const CleanAll: Boolean);
151 procedure DoGenerateProgram(const GuidFromName: Boolean);
152 procedure DoEditor;
153 procedure DoEditorRebuildIfNeeded;
154 procedure DoEditorRun(const WaitForProcessId: TProcessId);
155 procedure DoOutput(const OutputKey: String);
156
157 { Information about the project, derived from CastleEngineManifest.xml. }
158 { }
159
160 function Version: TProjectVersion;
161 function ManifestCompiler: TCompiler;
162 function QualifiedName: string;
163 function Dependencies: TDependencies;
164 function Name: string;
165 { Project path. Always ends with path delimiter, like a slash or backslash. }
166 function Path: string;
167 function DataExists: Boolean;
168 { Project data path. Always ends with path delimiter, like a slash or backslash.
169 Should be ignored if not @link(DataExists). }
170 function DataPath: string;
171 function Caption: string;
172 function Author: string;
173 function ExecutableName: string;
174 function FullscreenImmersive: boolean;
175 function ScreenOrientation: TScreenOrientation;
176 function AndroidCompileSdkVersion: Cardinal;
177 function AndroidMinSdkVersion: Cardinal;
178 function AndroidTargetSdkVersion: Cardinal;
179 function Icons: TImageFileNames;
180 function LaunchImages: TImageFileNames;
181 function AndroidServices: TServiceList;
182 function IOSServices: TServiceList;
183 function AssociateDocumentTypes: TAssociatedDocTypeList;
184 function LocalizedAppNames: TLocalizedAppNameList;
185 function LaunchImageStoryboard: TLaunchImageStoryboard;
186
187 function ReplaceMacros(const Source: string): string;
188
189 { Recursively copy a directory from TemplatePath (this is relative
190 to the build tool data) to the DestinationPath (this should be an absolute
191 existing directory name).
192
193 Each file is processed by the ReplaceMacros method.
194
195 OverrideExisting says what happens when the destination file already exists.
196
197 - OverrideExisting = @false (default) means that the
198 destination file will be left unchanged
199 (to preserve possible user customization),
200 or source will be merged into destination
201 (in case of special filenames;
202 this allows to e.g. merge AndroidManifest.xml).
203
204 - OverrideExisting = @true means that the destination file
205 will simply be overridden, without any warning, without
206 any merging.
207 }
208 procedure ExtractTemplate(const TemplatePath, DestinationPath: string;
209 const OverrideExisting: Boolean = false);
210
211 { Output Android library resulting from compilation.
212 Relative to @link(Path) if AbsolutePath = @false,
213 otherwise a complete absolute path.
214
215 CPU should be one of CPUs supported on Android platform (arm, aarch64)
216 or cpuNone to get the library name without the CPU suffix. }
217 function AndroidLibraryFile(const CPU: TCPU; const AbsolutePath: boolean = true): string;
218
219 { Get platform-independent files that should be included in a package,
220 remove files that should be excluded.
221
222 If OnlyData, then only takes stuff inside DataPath,
223 and Files will contain URLs relative to DataPath.
224 Otherwise, takes all files to be packaged in a project,
225 and Files will contain URLs relative to @link(Path).
226
227 The copy will only contain files useful on given TargetPlatform.
228 Right now this means we will exclude auto-generated textures not suitable
229 for TargetPlatform.
230
231 The associated objects of the returned TCastleStringList,
232 if non nil, are TIncludePath instances that caused inclusion
233 of given file in the package. }
234 function PackageFiles(const OnlyData: boolean;
235 const TargetPlatform: TCastlePlatform): TCastleStringList;
236
237 { Output iOS library resulting from compilation.
238 Relative to @link(Path) if AbsolutePath = @false,
239 otherwise a complete absolute path. }
240 function IOSLibraryFile(const AbsolutePath: boolean = true): string;
241
242 { Output Nintendo Switch library resulting from compilation.
243 Relative to @link(Path) if AbsolutePath = @false,
244 otherwise a complete absolute path. }
245 function NXLibraryFile(const AbsolutePath: boolean = true): string;
246
247 { Where should we place our output files, calculated looking at OutputPathBase
248 and project path. Always an absolute filename ending with path delimiter. }
249 function OutputPath: string;
250
251 { Copy project data subdirectory to given path.
252 OutputDataPath may but doesn't have to end with PathDelim.
253
254 The path will be created if necessary (even if there are no files,
255 this is useful at least for XCode as it references the resulting directory,
256 so it must exist).
257
258 The copy will only contain files useful on given TargetPlatform.
259 Right now this means we will exclude auto-generated textures not suitable
260 for TargetPlatform.
261
262 We also generate the auto_generated/CastleDataInformation.xml inside.
263 (Actually, this means the resulting directory is never empty now.) }
264 procedure CopyData(OutputDataPath: string; const TargetPlatform: TCastlePlatform);
265
266 { Is this filename created by some DoPackage or DoPackageSource command.
267 FileName must be relative to project root directory. }
268 function PackageOutput(const FileName: String): Boolean;
269
270 function IOSHasLaunchImageStoryboard: Boolean;
271 end;
272
273 implementation
274
275 uses {$ifdef UNIX} BaseUnix, {$endif}
276 StrUtils, DOM, Process,
277 CastleUriUtils, CastleXmlUtils, CastleLog, CastleFilesUtils, CastleImages,
278 CastleTimeUtils,
279 ToolResources, ToolAndroid, ToolMacOS,
280 ToolTextureGeneration, ToolIOS, ToolAndroidMerging, ToolNintendoSwitch,
281 ToolCommonUtils, ToolMacros, ToolCompilerInfo, ToolPackageCollectFiles;
282
283 const
284 SErrDataDir = 'Make sure you have installed the data files of the Castle Game Engine build tool. Usually it is easiest to set the $CASTLE_ENGINE_PATH environment variable to the location of castle_game_engine/ or castle-engine/ directory, the build tool will then find its data correctly.'
285 {$ifdef UNIX}
286 + ' Or place the data in system-wide location /usr/share/castle-engine/ or /usr/local/share/castle-engine/.'
287 {$endif};
288
289 { Insert 'lib' prefix at the beginning of file name. }
290 function InsertLibPrefix(const S: string): string;
291 begin
292 Result := ExtractFilePath(S) + 'lib' + ExtractFileName(S);
293 end;
294
295 { Compiled library name (.so, .dll etc.) from given source code filename. }
296 function CompiledLibraryFile(const S: string; const OS: TOS): string;
297 begin
298 Result := ChangeFileExt(S, LibraryExtensionOS(OS));
299 if OS in AllUnixOSes then
300 Result := InsertLibPrefix(Result);
301 end;
302
303 { List filenames of external libraries used by the Dependencies, on given OS/CPU. }
304 procedure ExternalLibraries(const OS: TOS; const CPU: TCPU;
305 const ProjectDependencies: TProjectDependencies; const List: TStrings;
306 const CheckFilesExistence: Boolean = true);
307
308 { Path to the external library in data/external_libraries/ .
309 Right now, these host various Windows-specific DLL files.
310 If CheckFilesExistence then this checks existence of appropriate files along the way,
311 and raises exception in case of trouble. }
312 function ExternalLibraryPath(const OS: TOS; const CPU: TCPU; const LibraryName: string): string;
313 var
314 LibraryUrl: String;
315 begin
316 LibraryUrl := 'castle-data:/' + LibraryName;
317 Result := UriToFilenameSafe(LibraryUrl);
318 if CheckFilesExistence and (not RegularFileExists(Result)) then
319 raise Exception.Create('Cannot find dependency library in "' + Result + '". ' + SErrDataDir);
320 end;
321
322 procedure AddExternalLibrary(const LibraryName: string);
323 begin
324 List.Add(ExternalLibraryPath(OS, CPU, LibraryName));
325 end;
326
327 var
328 Files: TStringList;
329 F: String;
330 begin
331 Files := TStringList.Create;
332 try
333 case OS of
334 win32: ProjectDependencies.DeployFiles(dpWin32, Files);
335 win64: ProjectDependencies.DeployFiles(dpWin64, Files);
336 else ; { no need to do anything on other OSes }
337 end;
338
339 for F in Files do
340 AddExternalLibrary(F);
341 finally FreeAndNil(Files) end;
342 end;
343
344 { TCastleProject ------------------------------------------------------------- }
345
346 constructor TCastleProject.Create;
347 var
348 { look for CastleEngineManifest.xml in this dir, or parents }
349 Dir, ParentDir: string;
350 begin
351 Dir := GetCurrentDir;
352 while not RegularFileExists(InclPathDelim(Dir) + ManifestName) do
353 begin
354 ParentDir := ExtractFileDir(ExclPathDelim(Dir));
355 if (ParentDir = '') or (ParentDir = Dir) then
356 begin
357 { no parent directory, give up, assume auto-guessed values in current dir }
358 Create(GetCurrentDir);
359 Exit;
360 end;
361 {if Verbose then
362 Writeln('Manifest not found, looking in parent directory: ', ParentDir);}
363 Dir := ParentDir;
364 end;
365 Create(Dir);
366 end;
367
368 constructor TCastleProject.Create(const APath: string);
369
370 procedure ReadManifest;
371
372 function GuessStandaloneSource: string;
373 var
374 FileInfo: TFileInfo;
375 begin
376 Result := ExtractFileName(ExtractFileDir(ManifestFile)) + '.lpr';
377 if RegularFileExists(Result) then
378 Exit;
379
380 Result := ExtractFileName(ExtractFileDir(ManifestFile)) + '.dpr';
381 if RegularFileExists(Result) then
382 Exit;
383
384 if FindFirstFile(GetCurrentDir, '*.lpr', false, [], FileInfo) then
385 Exit(FileInfo.Name);
386
387 if FindFirstFile(GetCurrentDir, '*.dpr', false, [], FileInfo) then
388 Exit(FileInfo.Name);
389
390 raise ECannotGuessManifest.Create('Cannot find any *.lpr or *.dpr file in this directory, cannot guess which file to compile.' + NL +
391 'Please create a CastleEngineManifest.xml to instruct Castle Game Engine build tool how to build your project.');
392 end;
393
394 var
395 ManifestUrl: String;
396 begin
397 ManifestFile := InclPathDelim(APath) + ManifestName;
398 ManifestUrl := FilenameToUriSafe(ManifestFile);
399
400 if not RegularFileExists(ManifestFile) then
401 begin
402 Writeln('Manifest file not found: ' + ManifestFile);
403 Writeln('Guessing project values. Use create-manifest command to write these guesses into new CastleEngineManifest.xml');
404 Manifest := TCastleManifest.CreateGuess(APath, GuessStandaloneSource);
405 end else
406 begin
407 WritelnVerbose('Manifest file found: ' + ManifestFile);
408 Manifest := TCastleManifest.CreateFromUrl(APath, ManifestUrl);
409 end;
410 end;
411
412 function DependenciesToStr(const S: TDependencies): string;
413 var
414 D: TDependency;
415 begin
416 Result := '';
417 for D in S do
418 begin
419 if Result <> '' then Result += ', ';
420 Result += DependencyToString(D);
421 end;
422 Result := '[' + Result + ']';
423 end;
424
425 begin
426 inherited Create;
427
428 ReadManifest;
429
430 if Verbose then
431 Writeln('Project "' + Name + '" dependencies: ' + DependenciesToStr(Dependencies));
432 end;
433
434 constructor TCastleProject.CreateNewProject(const ParentDir,
435 ProjectName, TemplateName, ProjectCaption, MainView: String);
436 var
437 Options: TProjectCreationOptions;
438 ProjectDirUrl, ProjectDir: String;
439 begin
440 Options.ParentDir := ParentDir;
441 Options.TemplateName := TemplateName;
442 Options.ProjectName := ProjectName;
443 Options.ProjectCaption := ProjectCaption;
444 Options.MainView := MainView;
445 ProjectCreateFromTemplate(CastleEnginePath, Options, ProjectDirUrl);
446
447 ProjectDir := UriToFilenameSafe(ProjectDirUrl);
448 Writeln('Created new project in ' + ProjectDir + ' based on template ' + TemplateName);
449
450 Create(ProjectDir);
451
452 DoGenerateProgram(false);
453 end;
454
455 destructor TCastleProject.Destroy;
456 begin
457 FreeAndNil(Manifest);
458 inherited;
459 end;
460
461 procedure TCastleProject.DoCreateManifest;
462 var
463 Contents: string;
464 begin
465 if RegularFileExists(ManifestFile) then
466 raise Exception.CreateFmt('Manifest file "%s" already exists, refusing to overwrite it',
467 [ManifestFile]);
468 Contents := '<?xml version="1.0" encoding="utf-8"?>' +NL+
469 '<project name="' + Name + '" standalone_source="' + Manifest.StandaloneSource + '">' +NL+
470 '</project>' + NL;
471 StringToFile(ManifestFile, Contents);
472 Writeln('Created manifest ' + ManifestFile);
473 end;
474
475 procedure TCastleProject.DoCompile(const OverrideCompiler: TCompiler; const Target: TTarget;
476 const OS: TOS; const CPU: TCPU; const Mode: TCompilationMode;
477 const CompilerExtraOptions: TStrings;
478 const AllowCache: Boolean);
479
480 { Copy external libraries to LibrariesOutputPath.
481 LibrariesOutputPath must be empty (current dir) or ending with path delimiter. }
482 procedure AddExternalLibraries(const LibrariesOutputPath: String);
483 var
484 List: TCastleStringList;
485 OutputFile, FileName: String;
486 begin
487 List := TCastleStringList.Create;
488 try
489 ExternalLibraries(OS, CPU, Manifest.ProjectDependencies, List);
490 for FileName in List do
491 begin
492 OutputFile := LibrariesOutputPath + ExtractFileName(FileName);
493 WritelnVerbose('Copying library to ' + OutputFile);
494 CheckCopyFile(FileName, OutputFile);
495 end;
496 finally FreeAndNil(List) end;
497 end;
498
499 var
500 SourceExe, DestExe, MainSource: string;
501 CompilerOptions: TCompilerOptions;
502 FinalCompiler: TCompiler;
503 begin
504 Writeln(Format('Compiling project "%s" for %s in mode "%s".',
505 [Name, TargetCompleteToString(Target, OS, CPU), ModeToString(Mode)]));
506
507 CompilerOptions := TCompilerOptions.Create;
508 try
509 CompilerOptions.AllowCache := AllowCache;
510 CompilerOptions.OS := OS;
511 CompilerOptions.CPU := CPU;
512 CompilerOptions.Mode := Mode;
513 CompilerOptions.DetectMemoryLeaks := Manifest.DetectMemoryLeaks;
514 CompilerOptions.ExtraOptions.AddRange(Manifest.ExtraCompilerOptions);
515 if CompilerExtraOptions <> nil then
516 CompilerOptions.ExtraOptions.AddRange(CompilerExtraOptions);
517 CompilerOptions.SearchPaths.AddRange(Manifest.SearchPaths);
518 CompilerOptions.LibraryPaths.AddRange(Manifest.LibraryPaths);
519 CompilerOptions.Defines.AddRange(Manifest.Defines);
520
521 { TODO: "lazbuild" should be another Compiler option, called "lazbuild (calls FPC using options from LPI file)" }
522 if Manifest.BuildUsingLazbuild then
523 begin
524 CompileLazbuild(Path, Manifest.LazarusProject, CompilerOptions);
525 Exit;
526 end;
527
528 { use compiler specified in CastleEngineManifest.xml,
529 overridden by Compiler specified on command-line (given as parameter). }
530 FinalCompiler := OverrideCompiler;
531 if FinalCompiler = coAutodetect then
532 FinalCompiler := ManifestCompiler;
533
534 case Target of
535 targetAndroid:
536 begin
537 CompileAndroid(FinalCompiler, Self, Path, AndroidSourceFile(true, true), CompilerOptions);
538 end;
539 targetIOS:
540 begin
541 CompileIOS(FinalCompiler, Path, IOSSourceFile(true, true), CompilerOptions);
542 LinkIOSLibrary(FinalCompiler, Path, IOSLibraryFile);
543 Writeln('Compiled library for iOS in ', IOSLibraryFile(false));
544 end;
545 targetNintendoSwitch:
546 begin
547 CompileNintendoSwitchLibrary(Self, Path, NXSourceFile(true, true), CompilerOptions);
548 end;
549 targetCustom:
550 begin
551 case OS of
552 Android:
553 begin
554 Compile(FinalCompiler, Path, AndroidSourceFile(true, true), CompilerOptions);
555 { Our default compilation output doesn't contain CPU suffix,
556 but we need the CPU suffix to differentiate between Android/ARM and Android/Aarch64. }
557 CheckRenameFile(AndroidLibraryFile(cpuNone), AndroidLibraryFile(CPU));
558 Writeln('Compiled library for Android in ', AndroidLibraryFile(CPU, false));
559 end;
560 else
561 begin
562 MainSource := StandaloneSourceFile(false, true);
563 if MainSource = '' then
564 raise Exception.Create('standalone_source property for project not defined, cannot compile standalone version');
565
566 if MakeAutoGeneratedResources(Self, Path + ExtractFilePath(MainSource), OS, CPU) then
567 CompilerOptions.ExtraOptions.Add('-dCASTLE_AUTO_GENERATED_RESOURCES');
568
569 Compile(FinalCompiler, Path, MainSource, CompilerOptions);
570
571 SourceExe := ChangeFileExt(MainSource, ExeExtensionOS(OS));
572 DestExe := ChangeFileExt(ExecutableName, ExeExtensionOS(OS));
573 AddExternalLibraries(OutputPath);
574 if not SameFileName(SourceExe, DestExe) then
575 begin
576 { move exe to top-level (in case MainSource is in subdirectory
577 like code/) and eventually rename to follow ExecutableName }
578 Writeln('Moving ', SourceExe, ' to ', DestExe);
579 CheckRenameFile(
580 CombinePaths(Path, SourceExe),
581 CombinePaths(OutputPath, DestExe));
582 end;
583 end;
584 end;
585 end;
586 {$ifndef COMPILER_CASE_ANALYSIS}
587 else raise EInternalError.Create('Unhandled --target for DoCompile');
588 {$endif}
589 end;
590 finally FreeAndNil(CompilerOptions) end;
591 end;
592
593 function TCastleProject.PackageFiles(const OnlyData: boolean;
594 const TargetPlatform: TCastlePlatform): TCastleStringList;
595 var
596 Collector: TBinaryPackageFiles;
597 begin
598 Result := TCastleStringList.Create;
599 try
600 Collector := TBinaryPackageFiles.Create(Self);
601 try
602 Collector.IncludePaths := Manifest.IncludePaths;
603 Collector.ExcludePaths := Manifest.ExcludePaths;
604 Collector.OnlyData := OnlyData;
605 Collector.TargetPlatform := TargetPlatform;
606 Collector.Run;
607 Result.Assign(Collector.CollectedFiles);
608 finally FreeAndNil(Collector) end;
609 except FreeAndNil(Result); raise; end;
610 end;
611
612 function TCastleProject.PackageFormatFinalize(
613 const Target: TTarget; const OS: TOS; const CPU: TCPU;
614 const PackageFormat: TPackageFormat): TPackageFormatNoDefault;
615 begin
616 // calculate Result
617
618 if PackageFormat = pfDefault then
619 begin
620 if Target = targetIOS then
621 Result := pfIosXcodeProject
622 else
623 if (Target = targetAndroid) or (OS = Android) then
624 Result := pfAndroidApk
625 else
626 if Target = targetNintendoSwitch then
627 Result := pfNintendoSwitchProject
628 else
629 if OS in AllWindowsOSes then
630 Result := pfZip
631 else
632 if (OS = Darwin) and Manifest.MacAppBundle then
633 Result := pfMacAppBundleZip
634 else
635 Result := pfTarGz;
636 end else
637 Result := PackageFormat;
638
639 // check Result
640
641 if (Result in [
642 pfIosXcodeProject,
643 pfIosArchiveDevelopment,
644 pfIosArchiveAdHoc,
645 pfIosArchiveAppStore
646 ]) and (Target <> targetIOS) then
647 begin
648 raise Exception.CreateFmt('Package format "%s" only makes sense when target is iOS', [
649 PackageFormatToString(Result)
650 ]);
651 end;
652
653 if Result in [pfDeb] then
654 begin
655 if (OS <> Linux) then
656 raise Exception.Create('Cannot package DEB for OS = ' + OSToString(OS) + ' Expected: Linux.');
657 {$ifndef Linux}
658 raise Exception.Create('Currently DEB package can only be created under Linux OS, as it depends on several Linux-specific tools.');
659 {$endif}
660 end;
661
662 if (Result in [
663 pfAndroidApk,
664 pfAndroidAppBundle
665 ]) and (Target <> targetAndroid) and (OS <> Android) then
666 begin
667 raise Exception.CreateFmt('Package format "%s" only makes sense when target is Android.', [
668 PackageFormatToString(Result)
669 ]);
670 end;
671
672 if (Result in [
673 pfNintendoSwitchProject
674 ]) and (Target <> targetNintendoSwitch) then
675 begin
676 raise Exception.CreateFmt('Package format "%s" only makes sense when target is Nintendo Switch.', [
677 PackageFormatToString(Result)
678 ]);
679 end;
680 end;
681
682 procedure TCastleProject.DoPackage(const Target: TTarget;
683 const OS: TOS; const CPU: TCPU;
684 const Mode: TCompilationMode; const PackageFormat: TPackageFormat;
685 const PackageNameIncludeVersion, UpdateOnlyCode: Boolean);
686 var
687 Pack: TPackageDirectory;
688
689 function UnixPermissionsMatter: Boolean;
690 begin
691 Result := not (OS in AllWindowsOSes);
692 end;
693
694 procedure AddExecutable;
695 var
696 ExecutableNameExt, ExecutableNameFull: string;
697 begin
698 if OS in [linux, go32v2, win32, os2, freebsd, beos, netbsd,
699 amiga, atari, solaris, qnx, netware, openbsd, wdosx,
700 palmos, macosclassic, darwin, emx, watcom, morphos, netwlibc,
701 win64, wince, gba,nds, embedded, symbian, haiku, {iphonesim,}
702 aix, java, {android,} nativent, msdos, wii] then
703 begin
704 ExecutableNameExt := ExecutableName + ExeExtensionOS(OS);
705 ExecutableNameFull := OutputPath + ExecutableNameExt;
706 Pack.Add(ExecutableNameFull, ExecutableNameExt, UnixPermissionsMatter);
707 end;
708 end;
709
710 procedure AddExternalLibraries;
711 var
712 List: TCastleStringList;
713 FileName: String;
714 begin
715 List := TCastleStringList.Create;
716 try
717 ExternalLibraries(OS, CPU, Manifest.ProjectDependencies, List);
718 for FileName in List do
719 Pack.Add(FileName, ExtractFileName(FileName));
720 finally FreeAndNil(List) end;
721 end;
722
723 { How the targets are detected (at build (right here) and inside the compiled application
724 (in Platform implementation)) is a bit complicated.
725
726 - nintendo-switch:
727
728 At build: building for [[Nintendo Switch]] using CGE build tool with --target=nintendo-switch .
729
730 Inside the application: if code was compiled with CASTLE_NINTENDO_SWITCH.
731
732 - Android
733
734 When OS is Android (currently possible values: Android/Arm, Android/Aarch64), and it is *not* detected as _Nintendo Switch_ (for internal reasons, right now _Nintendo Switch_ is also treated as Android by FPC).
735
736 This logic is used both at build, and inside the application.
737
738 - iOS: When
739 (OS is iPhoneSim) or
740 (FPC >= 3.2.2 and OS = iOS) or
741 (FPC < 3.2.2 and OS/architecture are Darwin/Arm or Darwin/Aarch64).
742
743 This logic is used inside the application.
744 At build, it is simpler, as our build tool just says "darwin is not iOS"
745 (just like FPC >= 3.2.2 says) to support new macOS 11 (desktop on arm).
746
747 - desktop: everything else.
748 }
749 function TargetPlatform: TCastlePlatform;
750 begin
751 case Target of
752 targetIOS: Result := cpIOS;
753 targetAndroid: Result := cpAndroid;
754 targetNintendoSwitch: Result := cpNintendoSwitch;
755 else // only targetCustom for now
756 begin
757 if OS = Android then
758 Result := cpAndroid
759 else
760 if OS in [iphonesim, iOS] then
761 Result := cpIOS
762 else
763 Result := cpDesktop;
764 end;
765 end;
766 end;
767
768 { Handle packaging using TPackageDirectory (to pfDirectory, pfZip, pfTarGz formats,
769 TPackageDirectory.Make will check it). }
770 procedure PackageDirectory(const PackageFormatFinal: TPackageFormatNoDefault);
771 var
772 I: Integer;
773 PackageFileName: string;
774 Files: TCastleStringList;
775 ExecutablePermission: Boolean;
776 begin
777 Pack := TPackageDirectory.Create(Name);
778 try
779 { executable is added 1st, since it's the most likely file
780 to not exist, so we'll fail earlier }
781 AddExecutable;
782 AddExternalLibraries;
783
784 Files := PackageFiles(false, TargetPlatform);
785 try
786 for I := 0 to Files.Count - 1 do
787 begin
788 ExecutablePermission := (Files.Objects[I] <> nil) and (TIncludePath(Files.Objects[I]).ExecutablePermission);
789 Pack.Add(Path + Files[I], Files[I], ExecutablePermission);
790 end;
791 finally FreeAndNil(Files) end;
792
793 Pack.AddDataInformation(TCastleManifest.DataName);
794
795 PackageFileName := PackageName(OS, CPU, PackageFormatFinal, PackageNameIncludeVersion);
796
797 Pack.Cpu := Cpu;
798 Pack.Manifest := Manifest;
799 Pack.Make(OutputPath, PackageFileName, PackageFormatFinal);
800 finally FreeAndNil(Pack) end;
801 end;
802
803 var
804 PackageFormatFinal: TPackageFormatNoDefault;
805 WantsIOSArchive: Boolean;
806 IOSArchiveType: TIosArchiveType;
807 begin
808 PackageFormatFinal := PackageFormatFinalize(Target, OS, CPU, PackageFormat);
809
810 Writeln(Format('Packaging project "%s" for %s (platform: %s).' + NL + 'Format: %s.', [
811 Name,
812 TargetCompleteToString(Target, OS, CPU),
813 PlatformToStr(TargetPlatform),
814 PackageFormatToString(PackageFormatFinal)
815 ]));
816
817 case PackageFormatFinal of
818 pfIosXcodeProject, pfIosArchiveDevelopment, pfIosArchiveAdHoc, pfIosArchiveAppStore:
819 begin
820 // set IOSExportMethod early, as it determines IOS_EXPORT_METHOD macro
821 WantsIOSArchive := PackageFormatWantsIOSArchive(PackageFormatFinal, IOSArchiveType, IOSExportMethod);
822 PackageIOS(Self, UpdateOnlyCode);
823 if WantsIOSArchive then
824 ArchiveIOS(Self, IOSArchiveType);
825 end;
826 pfAndroidApk, pfAndroidAppBundle:
827 begin
828 if Target = targetAndroid then
829 AndroidCPUS := DetectAndroidCPUS
830 else
831 AndroidCPUS := [CPU];
832 PackageAndroid(Self, OS, AndroidCPUS, Mode, PackageFormatFinal, PackageNameIncludeVersion);
833 end;
834 pfNintendoSwitchProject:
835 PackageNintendoSwitch(Self);
836 pfDirectory, pfZip, pfTarGz, pfDeb:
837 PackageDirectory(PackageFormatFinal);
838 pfMacAppBundle, pfMacAppBundleZip:
839 begin
840 CreateMacAppBundle(Self, OutputPath, false);
841 if PackageFormatFinal = pfMacAppBundleZip then
842 ZipMacAppBundle(Self, OutputPath, PackageName(OS, CPU, PackageFormatFinal, PackageNameIncludeVersion));
843 end;
844 {$ifndef COMPILER_CASE_ANALYSIS}
845 else raise EInternalError.Create('Unhandled PackageFormatFinal in DoPackage');
846 {$endif}
847 end;
848 end;
849
850 procedure TCastleProject.DoInstall(const Target: TTarget;
851 const OS: TOS; const CPU: TCPU; const Mode: TCompilationMode;
852 const PackageFormat: TPackageFormat;
853 const PackageNameIncludeVersion: Boolean);
854 var
855 PackageFormatFinal: TPackageFormatNoDefault;
856 begin
857 Writeln(Format('Installing project "%s" for %s.',
858 [Name, TargetCompleteToString(Target, OS, CPU)]));
859
860 PackageFormatFinal := PackageFormatFinalize(Target, OS, CPU, PackageFormat);
861
862 case PackageFormatFinal of
863 pfAndroidApk, pfAndroidAppBundle:
864 InstallAndroid(Self, Mode, PackageFormatFinal, PackageNameIncludeVersion);
865 else
866 raise Exception.Create('The "install" command is not useful for this target / OS / CPU right now. Install the application manually.');
867 end;
868 end;
869
870 procedure TCastleProject.DoRun(const Target: TTarget;
871 const OS: TOS; const CPU: TCPU;
872 const Params: TCastleStringList);
873
874 procedure MaybeUseWrapperToRun(var ExeName: String);
875 var
876 S: String;
877 begin
878 if OS in AllUnixOSes then
879 begin
880 S := Path + ChangeFileExt(ExecutableName, '') + '_run.sh';
881 if RegularFileExists(S) then
882 begin
883 ExeName := S;
884 Exit;
885 end;
886
887 S := Path + 'run.sh';
888 if RegularFileExists(S) then
889 begin
890 ExeName := S;
891 Exit;
892 end;
893 end;
894 end;
895
896 procedure MaybeUseWineToRun(var ExeName: String; const NewParams: TStrings);
897 var
898 WineExe: String;
899 begin
900 if (OS in AllWindowsOSes) and (DefaultOS in AllUnixOSes) then
901 begin
902 Writeln('Running Windows EXE on Unix, trying to use WINE.');
903
904 WineExe := '';
905 // try to find with suffix 32 or 64
906 case CPU of
907 i386: WineExe := FindExe('wine32');
908 x86_64: WineExe := FindExe('wine64');
909 else ;
910 end;
911 // try to use wine without a suffix
912 if WineExe = '' then
913 WineExe := FindExe('wine');
914
915 if WineExe <> '' then
916 begin
917 NewParams.Insert(0, ExeName);
918 ExeName := WineExe;
919 end;
920 end;
921 end;
922
923 procedure MaybeRunThroughMacAppBundle(var RunWorkingDir, ExeName: String; const NewParams: TStrings);
924 var
925 ExeInBundle: String;
926 begin
927 if (OS = Darwin) and Manifest.MacAppBundle then
928 begin
929 CreateMacAppBundle(Self, TempOutputPath(Path) + 'macos' + PathDelim, true, ExeInBundle);
930
931 RunWorkingDir := ExtractFilePath(ExeInBundle);
932 ExeName := ExeInBundle;
933
934 { Executing using "open" is also a reasonable option, this simulates more what Finder
935 is doing when double-clicking the application.
936 However
937 - it doesn't seem to have any benefit for us, over executing ExeInBundle directly
938 - it doesn't capture the stdout/stderr of the application.
939
940 ExeName := 'open';
941 NewParams.Insert(0, '--new');
942 NewParams.Insert(1, '--wait-apps');
943 NewParams.Insert(2, TempOutputPath(Path) + 'macos' + PathDelim + Name + '.app');
944 NewParams.Insert(3, '--args');
945 }
946 end;
947 end;
948
949 var
950 RunWorkingDir: String;
951 ExeName: string;
952 NewParams: TCastleStringList;
953 begin
954 Writeln(Format('Running project "%s" for %s.',
955 [Name, TargetCompleteToString(Target, OS, CPU)]));
956
957 if Target = targetIOS then
958 RunIOS(Self)
959 else
960 if (Target = targetAndroid) or (OS = Android) then
961 RunAndroid(Self)
962 else
963 if Target = targetCustom then
964 begin
965 ExeName := Path + ChangeFileExt(ExecutableName, ExeExtensionOS(OS));
966 RunWorkingDir := Path;
967
968 MaybeUseWrapperToRun(ExeName);
969 Writeln('Running ' + ExeName);
970 NewParams := TCastleStringList.Create;
971 try
972 NewParams.Assign(Params);
973 MaybeUseWineToRun(ExeName, NewParams);
974 MaybeRunThroughMacAppBundle(RunWorkingDir, ExeName, NewParams);
975 Flush(Output); // needed to see "Running Windows EXE on Unix, trying to use WINE." in right order in editor
976 { We set current path to Path, not OutputPath, because data/ subdirectory is under Path. }
977 RunCommandSimple(RunWorkingDir, ExeName, NewParams.ToArray, 'CASTLE_LOG', 'stdout');
978 finally FreeAndNil(NewParams) end;
979 end else
980 raise Exception.Create('The "run" command is not useful for this OS / CPU right now. Run the application manually.');
981 end;
982
983 procedure TCastleProject.DoPackageSource(const PackageFormat: TPackageFormat;
984 const PackageNameIncludeVersion: Boolean);
985 var
986 PackageFormatFinal: TPackageFormatNoDefault;
987 Pack: TPackageDirectory;
988 Files: TCastleStringList;
989 I: Integer;
990 PackageFileName: string;
991 Collector: TSourcePackageFiles;
992 ExecutablePermission: Boolean;
993 begin
994 Writeln(Format('Packaging source code of project "%s".', [Name]));
995
996 if PackageFormat = pfDefault then
997 PackageFormatFinal := pfZip
998 else
999 PackageFormatFinal := PackageFormat;
1000
1001 Pack := TPackageDirectory.Create(Name);
1002 try
1003 Collector := TSourcePackageFiles.Create(Self);
1004 try
1005 Collector.Run;
1006 Files := Collector.CollectedFiles;
1007 for I := 0 to Files.Count - 1 do
1008 begin
1009 ExecutablePermission := (Files.Objects[I] <> nil) and (TIncludePath(Files.Objects[I]).ExecutablePermission);
1010 Pack.Add(Path + Files[I], Files[I], ExecutablePermission);
1011 end;
1012 finally FreeAndNil(Collector) end;
1013
1014 PackageFileName := SourcePackageName(PackageNameIncludeVersion, PackageFormatFinal);
1015 Pack.Make(OutputPath, PackageFileName, PackageFormatFinal);
1016 finally FreeAndNil(Pack) end;
1017 end;
1018
1019 function TCastleProject.PackageName(const OS: TOS; const CPU: TCPU;
1020 const PackageFormat: TPackageFormatNoDefault;
1021 const PackageNameIncludeVersion: Boolean): string;
1022 begin
1023 Result := Name;
1024 if PackageNameIncludeVersion and (Version.DisplayValue <> '') then
1025 Result += '-' + Version.DisplayValue;
1026 Result += '-' + OSToString(OS) + '-' + CPUToString(CPU);
1027 case PackageFormat of
1028 pfZip, pfMacAppBundleZip: Result += '.zip';
1029 pfTarGz: Result += '.tar.gz';
1030 pfDeb: Result += '.deb';
1031 else ; // leave without extension for pfDirectory
1032 end;
1033 end;
1034
1035 function TCastleProject.SourcePackageName(const PackageNameIncludeVersion: Boolean;
1036 const PackageFormatFinal: TPackageFormatNoDefault): string;
1037 begin
1038 Result := Name;
1039 if PackageNameIncludeVersion and (Version.DisplayValue <> '') then
1040 Result += '-' + Version.DisplayValue;
1041 Result += '-src';
1042
1043 case PackageFormatFinal of
1044 pfZip : Result += '.zip';
1045 pfTarGz: Result += '.tar.gz';
1046 else raise Exception.CreateFmt('Package format "%s" not supported for source package', [
1047 PackageFormatToString(PackageFormatFinal)
1048 ]);
1049 end;
1050 end;
1051
1052 procedure TCastleProject.DeleteFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
1053 begin
1054 if Verbose then
1055 Writeln('Deleting ' + FileInfo.AbsoluteName);
1056 CheckDeleteFile(FileInfo.AbsoluteName);
1057 Inc(DeletedFiles);
1058 end;
1059
1060 function TCastleProject.NamePascal: string;
1061 begin
1062 Result := MakeProjectPascalName(Name);
1063 end;
1064
1065 procedure TCastleProject.GeneratedSourceFile(
1066 const TemplateRelativeUrl, TargetRelativePath, ErrorMessageMissingGameUnits: string;
1067 const CreateIfNecessary: boolean;
1068 out RelativeResult, AbsoluteResult: string);
1069 var
1070 TemplateFile: string;
1071 begin
1072 AbsoluteResult := TempOutputPath(Path, CreateIfNecessary) + TargetRelativePath;
1073 if CreateIfNecessary then
1074 begin
1075 TemplateFile := UriToFilenameSafe('castle-data:/' +TemplateRelativeUrl);
1076 if Manifest.GameUnits = '' then
1077 raise Exception.Create(ErrorMessageMissingGameUnits);
1078 ExtractTemplateFile(TemplateFile, AbsoluteResult, TemplateRelativeUrl, true);
1079 end;
1080 // This may not be true anymore, if user changes OutputPathBase
1081 // if not IsPrefix(Path, AbsoluteResult, true) then
1082 // raise EInternalError.CreateFmt('Something is wrong with the temporary source location "%s", it is not within the project "%s"',
1083 // [AbsoluteResult, Path]);
1084 RelativeResult := PrefixRemove(Path, AbsoluteResult, true);
1085 end;
1086
1087 procedure TCastleProject.GeneratedSourceFile(
1088 const TemplateRelativeUrl, TargetRelativePath, ErrorMessageMissingGameUnits: string;
1089 const CreateIfNecessary: boolean);
1090 var
1091 RelativeResult, AbsoluteResult: string;
1092 begin
1093 GeneratedSourceFile(TemplateRelativeUrl, TargetRelativePath, ErrorMessageMissingGameUnits,
1094 CreateIfNecessary, RelativeResult, AbsoluteResult);
1095 // just ignore RelativeResult, AbsoluteResult output values
1096 end;
1097
1098 function TCastleProject.AndroidSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
1099
1100 procedure InvalidAndroidSource(const FinalAndroidSource: string);
1101 begin
1102 raise Exception.Create('The android source library in "' + FinalAndroidSource + '" must export the necessary JNI functions for our integration to work. See the examples in "castle-engine/tools/build-tool/data/android/library_template_xxx.lpr".' + NL + 'It''s simplest to fix this error by removing the "android_source" from CastleEngineManifest.xml, and using only the "game_units" attribute in CastleEngineManifest.xml. Then the correct Android code will be auto-generated for you.');
1103 end;
1104
1105 const
1106 ErrorMessageMissingGameUnits = 'You must specify game_units="..." in the CastleEngineManifest.xml to enable build tool to create an Android project. Alternatively, you can specify android_source="..." in the CastleEngineManifest.xml, to explicitly indicate the Android library source code.';
1107 var
1108 AndroidSourceContents, RelativeResult, AbsoluteResult, TemplateRelativeUrl: String;
1109 begin
1110 { calculate RelativeResult, AbsoluteResult }
1111 if Manifest.AndroidSource <> '' then
1112 begin
1113 RelativeResult := Manifest.AndroidSource;
1114 AbsoluteResult := Path + RelativeResult;
1115 end else
1116 begin
1117 TemplateRelativeUrl := 'android/library_template_integrated.lpr';
1118 GeneratedSourceFile(TemplateRelativeUrl,
1119 'android' + PathDelim + NamePascal + '_android.lpr',
1120 ErrorMessageMissingGameUnits,
1121 CreateIfNecessary, RelativeResult, AbsoluteResult);
1122 GeneratedSourceFile('castleautogenerated_template.pas',
1123 'android' + PathDelim + 'castleautogenerated.pas',
1124 ErrorMessageMissingGameUnits,
1125 CreateIfNecessary);
1126 end;
1127
1128 // for speed, do not check correctness if CreateIfNecessary = false
1129 if CreateIfNecessary then
1130 begin
1131 { check Android lpr file correctness.
1132 For now, do it even if we generated Android project from our own template
1133 (when AndroidSource = ''), to check our own work. }
1134 AndroidSourceContents := FileToString(AbsoluteResult);
1135 if Pos('ANativeActivity_onCreate', AndroidSourceContents) = 0 then
1136 InvalidAndroidSource(AbsoluteResult);
1137 if Pos('Java_io_castleengine_MainActivity_jniMessage', AndroidSourceContents) = 0 then
1138 InvalidAndroidSource(AbsoluteResult);
1139 end;
1140
1141 if AbsolutePath then
1142 Result := AbsoluteResult
1143 else
1144 Result := RelativeResult;
1145 end;
1146
1147 function TCastleProject.IOSSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
1148 const
1149 ErrorMessageMissingGameUnits = 'You must specify game_units="..." in the CastleEngineManifest.xml to enable build tool to create an iOS project. Alternatively, you can specify ios_source="..." in the CastleEngineManifest.xml, to explicitly indicate the iOS library source code.';
1150 var
1151 RelativeResult, AbsoluteResult: string;
1152 begin
1153 if Manifest.IOSSource <> '' then
1154 begin
1155 RelativeResult := Manifest.IOSSource;
1156 AbsoluteResult := Path + RelativeResult;
1157 end else
1158 begin
1159 GeneratedSourceFile('ios/library_template.lpr',
1160 'ios' + PathDelim + NamePascal + '_ios.lpr',
1161 ErrorMessageMissingGameUnits,
1162 CreateIfNecessary, RelativeResult, AbsoluteResult);
1163 GeneratedSourceFile('castleautogenerated_template.pas',
1164 'ios' + PathDelim + 'castleautogenerated.pas',
1165 ErrorMessageMissingGameUnits,
1166 CreateIfNecessary);
1167 end;
1168
1169 if AbsolutePath then
1170 Result := AbsoluteResult
1171 else
1172 Result := RelativeResult;
1173 end;
1174
1175 function TCastleProject.NXSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
1176 const
1177 ErrorMessageMissingGameUnits = 'You must specify game_units="..." in the CastleEngineManifest.xml to enable build tool to create a Nintendo Switch project.';
1178 var
1179 RelativeResult, AbsoluteResult: string;
1180 begin
1181 { Without this, we would also have an error, but NxNotSupported makes
1182 nicer error message. }
1183 NxNotSupported;
1184
1185 GeneratedSourceFile('nintendo_switch/library_template.lpr',
1186 'nintendo_switch' + PathDelim + 'castle_nx.lpr',
1187 ErrorMessageMissingGameUnits,
1188 CreateIfNecessary, RelativeResult, AbsoluteResult);
1189 GeneratedSourceFile('castleautogenerated_template.pas',
1190 'nintendo_switch' + PathDelim + 'castleautogenerated.pas',
1191 ErrorMessageMissingGameUnits,
1192 CreateIfNecessary);
1193
1194 if AbsolutePath then
1195 Result := AbsoluteResult
1196 else
1197 Result := RelativeResult;
1198 end;
1199
1200 function TCastleProject.StandaloneSourceFile(const AbsolutePath, CreateIfNecessary: boolean): string;
1201 const
1202 ErrorMessageMissingGameUnits = 'You must specify game_units or standalone_source in the CastleEngineManifest.xml to compile for the standalone platform';
1203 var
1204 RelativeResult, AbsoluteResult: string;
1205 begin
1206 if Manifest.StandaloneSource <> '' then
1207 begin
1208 RelativeResult := Manifest.StandaloneSource;
1209 AbsoluteResult := Path + RelativeResult;
1210 end else
1211 begin
1212 GeneratedSourceFile('standalone/program_template.dpr',
1213 'standalone' + PathDelim + NamePascal + '_standalone.dpr',
1214 ErrorMessageMissingGameUnits,
1215 CreateIfNecessary, RelativeResult, AbsoluteResult);
1216 GeneratedSourceFile('castleautogenerated_template.pas',
1217 'standalone' + PathDelim + 'castleautogenerated.pas',
1218 ErrorMessageMissingGameUnits,
1219 CreateIfNecessary);
1220 end;
1221
1222 if AbsolutePath then
1223 Result := AbsoluteResult
1224 else
1225 Result := RelativeResult;
1226 end;
1227
1228 function TCastleProject.AndroidLibraryFile(const CPU: TCPU;
1229 const AbsolutePath: boolean): string;
1230 var
1231 Ext: String;
1232 begin
1233 Ext := '.so';
1234 if CPU <> cpuNone then
1235 Ext := '_' + CPUToString(CPU) + Ext;
1236 Result := InsertLibPrefix(ChangeFileExt(AndroidSourceFile(AbsolutePath, false), Ext));
1237 end;
1238
1239 function TCastleProject.IOSLibraryFile(const AbsolutePath: boolean): string;
1240 begin
1241 Result := InsertLibPrefix(ChangeFileExt(IOSSourceFile(AbsolutePath, false), '.a'));
1242 end;
1243
1244 function TCastleProject.NXLibraryFile(const AbsolutePath: boolean): string;
1245 begin
1246 Result := InsertLibPrefix(ChangeFileExt(NXSourceFile(AbsolutePath, false), '.a'));
1247 end;
1248
1249 procedure TCastleProject.DoClean;
1250
1251 { Delete a file, given as absolute FileName. }
1252 procedure TryDeleteAbsoluteFile(FileName: string);
1253 begin
1254 if RegularFileExists(FileName) then
1255 begin
1256 if Verbose then
1257 Writeln('Deleting ' + FileName);
1258 CheckDeleteFile(FileName);
1259 Inc(DeletedFiles);
1260 end;
1261 end;
1262
1263 { Delete a file, given as FileName relative to project root. }
1264 procedure TryDeleteFile(FileName: string);
1265 begin
1266 TryDeleteAbsoluteFile(Path + FileName);
1267 end;
1268
1269 procedure DeleteFilesRecursive(const Mask: string);
1270 begin
1271 FindFiles(Path, Mask, false, @DeleteFoundFile, [ffRecursive]);
1272 end;
1273
1274 procedure DeleteExternalLibraries(const LibrariesOutputPath: String; const OS: TOS; const CPU: TCPU);
1275 var
1276 List: TCastleStringList;
1277 OutputFile, FileName: String;
1278 begin
1279 List := TCastleStringList.Create;
1280 try
1281 { CheckFilesExistence parameter for ExternalLibraries may be false.
1282 This way you can run "castle-engine clean" without setting $CASTLE_ENGINE_PATH . }
1283 ExternalLibraries(OS, CPU, Manifest.ProjectDependencies, List, false);
1284 for FileName in List do
1285 begin
1286 OutputFile := LibrariesOutputPath + ExtractFileName(FileName);
1287 TryDeleteFile(OutputFile);
1288 end;
1289 finally FreeAndNil(List) end;
1290 end;
1291
1292 var
1293 OS: TOS;
1294 CPU: TCPU;
1295 OutputP: string;
1296 begin
1297 { delete OutputPath first, this also removes many files
1298 (but RemoveNonEmptyDir does not count them) }
1299 OutputP := TempOutputPath(Path, false);
1300 if DirectoryExists(OutputP) then
1301 begin
1302 RemoveNonEmptyDir(OutputP);
1303 Writeln('Deleted ', OutputP);
1304 end;
1305
1306 DeletedFiles := 0;
1307
1308 TryDeleteFile(ChangeFileExt(ExecutableName, ''));
1309 TryDeleteFile(ChangeFileExt(ExecutableName, '.exe'));
1310 TryDeleteFile(ChangeFileExt(ExecutableName, '.log'));
1311
1312 if Manifest.AndroidSource <> '' then
1313 begin
1314 TryDeleteAbsoluteFile(AndroidLibraryFile(arm));
1315 TryDeleteAbsoluteFile(AndroidLibraryFile(aarch64));
1316 end;
1317 if Manifest.IOSSource <> '' then
1318 TryDeleteAbsoluteFile(IOSLibraryFile);
1319
1320 for OS in TOS do
1321 for CPU in TCPU do
1322 if OSCPUSupported[OS, CPU] then
1323 begin
1324 { packages created by DoPackage? Or not, it's safer to not remove them. }
1325 // TryDeleteFile(PackageName(OS, CPU));
1326
1327 DeleteExternalLibraries(ExtractFilePath(ExecutableName), OS, CPU);
1328 end;
1329
1330 { compilation and editor backups }
1331 DeleteFilesRecursive('*~'); // editor backup, e.g. Emacs
1332 DeleteFilesRecursive('*.ppu'); // compilation
1333 DeleteFilesRecursive('*.o'); // compilation
1334 DeleteFilesRecursive('*.or'); // compilation
1335 DeleteFilesRecursive('*.compiled'); // Lazarus compilation
1336 DeleteFilesRecursive('*.rst'); // resource strings
1337 DeleteFilesRecursive('*.rsj'); // resource strings
1338 TryDeleteFile('castle-auto-generated-resources.res');
1339
1340 Writeln('Deleted ', DeletedFiles, ' files');
1341 end;
1342
1343 procedure TCastleProject.DoAutoGenerateTextures;
1344 begin
1345 AutoGenerateTextures(Self);
1346 end;
1347
1348 procedure TCastleProject.DoAutoGenerateClean(const CleanAll: Boolean);
1349 begin
1350 if CleanAll then
1351 AutoGenerateCleanAll(Self)
1352 else
1353 AutoGenerateCleanUnused(Self);
1354 end;
1355
1356 function TCastleProject.ExplicitStandaloneFile(const Ext: String): String;
1357 begin
1358 if Manifest.StandaloneSource <> '' then
1359 begin
1360 { If we wanted to generate dpr/lpr file, then just use standalone_source value from manifest
1361 instead, preserving extension (whether it is dpr,lpr or something else). }
1362 if (Ext = '.dpr') or
1363 (Ext = '.lpr') then
1364 Result := Manifest.StandaloneSource
1365 else
1366 Result := ChangeFileExt(Manifest.StandaloneSource, Ext);
1367 end else
1368 Result := NamePascal + '_standalone' + Ext;
1369 end;
1370
1371 procedure TCastleProject.DoGenerateProgram(const GuidFromName: Boolean);
1372
1373 procedure Generate(const TemplateRelativePath, TargeRelativePath: string);
1374 var
1375 TemplateFile, TargetFile: string;
1376 begin
1377 TemplateFile := UriToFilenameSafe('castle-data:/' +TemplateRelativePath);
1378 TargetFile := Path + TargeRelativePath;
1379 ExtractTemplateFile(TemplateFile, TargetFile, TemplateRelativePath, true);
1380 Writeln('Generated ', ExtractRelativePath(Path, TargetFile));
1381 end;
1382
1383 procedure GenerateStandaloneProgram(const Ext: string);
1384 var
1385 TargetFile: String;
1386 begin
1387 TargetFile := ExplicitStandaloneFile(Ext);
1388 Generate(
1389 'standalone/program_template' + Ext,
1390 TargetFile);
1391 end;
1392
1393 begin
1394 FGuidFromName := GuidFromName;
1395
1396 { Generate castleautogenerated.pas before generating LPI,
1397 because LPI contains list of units that should include castleautogenerated.pas. }
1398 Generate('castleautogenerated_template.pas', 'castleautogenerated.pas');
1399
1400 if Manifest.GameUnits = '' then
1401 begin
1402 WritelnWarning('CastleEngineManifest.xml does not specify game_units="...".' + NL +
1403 ' We cannot auto-generate main Pascal program (dpr, lpr) in this case.' + NL +
1404 ' We will still auto-generate other project files, assuming you have hand-crafted dpr/lpr.');
1405 end else
1406 GenerateStandaloneProgram('.dpr');
1407
1408 GenerateStandaloneProgram('.lpi');
1409 GenerateStandaloneProgram('.dproj');
1410
1411 if (Manifest.StandaloneSource <> '') and
1412 (not SameText(ExtractFileExt(Manifest.StandaloneSource), '.dpr')) then
1413 WritelnWarning('Main program (standalone_source) does not have ".dpr" extension.' + NL +
1414 ' It will not be possible to compile this project with Delphi.' + NL +
1415 ' We recommend changing the standalone_source extension to ".dpr".' + NL +
1416 ' The ".dpr" extension will work with both FPC/Lazarus and Delphi.');
1417 end;
1418
1419 procedure TCastleProject.DoEditor;
1420 begin
1421 DoEditorRebuildIfNeeded;
1422 DoEditorRun(0);
1423 end;
1424
1425 procedure TCastleProject.DoEditorRebuildIfNeeded;
1426 var
1427 CgePath, EditorPath: String;
1428 begin
1429 if Trim(Manifest.EditorUnits) <> '' then
1430 begin
1431 { Check CastleEnginePath, since without this, compiling custom castle-editor.lpi
1432 will always fail. }
1433 CgePath := CastleEnginePath;
1434 if CgePath = '' then
1435 raise Exception.Create(SCannotFindCgePath);
1436
1437 // create custom editor directory
1438 EditorPath := TempOutputPath(Path) + 'editor' + PathDelim;
1439 { Do not remove previous directory contents,
1440 allows to reuse previous lazbuild compilation results.
1441 Just silence ExtractTemplate warnings when overriding. }
1442 ExtractTemplate('custom_editor_template/', EditorPath, true);
1443
1444 // use lazbuild to compile CGE packages and CGE editor
1445 RunLazbuild(Path, [CgePath + 'packages/castle_base.lpk']);
1446 RunLazbuild(Path, [CgePath + 'packages/castle_components.lpk']);
1447 RunLazbuild(Path, [CgePath + 'packages/castle_editor_components.lpk']);
1448 RunLazbuild(Path, [EditorPath + 'castle_editor_automatic_package.lpk']);
1449 RunLazbuild(Path, [EditorPath + 'castle_editor.lpi']);
1450 end;
1451 end;
1452
1453 procedure TCastleProject.DoEditorRun(const WaitForProcessId: TProcessId);
1454
1455 {$ifdef UNIX}
1456 { Copied from FPC packages/fcl-extra/src/unix/daemonapp.inc .
1457 We need to become a daemon to reliably keep working even if parent process
1458 terminates. Otherwise restarting CGE editor after rebuilding new editor
1459 fails. }
1460 const
1461 SErrFailedToFork = 'Failed to fork daemon process.';
1462
1463 procedure DaemonizeProgram;
1464 var
1465 pid, sid: TPid;
1466 begin
1467 pid := FpFork;
1468 if (pid<0) then
1469 raise Exception.Create(SErrFailedToFork);
1470 if pid>0 then
1471 begin
1472 // We are now in the main program, which has to terminate
1473 FpExit(0);
1474 end
1475 else
1476 begin
1477 // Here we are in the daemonized proces
1478 sid := FpSetsid;
1479 if sid < 0 then
1480 raise Exception.Create(SErrFailedToFork);
1481 // Reset the file-mask
1482 FpUmask(0);
1483 // Change the current directory, to avoid locking the current directory
1484 chdir('/');
1485 FpClose(StdInputHandle);
1486 FpClose(StdOutputHandle);
1487 FpClose(StdErrorHandle);
1488 end;
1489 end;
1490 {$endif}
1491
1492 { Copy external libraries to LibrariesOutputPath. }
1493 procedure AddExternalLibraries(const LibrariesOutputPath: String);
1494 var
1495 List: TCastleStringList;
1496 OutputFile, FileName: String;
1497 EditorProjectDependencies: TProjectDependencies;
1498 begin
1499 List := TCastleStringList.Create;
1500 try
1501 EditorProjectDependencies := TProjectDependencies.Create;
1502 try
1503 EditorProjectDependencies.Dependencies := [
1504 // to read fonts
1505 depFreetype,
1506 // to read PNG
1507 depZlib, depPng,
1508 // to play sound
1509 depSound,
1510 // to read OggVorbis
1511 depOggVorbis,
1512 // not used now by the editor -- but likely will be used in the future, e.g. to check for new version by HTTPS query.
1513 depHttps
1514 ];
1515 ExternalLibraries(DefaultOS, DefaultCPU, EditorProjectDependencies, List);
1516 for FileName in List do
1517 begin
1518 OutputFile := LibrariesOutputPath + ExtractFileName(FileName);
1519 WritelnVerbose('Copying library to ' + OutputFile);
1520 CheckCopyFile(FileName, OutputFile);
1521 end;
1522 finally FreeAndNil(EditorProjectDependencies) end;
1523 finally FreeAndNil(List) end;
1524 end;
1525
1526 var
1527 EditorPath: String;
1528
1529 function GetEditorExe(const Suffix: String): String;
1530 begin
1531 Result := EditorPath + 'castle-editor' + Suffix + ExeExtension;
1532 {$ifdef DARWIN}
1533 // on macOS, run new editor through app bundle
1534 Result := Result + '.app/Contents/MacOS/castle-editor' + Suffix;
1535 {$endif}
1536 end;
1537
1538 var
1539 EditorExe{$ifndef DARWIN}, NewEditorExe{$endif}: String;
1540 NewEnvironment: TStringList;
1541 begin
1542 {$ifdef UNIX}
1543 DaemonizeProgram;
1544 {$endif}
1545
1546 if WaitForProcessId <> 0 then
1547 WaitForProcessExit(WaitForProcessId);
1548
1549 NewEnvironment := nil;
1550
1551 if Trim(Manifest.EditorUnits) = '' then
1552 begin
1553 EditorExe := FindExeCastleTool('castle-editor');
1554 if EditorExe = '' then
1555 raise Exception.Create('Cannot find "castle-editor" program on $PATH or within $CASTLE_ENGINE_PATH/bin directory.');
1556 end else
1557 begin
1558 // here EditorPath and EditorExe are calculated like in DoEditorRebuildIfNeeded
1559 EditorPath := TempOutputPath(Path) + 'editor' + PathDelim;
1560
1561 { This can be done only once previous editor process finished,
1562 to not block EXE and DLL files on Windows. }
1563 AddExternalLibraries(EditorPath);
1564
1565 {$ifdef DARWIN}
1566 { on macOS, run new editor through app bundle.
1567 We never rename it (no need to, and this is simplest), it always remains with -new suffix). }
1568 EditorExe := GetEditorExe('-new');
1569 {$else}
1570 NewEditorExe := GetEditorExe('-new');
1571 EditorExe := GetEditorExe('');
1572 { Rename NewEditorExe -> EditorExe.
1573 If you use DoEditorRebuildIfNeeded + DoEditorRun, the NewEditorExe must exist.
1574 But if you directly use DoEditorRun (e.g. using "Run Last Editor" from CGE editor)
1575 then NewEditorExe may not exist. }
1576 if RegularFileExists(NewEditorExe) then
1577 CheckRenameFile(NewEditorExe, EditorExe);
1578 {$endif}
1579
1580 { When running custom editor build, we must make sure it can find CGE location,
1581 in particular so it can find editor's data (which means InternalCastleDesignData
1582 must be useful, and it must be able to load gfx stuff like gizmo images and
1583 layer_physics_simulation.castle-user-interface).
1584
1585 So it is not sufficient that only build tool can find the CGE path (and use it for compilation).
1586 CGE editor must be able to find it too.
1587
1588 Note that in usual user installation (when CASTLE_ENGINE_PATH is undefined):
1589 - Build tool will be inside CGE/bin/ and can detect CGE location reliably
1590 based on exe name.
1591 - OTOH editor, when it is a custom editor build, is in project's directory and will
1592 not be able to detect CGE location reliably based on exe name.
1593 This means build tool must pass it to CGE editor.
1594
1595 Relevant bugreport: https://forum.castle-engine.io/t/castle-lines-2d/701/5
1596 }
1597 if (CastleEnginePath <> '') and
1598 (GetEnvironmentVariable('CASTLE_ENGINE_PATH') = '') then
1599 begin
1600 NewEnvironment := EnvironmentStrings;
1601 NewEnvironment.Values['CASTLE_ENGINE_PATH'] := CastleEnginePath;
1602 end;
1603 end;
1604
1605 { Regardless of all above conditions (
1606 whether Manifest.EditorUnits is empty or not,
1607 whether we renamed NewEditorExe or not,
1608 whether it's in macOS bundle or not)... EditorExe must exist. }
1609 if not RegularFileExists(EditorExe) then
1610 raise Exception.Create('Editor should be compiled, but we cannot find file "' + EditorExe + '"');
1611
1612 { Running with CurrentDirectory = Path, so that at least on Windows
1613 editor can automatically use the DLL files inside the project, like libeffekseer.dll.
1614
1615 TODO: In the long run, this should change to use EditorPath as current path.
1616 Running editor should not "lock" the project DLLs on Windows.
1617 We should have a system of services for desktop, to manage DLLs, including custom
1618 DLLs like Effekseer and FMOD. }
1619 RunCommandNoWait(Path, EditorExe, [ManifestFile], [], NewEnvironment);
1620 end;
1621
1622 procedure TCastleProject.DoOutput(const OutputKey: String);
1623 begin
1624 case OutputKey of
1625 'executable-name': Writeln(ExecutableName);
1626 'name': Writeln(Name);
1627 'pascal-name': Writeln(NamePascal);
1628 'search-paths': Writeln(Manifest.SearchPaths.Text);
1629 'version': Writeln(Manifest.Version.DisplayValue);
1630 'version-code': Writeln(Manifest.Version.Code);
1631 else raise Exception.CreateFmt('Unsupported output key: "%s"', [OutputKey]);
1632 end;
1633 end;
1634
1635 procedure TCastleProject.AddMacrosAndroid(const Macros: TStringStringMap);
1636 const
1637 AndroidScreenOrientation: array [TScreenOrientation] of string =
1638 ('unspecified', 'sensorLandscape', 'sensorPortrait');
1639
1640 AndroidScreenOrientationFeature: array [TScreenOrientation] of string =
1641 ('',
1642 '<uses-feature android:name="android.hardware.screen.landscape"/>',
1643 '<uses-feature android:name="android.hardware.screen.portrait"/>');
1644
1645 function AndroidActivityTheme: string;
1646 begin
1647 if FullscreenImmersive then
1648 Result := 'android:Theme.NoTitleBar.Fullscreen'
1649 else
1650 Result := 'android:Theme.NoTitleBar';
1651 end;
1652
1653 function AndroidActivityLoadLibraries: string;
1654 begin
1655 { Some Android devices work without this clause, some don't.
1656 TODO: This should be moved to CastleEngineService.xml, not hardcoded here. }
1657 Result := '';
1658 if depSound in Dependencies then
1659 Result += 'safeLoadLibrary("openal");' + NL;
1660 if depOggVorbis in Dependencies then
1661 Result += 'safeLoadLibrary("tremolo");' + NL;
1662 if depFreetype in Dependencies then
1663 Result += 'safeLoadLibrary("freetype");' + NL;
1664 if depPng in Dependencies then
1665 Result += 'safeLoadLibrary("png");' + NL;
1666 { Necessary, otherwise FMOD is not initialized correctly, and reports
1667 [ERR] FMOD_JNI_GetEnv : JNI_OnLoad has not run, should have occurred during System.LoadLibrary.
1668 and reports internal error even from FMOD_System_Create. }
1669 if AndroidServices.HasService('fmod') then
1670 Result += 'safeLoadLibrary("fmod");' + NL;
1671 end;
1672
1673 { Android ABI list like '"armeabi-v7a","arm64-v8a"' }
1674 function AndroidAbiList: String;
1675 var
1676 CPU: TCPU;
1677 begin
1678 Result := '';
1679 for CPU in AndroidCPUS do
1680 Result := SAppendPart(Result, ',', '"' + CPUToAndroidArchitecture(CPU) + '"');
1681 end;
1682
1683 { Android ABI list like 'armeabi-v7a arm64-v8a' }
1684 function AndroidAbiListMakefile: String;
1685 var
1686 CPU: TCPU;
1687 begin
1688 Result := '';
1689 for CPU in AndroidCPUS do
1690 Result := SAppendPart(Result, ' ', CPUToAndroidArchitecture(CPU));
1691 end;
1692
1693 var
1694 AndroidLibraryName: string;
1695 Service: TService;
1696 begin
1697 AndroidLibraryName := ChangeFileExt(ExtractFileName(AndroidSourceFile(true, false)), '');
1698 Macros.Add('ANDROID_LIBRARY_NAME' , AndroidLibraryName);
1699 Macros.Add('ANDROID_ACTIVITY_THEME' , AndroidActivityTheme);
1700 Macros.Add('ANDROID_SCREEN_ORIENTATION' , AndroidScreenOrientation[ScreenOrientation]);
1701 Macros.Add('ANDROID_SCREEN_ORIENTATION_FEATURE' , AndroidScreenOrientationFeature[ScreenOrientation]);
1702 Macros.Add('ANDROID_ACTIVITY_LOAD_LIBRARIES' , AndroidActivityLoadLibraries);
1703 Macros.Add('ANDROID_COMPILE_SDK_VERSION' , IntToStr(AndroidCompileSdkVersion));
1704 Macros.Add('ANDROID_MIN_SDK_VERSION' , IntToStr(AndroidMinSdkVersion));
1705 Macros.Add('ANDROID_TARGET_SDK_VERSION' , IntToStr(AndroidTargetSdkVersion));
1706 Macros.Add('ANDROID_ASSOCIATE_DOCUMENT_TYPES' , AssociateDocumentTypes.ToIntentFilter);
1707 Macros.Add('ANDROID_LOG_TAG' , Copy(Name, 1, MaxAndroidTagLength));
1708 Macros.Add('ANDROID_ABI_LIST' , AndroidAbiList);
1709 Macros.Add('ANDROID_ABI_LIST_MAKEFILE' , AndroidAbiListMakefile);
1710
1711 for Service in AndroidServices do
1712 ParametersAddMacros(Macros, Service.Parameters, 'ANDROID.' + Service.Name + '.');
1713 end;
1714
1715 procedure TCastleProject.AddMacrosIOS(const Macros: TStringStringMap);
1716 const
1717 IOSScreenOrientation: array [TScreenOrientation] of string = (
1718 #9#9'<string>UIInterfaceOrientationPortrait</string>' + NL +
1719 #9#9'<string>UIInterfaceOrientationPortraitUpsideDown</string>' + NL +
1720 #9#9'<string>UIInterfaceOrientationLandscapeLeft</string>' + NL +
1721 #9#9'<string>UIInterfaceOrientationLandscapeRight</string>' + NL,
1722
1723 #9#9'<string>UIInterfaceOrientationLandscapeLeft</string>' + NL +
1724 #9#9'<string>UIInterfaceOrientationLandscapeRight</string>' + NL,
1725
1726 #9#9'<string>UIInterfaceOrientationPortrait</string>' + NL +
1727 #9#9'<string>UIInterfaceOrientationPortraitUpsideDown</string>' + NL
1728 );
1729
1730 IOSCapabilityEnable =
1731 #9#9#9#9#9#9#9'com.apple.%s = {' + NL +
1732 #9#9#9#9#9#9#9#9'enabled = 1;' + NL +
1733 #9#9#9#9#9#9#9'};' + NL;
1734
1735 { QualifiedName for iOS: either qualified_name, or ios.override_qualified_name. }
1736 function IOSQualifiedName: string;
1737 begin
1738 if Manifest.IOSOverrideQualifiedName <> '' then
1739 Result := Manifest.IOSOverrideQualifiedName
1740 else
1741 Result := QualifiedName;
1742 end;
1743
1744 procedure LaunchImageStoryboardInitialize;
1745 var
1746 Img: TCastleImage;
1747 begin
1748 if Manifest.LaunchImageStoryboard.Path <> '' then
1749 begin
1750 if ExtractFileExt(Manifest.LaunchImageStoryboard.Path) <> '.png' then
1751 raise Exception.CreateFmt('Launch image storyboard must be a PNG file, but is "%s"', [
1752 Manifest.LaunchImageStoryboard.Path
1753 ]);
1754 Img := LoadImage(Manifest.LaunchImageStoryboard.Path);
1755 try
1756 FLaunchImageStoryboardWidth := Img.Width;
1757 FLaunchImageStoryboardHeight := Img.Height;
1758 finally FreeAndNil(Img) end;
1759 end;
1760 end;
1761
1762 var
1763 InfoPList, IOSTargetAttributes, IOSRequiredDeviceCapabilities, IOSSystemCapabilities: string;
1764 Service: TService;
1765 IOSVersion: TProjectVersion;
1766 GccPreprocessorDefinitions: String;
1767 begin
1768 InfoPList := '';
1769
1770 // first time: initialize launch image storyboard
1771 if not FLaunchImageStoryboardInitialized then
1772 begin
1773 FLaunchImageStoryboardInitialized := true;
1774 LaunchImageStoryboardInitialize;
1775 end;
1776 // define macros related to launch image storyboard
1777 if IOSHasLaunchImageStoryboard then
1778 begin
1779 Macros.Add('IOS_LAUNCH_IMAGE_WIDTH' , IntToStr(FLaunchImageStoryboardWidth));
1780 Macros.Add('IOS_LAUNCH_IMAGE_HEIGHT', IntToStr(FLaunchImageStoryboardHeight));
1781 Macros.Add('IOS_LAUNCH_IMAGE_DISPLAY_WIDTH' , IntToStr(Round(256 * Manifest.LaunchImageStoryboard.Scale)));
1782 Macros.Add('IOS_LAUNCH_IMAGE_DISPLAY_HEIGHT', IntToStr(Round(256 * Manifest.LaunchImageStoryboard.Scale)));
1783 Macros.Add('IOS_LAUNCH_BACKGROUND_RED' , FloatToStrDot(Manifest.LaunchImageStoryboard.BackgroundColor[0]));
1784 Macros.Add('IOS_LAUNCH_BACKGROUND_GREEN', FloatToStrDot(Manifest.LaunchImageStoryboard.BackgroundColor[1]));
1785 Macros.Add('IOS_LAUNCH_BACKGROUND_BLUE' , FloatToStrDot(Manifest.LaunchImageStoryboard.BackgroundColor[2]));
1786 Macros.Add('IOS_LAUNCH_BACKGROUND_ALPHA', FloatToStrDot(Manifest.LaunchImageStoryboard.BackgroundColor[3]));
1787 InfoPList := SAppendPart(InfoPList, NL,
1788 '<key>UILaunchStoryboardName</key> <string>Launch Screen</string>');
1789 end;
1790
1791 if Manifest.IOSOverrideVersion <> nil then
1792 IOSVersion := Manifest.IOSOverrideVersion
1793 else
1794 IOSVersion := Manifest.Version;
1795 Macros.Add('IOS_QUALIFIED_NAME', IOSQualifiedName);
1796 Macros.Add('IOS_VERSION', IOSVersion.DisplayValue);
1797 Macros.Add('IOS_VERSION_CODE', IntToStr(IOSVersion.Code));
1798 Macros.Add('IOS_LIBRARY_BASE_NAME' , ExtractFileName(IOSLibraryFile));
1799 Macros.Add('IOS_STATUSBAR_HIDDEN', Iff(FullscreenImmersive, 'YES', 'NO'));
1800 Macros.Add('IOS_SCREEN_ORIENTATION', IOSScreenOrientation[ScreenOrientation]);
1801 InfoPList := SAppendPart(InfoPList, NL,
1802 AssociateDocumentTypes.ToPListSection(IOSQualifiedName, 'AppIcon'));
1803 if not Manifest.UsesNonExemptEncryption then
1804 InfoPList := SAppendPart(InfoPList, NL,
1805 '<key>ITSAppUsesNonExemptEncryption</key> <false/>');
1806 Macros.Add('IOS_EXTRA_INFO_PLIST', InfoPList);
1807
1808 IOSTargetAttributes := '';
1809 IOSRequiredDeviceCapabilities := '';
1810 if Manifest.IOSTeam <> '' then
1811 begin
1812 IOSTargetAttributes := IOSTargetAttributes +
1813 #9#9#9#9#9#9'DevelopmentTeam = ' + Manifest.IOSTeam + ';' + NL;
1814 Macros.Add('IOS_DEVELOPMENT_TEAM_LINE', 'DEVELOPMENT_TEAM = ' + Manifest.IOSTeam + ';');
1815 end else
1816 begin
1817 Macros.Add('IOS_DEVELOPMENT_TEAM_LINE', '');
1818 end;
1819
1820 IOSSystemCapabilities := '';
1821 // TODO: These service-specifics should be in CastleEngineService.xml now
1822 if IOSServices.HasService('apple_game_center') then
1823 begin
1824 IOSSystemCapabilities := IOSSystemCapabilities +
1825 Format(IOSCapabilityEnable, ['GameCenter']);
1826 IOSRequiredDeviceCapabilities := IOSRequiredDeviceCapabilities +
1827 #9#9'<string>gamekit</string>' + NL;
1828 end;
1829 if IOSServices.HasService('icloud_for_save_games') then
1830 IOSSystemCapabilities := IOSSystemCapabilities +
1831 Format(IOSCapabilityEnable, ['iCloud']);
1832 if IOSServices.HasService('in_app_purchases') then
1833 IOSSystemCapabilities := IOSSystemCapabilities +
1834 Format(IOSCapabilityEnable, ['InAppPurchase']);
1835 // If not empty, add IOSSystemCapabilities to IOSTargetAttributes,
1836 // wrapped in SystemCapabilities = { } block.
1837 if IOSSystemCapabilities <> '' then
1838 IOSTargetAttributes := IOSTargetAttributes +
1839 #9#9#9#9#9#9'SystemCapabilities = {' + NL +
1840 IOSSystemCapabilities +
1841 #9#9#9#9#9#9'};' + NL;
1842
1843 Macros.Add('IOS_TARGET_ATTRIBUTES', IOSTargetAttributes);
1844 Macros.Add('IOS_REQUIRED_DEVICE_CAPABILITIES', IOSRequiredDeviceCapabilities);
1845 Macros.Add('IOS_EXPORT_METHOD', IOSExportMethod);
1846
1847 if IOSServices.HasService('icloud_for_save_games') then
1848 Macros.Add('IOS_CODE_SIGN_ENTITLEMENTS', 'CODE_SIGN_ENTITLEMENTS = "' + Name + '/icloud_for_save_games.entitlements";')
1849 else
1850 Macros.Add('IOS_CODE_SIGN_ENTITLEMENTS', '');
1851
1852 GccPreprocessorDefinitions := '';
1853 // Since right now we always compile with CASTLE_TREMOLO_STATIC,
1854 // we just always behave like ogg_vorbis service was included.
1855 //if depOggVorbis in Dependencies then
1856 GccPreprocessorDefinitions := GccPreprocessorDefinitions + '"ONLY_C=1",' + NL;
1857 Macros.Add('IOS_GCC_PREPROCESSOR_DEFINITIONS', GccPreprocessorDefinitions);
1858
1859 for Service in IOSServices do
1860 ParametersAddMacros(Macros, Service.Parameters, 'IOS.' + Service.Name + '.');
1861 end;
1862
1863 function TCastleProject.ReplaceMacros(const Source: string): string;
1864
1865 function MakePathsStr(const Paths: TStringList; const Absolute: Boolean): String;
1866 var
1867 S, Dir: string;
1868 begin
1869 Result := '';
1870 for S in Paths do
1871 begin
1872 if Result <> '' then
1873 Result := Result + ';';
1874 if Absolute then
1875 Dir := CombinePaths(Path, S)
1876 else
1877 Dir := S;
1878 Result := Result + Dir;
1879 end;
1880
1881 { For ABSOLUTE_xxx macros, add Path (project directory).
1882 It is not necessary for relative paths, as their handling always includes current dir for now.
1883 Testcase: examples/advanced_editor/CastleEngineManifest.xml ,
1884 without this the "castle-engine editor" would not find GameControls. }
1885 if Absolute then
1886 Result := SAppendPart(Result, ';', Path);
1887 end;
1888
1889 function DelphiSearchPaths: String;
1890
1891 { Make DPROJ generated on Windows and Unix the same.
1892 We use slashes as they work on both Windows and Unix
1893 (through Delphi IDE is for now only on Windows, so using backslashes would be OK too.) }
1894 function PathNormalizeDelimiter(const S: String): String;
1895 begin
1896 Result := SReplaceChars(S, '\', '/');
1897 end;
1898
1899 var
1900 RelativeEnginePaths: Boolean;
1901 S, EnginePathPrefix: String;
1902 begin
1903 RelativeEnginePaths := IsPrefix(
1904 ExpandFileName(CastleEnginePath),
1905 ExpandFileName(Path),
1906 not FileNameCaseSensitive);
1907 if RelativeEnginePaths then
1908 EnginePathPrefix := ExtractRelativePath(Path, CastleEnginePath) + 'src/'
1909 else
1910 EnginePathPrefix := CastleEnginePath + 'src/';
1911 Result := '';
1912 for S in EnginePaths do
1913 Result := SAppendPart(Result, ';', PathNormalizeDelimiter(EnginePathPrefix + S));
1914 for S in EnginePathsDelphi do
1915 Result := SAppendPart(Result, ';', PathNormalizeDelimiter(EnginePathPrefix + S));
1916 for S in Manifest.SearchPaths do
1917 Result := SAppendPart(Result, ';', PathNormalizeDelimiter(S));
1918 end;
1919
1920 procedure AddMacrosLazarusProject(const Macros: TStringStringMap);
1921 var
1922 PascalFiles: TStringList;
1923 PascalFile, PascalFilesXml: String;
1924 I: Integer;
1925 begin
1926 { As an optimization, do not calculate LAZARUS_PROJECT_ALL_UNITS
1927 macro value when not needed. }
1928 if Pos('${LAZARUS_PROJECT_ALL_UNITS}', Source) <> 0 then
1929 begin
1930 PascalFiles := Manifest.FindPascalFiles;
1931 try
1932 { Make the files' list sorted,
1933 to have the `castle-engine generate-program`
1934 output fully deterministic for a given project,
1935 and indepedent from source OS, undefined ordef of FindFiles etc.
1936 This avoids diffs in version control if nothing changed. }
1937 PascalFiles.CaseSensitive := true;
1938 PascalFiles.Sort;
1939
1940 PascalFilesXml := '';
1941 I := 1;
1942 for PascalFile in PascalFiles do
1943 begin
1944 if LowerCase(ExtractFileExt(PascalFile)) = '.inc' then
1945 begin
1946 PascalFilesXml += Format(
1947 ' <Unit%d>' + NL +
1948 ' <Filename Value="%s"/>' + NL +
1949 ' <IsPartOfProject Value="True"/>' + NL +
1950 ' </Unit%d>' + NL, [
1951 I,
1952 PascalFile,
1953 I
1954 ]);
1955 end else
1956 begin
1957 PascalFilesXml += Format(
1958 ' <Unit%d>' + NL +
1959 ' <Filename Value="%s"/>' + NL +
1960 ' <IsPartOfProject Value="True"/>' + NL +
1961 ' <UnitName Value="%s"/>' + NL +
1962 ' </Unit%d>' + NL, [
1963 I,
1964 PascalFile,
1965 DeleteFileExt(ExtractFileName(PascalFile)),
1966 I
1967 ]);
1968 end;
1969 Inc(I);
1970 end;
1971 Macros.Add('LAZARUS_PROJECT_ALL_UNITS_COUNT', IntToStr(PascalFiles.Count + 1));
1972 Macros.Add('LAZARUS_PROJECT_ALL_UNITS', PascalFilesXml);
1973 finally FreeAndNil(PascalFiles) end;
1974 end;
1975 end;
1976
1977 function IcoPath: String;
1978 begin
1979 Result := Icons.FindExtension(['.ico']);
1980 { Let it be '' if not found, don't make warning, as this is only used by Delphi DPROJ. }
1981 end;
1982
1983 function ProjectGuid: String;
1984 var
1985 MyGuid: TGUID;
1986 begin
1987 if FGuidFromName then
1988 MyGuid := CreateGUIDFromHash(QualifiedName)
1989 else
1990 CreateGUID(MyGuid);
1991 Result := GUIDToString(MyGuid);
1992 end;
1993
1994 function DefinesAsCompilerOptions: String;
1995 var
1996 D: String;
1997 begin
1998 Result := '';
1999 for D in Manifest.Defines do
2000 Result := Result + '-d' + D + NL;
2001 end;
2002
2003 function DefinesSemicolonSeparated: String;
2004 var
2005 D: String;
2006 begin
2007 Result := '';
2008 for D in Manifest.Defines do
2009 Result := Result + D + ';';
2010 end;
2011
2012 { Generate proper DeployFile elements for DPROJ,
2013 to deploy programs with their data using PAServer.
2014
2015 Sample:
2016 <DeployFile LocalName="data\Dino.gltf" Configuration="Debug" Class="File">
2017 <Platform Name="Linux64">
2018 <RemoteDir>./data/</RemoteDir>
2019 <RemoteName>Dino.gltf</RemoteName>
2020 <Overwrite>true</Overwrite>
2021 </Platform>
2022 ... // repeat for all platforms
2023 </DeployFile>
2024 // repeat for release too
2025 }
2026 function DelphiDprojDeployFiles: String;
2027 const
2028 AllDelphiPlatformNames: array [0..2] of String = (
2029 { For now, commented out platforms that we don't use.
2030 These platforms make DPROJ extra large
2031 ( see https://forum.castle-engine.io/t/there-is-a-problem-with-generating-files-for-testing-new-features/1264/6 )
2032 so for now, at least make it smaller but commenting out platforms that we don't use. }
2033 // 'Android',
2034 // 'Android64',
2035 // 'iOSDevice64',
2036 // 'iOSSimARM64',
2037 'Linux64',
2038 // 'OSX64',
2039 // 'OSXARM64',
2040 'Win32',
2041 'Win64'
2042 );
2043 AllDelphiConfigNames: array [0..1] of String = (
2044 'Debug',
2045 'Release'
2046 );
2047 var
2048 ConfigName, PlatformName, FileRelativeName: String;
2049 Files: TStringList;
2050 ResultBuilder: TStringBuilder;
2051 begin
2052 ResultBuilder := TStringBuilder.Create;
2053 try
2054 Files := PackageFiles(true, cpDesktop);
2055 try
2056 { Make the files' list sorted,
2057 to have the `castle-engine generate-program`
2058 output fully deterministic for a given project,
2059 and indepedent from source OS, undefined ordef of FindFiles etc.
2060 This avoids diffs in version control if nothing changed. }
2061 Files.CaseSensitive := true;
2062 Files.Sort;
2063
2064 { Note that we try to minimize output below, as it may get really
2065 large for many files.
2066 ( see https://forum.castle-engine.io/t/there-is-a-problem-with-generating-files-for-testing-new-features/1264/6 )
2067 That's also why we don't add too much whitespace and indentation below.
2068 }
2069
2070 if Files.Count <> 0 then
2071 begin
2072 ResultBuilder.Append(
2073 '<!-- Auto-generated list of deploy files.' + NL +
2074 ' We need to list all "data" files to deploy Delphi applications' + NL +
2075 ' to non-Windows targets,' + NL +
2076 ' see https://castle-engine.io/delphi_linux#data_files_deployment .' + NL +
2077 '-->' + NL);
2078 end;
2079
2080 for ConfigName in AllDelphiConfigNames do
2081 begin
2082 for FileRelativeName in Files do
2083 begin
2084 ResultBuilder.Append(Format(
2085 '<DeployFile LocalName="%s\%s" Configuration="%s" Class="File">' + NL, [
2086 TCastleManifest.DataName,
2087 FileRelativeName,
2088 ConfigName
2089 ]));
2090 for PlatformName in AllDelphiPlatformNames do
2091 ResultBuilder.Append(Format(
2092 ' <Platform Name="%s">' + NL +
2093 ' <RemoteDir>./%s/%s</RemoteDir>' + NL +
2094 ' <RemoteName>%s</RemoteName>' + NL +
2095 ' <Overwrite>true</Overwrite>' + NL +
2096 ' </Platform>' + NL, [
2097 PlatformName,
2098 TCastleManifest.DataName,
2099 ExtractFilePath(FileRelativeName),
2100 ExtractFileName(FileRelativeName)
2101 ]));
2102 ResultBuilder.Append(
2103 '</DeployFile>' + NL);
2104 end;
2105 end;
2106 finally FreeAndNil(Files) end;
2107 Result := ResultBuilder.ToString;
2108 finally FreeAndNil(ResultBuilder) end;
2109 end;
2110
2111 { Add macros specifically useful by Delphi project files. }
2112 procedure AddMacrosDproj(const Macros: TStringStringMap;
2113 const StandaloneSource: String);
2114 var
2115 WelcomePageFile, IncludedFiles, WelcomePageXml: String;
2116 // PascalFiles unused -- see comment below
2117 // PascalFiles: TStringList;
2118 // PascalFile, UnitFileForDelphi: String;
2119 begin
2120 WelcomePageFile := WelcomePage;
2121
2122 { Optimize: do not calculate DPROJ_INCLUDED_FILES when not necessary. }
2123 if Pos('${DPROJ_INCLUDED_FILES}', Source) <> 0 then
2124 begin
2125 IncludedFiles := '';
2126
2127 { Add project units to IncludedFiles
2128
2129 Commented out: Note that we don't add units (like castleautogenerated.pas,
2130 code/gameinitialize.pas, code/gameview*.pas) to DPROJ.
2131 While possible, it would be pointless: Delphi IDE doesn't actually
2132 display them as part of the project, unless they are repeated in DPR.
2133
2134 And we don't want to add Manifest.FindPascalFiles to DPR.
2135 Because we are not 100% certain that all units in Manifest.FindPascalFiles
2136 should be linked into the application, and for all platforms.
2137 We obtain Manifest.FindPascalFiles by scanning code directories,
2138 we could pick units like code/unused.pas or code/onlymobile.pas .
2139
2140 Ultimately, we'd have to ask user to specify every used unit
2141 explicitly in CastleEngineManifest.xml, for us to add it to Delphi project.
2142 Doing it automatically based on Manifest.FindPascalFiles is too risky. }
2143 (*
2144 PascalFiles := Manifest.FindPascalFiles;
2145 try
2146 { Make the files' list sorted,
2147 to have the `castle-engine generate-program`
2148 output fully deterministic for a given project,
2149 and indepedent from source OS, undefined ordef of FindFiles etc.
2150 This avoids diffs in version control if nothing changed. }
2151 PascalFiles.CaseSensitive := true;
2152 PascalFiles.Sort;
2153
2154 for PascalFile in PascalFiles do
2155 begin
2156 if LowerCase(ExtractFileExt(PascalFile)) = '.pas' then
2157 begin
2158 { Normalize paths to Pascal files to use backslashes
2159 (seems more standard in Delphi IDE, which is Windows-only). }
2160 UnitFileForDelphi := SReplaceChars(PascalFile, '/', '\');
2161 IncludedFiles := SAppendPart(IncludedFiles, NL,
2162 ' <DCCReference Include="' + UnitFileForDelphi + '"/>');
2163 end;
2164 end;
2165 finally FreeAndNil(PascalFiles) end;
2166 *)
2167
2168 { Add lines like this to define files:
2169 <None Include="README.md"/>
2170 <None Include="play_animation_standalone.dpr"/>
2171 This allows to easily open them from IDE, also it seems "welcome page"
2172 (see below) has to be listed here to work. }
2173 if WelcomePageFile <> '' then
2174 IncludedFiles := SAppendPart(IncludedFiles, NL,
2175 ' <None Include="' + WelcomePageFile + '"/>');
2176 if StandaloneSource <> '' then
2177 IncludedFiles := SAppendPart(IncludedFiles, NL,
2178 ' <None Include="' + StandaloneSource + '"/>');
2179 Macros.Add('DPROJ_INCLUDED_FILES', IncludedFiles);
2180 end;
2181
2182 { Define welcome page by XML content like this:
2183
2184 <WelcomePageFile Path="README.md"/>
2185 <WelcomePageFolder/>
2186 }
2187 if WelcomePageFile <> '' then
2188 begin
2189 WelcomePageXml := Format(
2190 ' <WelcomePageFile Path="%s"/>' + NL +
2191 ' <WelcomePageFolder/>', [WelcomePageFile])
2192 end else
2193 WelcomePageXml := '';
2194 Macros.Add('DPROJ_WELCOME_PAGE', WelcomePageXml);
2195
2196 { As an optimization, do not calculate DPROJ_DEPLOY_FILES
2197 macro value when not needed. }
2198 if Pos('${DPROJ_DEPLOY_FILES}', Source) <> 0 then
2199 Macros.Add('DPROJ_DEPLOY_FILES', DelphiDprojDeployFiles);
2200 end;
2201
2202 var
2203 NonEmptyAuthor, StandaloneSource: string;
2204 Macros: TStringStringMap;
2205 begin
2206 if Author = '' then
2207 NonEmptyAuthor := 'Unknown Author'
2208 else
2209 NonEmptyAuthor := Author;
2210
2211 StandaloneSource := ExplicitStandaloneFile('.dpr');
2212
2213 Macros := TStringStringMap.Create;
2214 try
2215 Macros.Add('DOLLAR' , '$');
2216 Macros.Add('VERSION_MAJOR' , IntToStr(Version.Items[0]));
2217 Macros.Add('VERSION_MINOR' , IntToStr(Version.Items[1]));
2218 Macros.Add('VERSION_RELEASE' , IntToStr(Version.Items[2]));
2219 Macros.Add('VERSION_BUILD' , IntToStr(Version.Items[3]));
2220 Macros.Add('VERSION' , Manifest.Version.DisplayValue);
2221 Macros.Add('VERSION_CODE' , IntToStr(Manifest.Version.Code));
2222 Macros.Add('NAME' , Name);
2223 Macros.Add('NAME_PASCAL' , NamePascal);
2224 Macros.Add('QUALIFIED_NAME' , QualifiedName);
2225 Macros.Add('CAPTION' , Caption);
2226 Macros.Add('AUTHOR' , NonEmptyAuthor);
2227 Macros.Add('EXECUTABLE_NAME' , ExecutableName);
2228 { TODO: Right now Delphi IDE compiles exe with basename matching
2229 DeleteFileExt(StandaloneSource), not our ExecutableName
2230 (which is sometimes different, e.g. doesn't contain "_standalone" suffix,
2231 has - instead of _).
2232 So we have DELPHI_EXECUTABLE_NAME.
2233 In the long run, it would be ideal to only have EXECUTABLE_NAME
2234 and make Delphi IDE build the same as Delphi command-line and FPC. }
2235 Macros.Add('DELPHI_EXECUTABLE_NAME', DeleteFileExt(StandaloneSource));
2236 Macros.Add('GAME_UNITS' , Manifest.GameUnits);
2237 Macros.Add('SEARCH_PATHS' , MakePathsStr(Manifest.SearchPaths, false));
2238 Macros.Add('ABSOLUTE_SEARCH_PATHS' , MakePathsStr(Manifest.SearchPaths, true));
2239 Macros.Add('LIBRARY_PATHS' , MakePathsStr(Manifest.LibraryPaths, false));
2240 { Using this is important in ../data/custom_editor_template/castle_editor.lpi ,
2241 otherwise with FPC 3.3.1 (rev 40292) doing "castle-engine editor"
2242 fails when the project uses some libraries (like mORMot's .o files in static/). }
2243 Macros.Add('ABSOLUTE_LIBRARY_PATHS', MakePathsStr(Manifest.LibraryPaths, true));
2244 Macros.Add('CASTLE_ENGINE_PATH' , CastleEnginePath);
2245 Macros.Add('EXTRA_COMPILER_OPTIONS', Manifest.ExtraCompilerOptions.Text);
2246 Macros.Add('EXTRA_COMPILER_OPTIONS_ABSOLUTE', Manifest.ExtraCompilerOptionsAbsolute.Text);
2247 Macros.Add('DEFINES_SEMICOLON_SEPARATED', DefinesSemicolonSeparated);
2248 Macros.Add('DEFINES_AS_COMPILER_OPTIONS', DefinesAsCompilerOptions);
2249 Macros.Add('EDITOR_UNITS' , Manifest.EditorUnits);
2250 Macros.Add('EXPLICIT_STANDALONE_SOURCE', StandaloneSource);
2251 // Suitable name for Pascal "program" declaration
2252 Macros.Add('PASCAL_PROGRAM_NAME', TCastleManifest.StandaloneSourceToProgramName(StandaloneSource));
2253 Macros.Add('DELPHI_SEARCH_PATHS', DelphiSearchPaths);
2254 Macros.Add('ICO_PATH', IcoPath);
2255 Macros.Add('PROJECT_GUID', ProjectGuid);
2256 Macros.Add('APPLE_BUNDLE_SIGNATURE', Copy(ExecutableName + '????', 1, 4));
2257 Macros.Add('APPLE_ASSOCIATE_DOCUMENT_TYPES', AssociateDocumentTypes.ToPListSection(QualifiedName, Name));
2258
2259 AddMacrosAndroid(Macros);
2260 AddMacrosIOS(Macros);
2261 AddMacrosLazarusProject(Macros);
2262 AddMacrosDproj(Macros, StandaloneSource);
2263
2264 Result := ToolMacros.ReplaceMacros(Macros, Source);
2265 finally FreeAndNil(Macros) end;
2266 end;
2267
2268 function TCastleProject.WelcomePage: String;
2269
2270 procedure TryWelcomePage(const RelativeFileName: String);
2271 begin
2272 if FileExists(Path + RelativeFileName) then
2273 Result := RelativeFileName;
2274 end;
2275
2276 begin
2277 Result := '';
2278
2279 TryWelcomePage('README.md');
2280 if Result <> '' then Exit;
2281
2282 TryWelcomePage('README.txt');
2283 if Result <> '' then Exit;
2284 end;
2285
2286 procedure TCastleProject.ExtractTemplate(const TemplatePath, DestinationPath: string;
2287 const OverrideExisting: boolean);
2288 var
2289 TemplateFilesCount: Cardinal;
2290 begin
2291 ExtractTemplateOverrideExisting := OverrideExisting;
2292 ExtractTemplateDestinationPath := InclPathDelim(DestinationPath);
2293 ExtractTemplateDir := ExclPathDelim(UriToFilenameSafe('castle-data:/' +TemplatePath));
2294 if not DirectoryExists(ExtractTemplateDir) then
2295 raise Exception.Create('Cannot find template in "' + ExtractTemplateDir + '". ' + SErrDataDir);
2296
2297 TemplateFilesCount := FindFiles(ExtractTemplateDir, '*', false,
2298 @ExtractTemplateFoundFile, [ffRecursive]);
2299 if Verbose then
2300 Writeln(Format('Copied template "%s" (%d files) to "%s"',
2301 [TemplatePath, TemplateFilesCount, DestinationPath]));
2302 end;
2303
2304 procedure TCastleProject.ExtractTemplateFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
2305 var
2306 DestinationRelativeFileName, DestinationFileName: string;
2307 begin
2308 DestinationRelativeFileName := PrefixRemove(InclPathDelim(ExtractTemplateDir),
2309 FileInfo.AbsoluteName, true);
2310
2311 if IsWild(DestinationRelativeFileName, '*setup_sdk.sh', true) or
2312 IsWild(DestinationRelativeFileName, '*~', true) or
2313 SameFileName(ExtractFileName(DestinationRelativeFileName), '.DS_Store') or
2314 SameFileName(ExtractFileName(DestinationRelativeFileName), 'thumbs.db') then
2315 begin
2316 // if Verbose then
2317 // Writeln('Ignoring template file: ' + DestinationRelativeFileName);
2318 Exit;
2319 end;
2320
2321 StringReplaceAllVar(DestinationRelativeFileName, 'cge_project_name', Name);
2322
2323 DestinationFileName := ExtractTemplateDestinationPath + DestinationRelativeFileName;
2324
2325 ExtractTemplateFile(FileInfo.AbsoluteName, DestinationFileName,
2326 DestinationRelativeFileName,
2327 ExtractTemplateOverrideExisting);
2328 end;
2329
2330 procedure TCastleProject.ExtractTemplateFile(
2331 const SourceFileName, DestinationFileName, DestinationRelativeFileName: string;
2332 const OverrideExisting: boolean);
2333 var
2334 DestinationRelativeFileNameSlashes, Contents, Ext: string;
2335 BinaryFile: boolean;
2336 begin
2337 { Do not copy README.adoc, most services define it and would just overwrite each other.
2338 It is for informational purposes in CGE sources.
2339 Similarly do not copy CastleEngineService.xml, most services define it,
2340 it is internal info for build tool. }
2341 if SameText(DestinationRelativeFileName, 'README.adoc') or
2342 SameText(DestinationRelativeFileName, 'CastleEngineService.xml') then
2343 Exit;
2344
2345 if (not OverrideExisting) and RegularFileExists(DestinationFileName) then
2346 begin
2347 DestinationRelativeFileNameSlashes := StringReplace(
2348 DestinationRelativeFileName, '\', '/', [rfReplaceAll]);
2349
2350 if SameText(DestinationRelativeFileNameSlashes, Name + '/AppDelegate.m') then
2351 MergeIOSAppDelegate(SourceFileName, DestinationFileName, @ReplaceMacros)
2352 else
2353 if SameText(DestinationRelativeFileNameSlashes, 'Podfile') then
2354 MergeIOSPodfile(SourceFileName, DestinationFileName, @ReplaceMacros)
2355 else
2356 if SameText(DestinationRelativeFileNameSlashes, Name + '/' + Name + '-Info.plist') then
2357 MergeIOSInfoPlist(SourceFileName, DestinationFileName, @ReplaceMacros)
2358 else
2359 if SameText(DestinationRelativeFileNameSlashes, 'app/src/main/AndroidManifest.xml') then
2360 MergeAndroidManifest(SourceFileName, DestinationFileName, @ReplaceMacros)
2361 else
2362 if SameText(DestinationRelativeFileNameSlashes, 'app/src/main/CMakeLists.txt') then
2363 MergeAppend(SourceFileName, DestinationFileName, @ReplaceMacros)
2364 else
2365 if SameText(DestinationRelativeFileNameSlashes, 'app/src/main/res/values/strings.xml') then
2366 MergeStringsXml(SourceFileName, DestinationFileName, @ReplaceMacros)
2367 else
2368 if SameText(DestinationRelativeFileNameSlashes, 'app/src/main/java/io/castleengine/MainActivity.java') then
2369 MergeAndroidMainActivity(SourceFileName, DestinationFileName, @ReplaceMacros)
2370 else
2371 if SameText(DestinationRelativeFileNameSlashes, 'app/src/main/jni/Android.mk') or
2372 SameText(DestinationRelativeFileNameSlashes, 'app/src/main/custom-proguard-project.txt') then
2373 MergeAppend(SourceFileName, DestinationFileName, @ReplaceMacros)
2374 else
2375 if SameText(DestinationRelativeFileNameSlashes, 'app/build.gradle') then
2376 MergeBuildGradle(SourceFileName, DestinationFileName, @ReplaceMacros)
2377 else
2378 if SameText(DestinationRelativeFileNameSlashes, 'build.gradle') then
2379 MergeBuildGradle(SourceFileName, DestinationFileName, @ReplaceMacros)
2380 else
2381 WritelnWarning('Template not overwriting custom ' + DestinationRelativeFileName);
2382
2383 Exit;
2384 end;
2385
2386 Ext := ExtractFileExt(SourceFileName);
2387 BinaryFile := SameText(Ext, '.so') or SameText(Ext, '.jar');
2388 CheckForceDirectories(ExtractFilePath(DestinationFileName));
2389
2390 try
2391 if BinaryFile then
2392 begin
2393 CheckCopyFile(SourceFileName, DestinationFileName);
2394 end else
2395 begin
2396 Contents := FileToString(FilenameToUriSafe(SourceFileName));
2397 Contents := ReplaceMacros(Contents);
2398 StringToFile(FilenameToUriSafe(DestinationFileName), Contents);
2399 end;
2400 except
2401 on E: EFOpenError do
2402 begin
2403 Writeln('Cannot open a template file.');
2404 Writeln(SErrDataDir);
2405 raise;
2406 end;
2407 end;
2408 end;
2409
2410 function TCastleProject.OutputPath: string;
2411 begin
2412 if OutputPathBase = '' then
2413 Result := Path
2414 else
2415 begin
2416 Result := InclPathDelim(ExpandFileName(OutputPathBase));
2417 CheckForceDirectories(Result);
2418 end;
2419 end;
2420
2421 procedure TCastleProject.CopyData(OutputDataPath: string; const TargetPlatform: TCastlePlatform);
2422 var
2423 I: Integer;
2424 FileFrom, FileTo: string;
2425 Files: TCastleStringList;
2426 begin
2427 OutputDataPath := InclPathDelim(OutputDataPath);
2428 ForceDirectories(OutputDataPath);
2429
2430 Files := PackageFiles(true, TargetPlatform);
2431 try
2432 for I := 0 to Files.Count - 1 do
2433 begin
2434 FileFrom := DataPath + Files[I];
2435 FileTo := OutputDataPath + Files[I];
2436 SmartCopyFile(FileFrom, FileTo);
2437 if Verbose then
2438 Writeln('Packaging data file: ' + Files[I]);
2439 end;
2440 finally FreeAndNil(Files) end;
2441
2442 GenerateDataInformation(OutputDataPath);
2443 end;
2444
2445 function TCastleProject.PackageOutput(const FileName: String): Boolean;
2446 var
2447 OS: TOS;
2448 CPU: TCPU;
2449 PackageFormat: TPackageFormatNoDefault;
2450 HasVersion: Boolean;
2451 begin
2452 for OS in TOS do
2453 for CPU in TCPU do
2454 // TODO: This will not exclude output of packaging with pfDirectory
2455 for PackageFormat in TPackageFormatNoDefault do
2456 for HasVersion in Boolean do
2457 if OSCPUSupported[OS, CPU] then
2458 if SameFileName(FileName, PackageName(OS, CPU, PackageFormat, HasVersion)) then
2459 Exit(true);
2460
2461 for HasVersion in Boolean do
2462 // list all package formats allowed for source packages now
2463 if SameFileName(FileName, SourcePackageName(HasVersion, pfZip)) or
2464 SameFileName(FileName, SourcePackageName(HasVersion, pfTarGz)) then
2465 Exit(true);
2466
2467 if { avoid Android packages }
2468 IsWild(FileName, Name + '*-android-debug.apk', true) or
2469 IsWild(FileName, Name + '*-android-debug.aab', true) or
2470 IsWild(FileName, Name + '*-android-release.apk', true) or
2471 IsWild(FileName, Name + '*-android-release.aab', true) or
2472 { do not pack AndroidSigningProperties.txt (AndroidAntProperties.txt is older name for it) with private stuff }
2473 SameFileName(FileName, 'AndroidAntProperties.txt') or
2474 SameFileName(FileName, 'AndroidSigningProperties.txt') then
2475 Exit(true);
2476
2477 Result := false;
2478 end;
2479
2480 function TCastleProject.IOSHasLaunchImageStoryboard: Boolean;
2481 begin
2482 Result :=
2483 (FLaunchImageStoryboardWidth <> 0) and
2484 (FLaunchImageStoryboardHeight <> 0);
2485 end;
2486
2487 { shortcut methods to acces Manifest.Xxx ------------------------------------- }
2488
2489 function TCastleProject.Version: TProjectVersion;
2490 begin
2491 Result := Manifest.Version;
2492 end;
2493
2494 function TCastleProject.ManifestCompiler: TCompiler;
2495 begin
2496 Result := Manifest.Compiler;
2497 end;
2498
2499 function TCastleProject.QualifiedName: string;
2500 begin
2501 Result := Manifest.QualifiedName;
2502 end;
2503
2504 function TCastleProject.Dependencies: TDependencies;
2505 begin
2506 Result := Manifest.Dependencies;
2507 end;
2508
2509 function TCastleProject.Name: string;
2510 begin
2511 Result := Manifest.Name;
2512 end;
2513
2514 function TCastleProject.Path: string;
2515 begin
2516 Result := Manifest.Path;
2517 end;
2518
2519 function TCastleProject.DataExists: Boolean;
2520 begin
2521 Result := Manifest.DataExists;
2522 end;
2523
2524 function TCastleProject.DataPath: string;
2525 begin
2526 Result := Manifest.DataPath;
2527 end;
2528
2529 function TCastleProject.Caption: string;
2530 begin
2531 Result := Manifest.Caption;
2532 end;
2533
2534 function TCastleProject.Author: string;
2535 begin
2536 Result := Manifest.Author;
2537 end;
2538
2539 function TCastleProject.ExecutableName: string;
2540 begin
2541 Result := Manifest.ExecutableName;
2542 end;
2543
2544 function TCastleProject.FullscreenImmersive: boolean;
2545 begin
2546 Result := Manifest.FullscreenImmersive;
2547 end;
2548
2549 function TCastleProject.ScreenOrientation: TScreenOrientation;
2550 begin
2551 Result := Manifest.ScreenOrientation;
2552 end;
2553
2554 function TCastleProject.AndroidCompileSdkVersion: Cardinal;
2555 begin
2556 Result := Manifest.AndroidCompileSdkVersion;
2557 end;
2558
2559 function TCastleProject.AndroidMinSdkVersion: Cardinal;
2560 begin
2561 Result := Manifest.AndroidMinSdkVersion;
2562 end;
2563
2564 function TCastleProject.AndroidTargetSdkVersion: Cardinal;
2565 begin
2566 Result := Manifest.AndroidTargetSdkVersion;
2567 end;
2568
2569 function TCastleProject.Icons: TImageFileNames;
2570 begin
2571 Result := Manifest.Icons;
2572 end;
2573
2574 function TCastleProject.LaunchImages: TImageFileNames;
2575 begin
2576 Result := Manifest.LaunchImages;
2577 end;
2578
2579 function TCastleProject.AndroidServices: TServiceList;
2580 begin
2581 Result := Manifest.AndroidServices;
2582 end;
2583
2584 function TCastleProject.IOSServices: TServiceList;
2585 begin
2586 Result := Manifest.IOSServices;
2587 end;
2588
2589 function TCastleProject.AssociateDocumentTypes: TAssociatedDocTypeList;
2590 begin
2591 Result := Manifest.AssociateDocumentTypes;
2592 end;
2593
2594 function TCastleProject.LocalizedAppNames: TLocalizedAppNameList;
2595 begin
2596 Result := Manifest.LocalizedAppNames;
2597 end;
2598
2599 function TCastleProject.LaunchImageStoryboard: TLaunchImageStoryboard;
2600 begin
2601 Result := Manifest.LaunchImageStoryboard;
2602 end;
2603
2604 end.