Debian Codegraph @

tools/image-to-pascal/image_to_pascal.lpr

raw
1 {
2 Copyright 2001-2023 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 { Convert image files to a Pascal source code, thus allowing
17 you to easily embed image files in program executables.
18
19 1st command-line option specifies the unit name, usually in CamelCase.
20 Rest of the command-line options specify image URLs (usually filenames).
21
22 The output unit filename will be lowercase(unit name) + '.pas'.
23 (We make the name lowercase, as this is nice under Unix.)
24 We also output an include file, with .images_data extension, containing
25 actual image data (the extension is deliberately weird:
26 the contents may be large, and would confuse http://www.ohloh.net/
27 into thinking you have a lot of (uncommented) Pascal source code).
28 We place it all inside directory given by --output option, by default
29 just in the current directory.
30
31 The generated Pascal unit defines TCastleImage instances
32 (created / freed in unit's initialization / finalization)
33 that contain the size and contents of your images.
34 Remember that you can provide many image URLs on the command-line,
35 then all of them will be included in the unit.
36 The images are compressed with simple RLE compression per-channel,
37 to not make the EXE size (and compilation speed) too large.
38
39 For an example output of this program see e.g. castle-model-viewer sources,
40 unit v3dsceneimages, generated from images inside castle-model-viewer/images.
41
42 Run with --help for a description of other command-line parameters.
43 }
44
45 {$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
46
47 uses SysUtils, CastleImages, CastleUtils, CastleFilesUtils,
48 CastleParameters, CastleUriUtils, CastleStringUtils,
49 CastleClassUtils, CastleDownload, CastleLog;
50
51 var
52 OutputDirectory: string = '';
53
54 const
55 Options: array [0..3] of TOption = (
56 (Short: 'h'; Long: 'help'; Argument: oaNone),
57 (Short: 'v'; Long: 'version'; Argument: oaNone),
58 (Short: 'o'; Long: 'output'; Argument: oaRequired),
59 (Short: 'V'; Long: 'verbose'; Argument: oaNone)
60 );
61
62 procedure OptionProc(OptionNum: Integer; HasArgument: boolean;
63 const Argument: string; const SeparateArgs: TSeparateArgs; Data: Pointer);
64 begin
65 case OptionNum of
66 0: begin
67 Writeln(
68 'image-to-pascal: Convert image files into Pascal source code,' +NL+
69 'useful together with Castle Game Engine image units.' +NL+
70 nl+
71 'Usage:' +NL+
72 ' image-to-pascal [OPTIONS...] UnitName image_name1.png...' +NL+
73 nl+
74 'Available options are:' +NL+
75 OptionDescription('-h / --help', 'Print this help message and exit.') + NL +
76 OptionDescription('-v / --version', 'Print the version number and exit.') + NL +
77 OptionDescription('--no-show-progress', 'Do not show progress on stderr.') + NL +
78 OptionDescription('-o / --output DIRECTORY', 'Place output unit files inside this dir.') + NL +
79 OptionDescription('-V / --verbose', 'Print full log.') + NL +
80 OptionDescription('@alpha=keep', 'Keep the alpha channel on the following images (the default). As a result, alpha channel will be stored in source files.') + NL +
81 OptionDescription('@alpha=strip', 'Strip the alpha channel from the following images.') + NL +
82 OptionDescription('@alpha=keep-and-bleed', 'Like "keep", moreover perform "alpha bleeding" (see https://castle-engine.io/manual_alpha_bleeding.php ) to fix RGB values under transparent pixels.') + NL
83 );
84 Halt;
85 end;
86 1: begin
87 // include ApplicationName in version, good for help2man
88 Writeln(ApplicationName + ' ' + CastleEngineVersion);
89 Halt;
90 end;
91 2: OutputDirectory := Argument + '/';
92 3: InitializeLog;
93 else raise EInternalError.Create('OptionProc -- unknown arg');
94 end;
95 end;
96
97 function PascalNameFromUrl(const Url: String): String;
98 const
99 ValidChars = ['0'..'9', 'a'..'z', 'A'..'Z', '_'];
100 ValidFirstChars = ['a'..'z', 'A'..'Z', '_'];
101 begin
102 Result := DeleteURIExt(ExtractURIName(Url));
103 // replace chars not valid in the middle of Pascal identifier
104 Result := SReplaceChars(Result, AllChars - ValidChars, '_');
105 // replace chars not valid as 1st char of Pascal identifier
106 if not (Result[1] in ValidFirstChars) then
107 Result[1] := '_';
108 Result[1] := UpCase(Result[1]);
109 end;
110
111 type
112 TAlpha = (alphaKeep, alphaStrip, alphaKeepAndBleed);
113
114 var
115 Image, TempImage: TCastleImage;
116 ImageUrl: String;
117 UnitName, ImageName: string;
118 CodeInterface, CodeImplementation, CodeInitialization, CodeFinalization: string;
119 ImageIndex: Integer;
120 OutputUnit: TTextWriter;
121 Alpha: TAlpha = alphaKeep;
122 begin
123 { parse params }
124 Parameters.Parse(Options, @OptionProc, nil);
125 Parameters.CheckHighAtLeast(2);
126 UnitName := Parameters[1];
127 Parameters.Delete(1);
128
129 { calculate unit's content from images into Images* strings }
130 CodeInterface := '';
131 CodeImplementation := '';
132 CodeInitialization := '';
133 CodeFinalization := '';
134 for ImageIndex := 1 to Parameters.High do
135 begin
136 ImageUrl := Parameters[ImageIndex];
137
138 if ImageUrl = '@alpha=strip' then
139 begin
140 Alpha := alphaStrip;
141 Continue;
142 end else
143 if ImageUrl = '@alpha=keep' then
144 begin
145 Alpha := alphaKeep;
146 Continue;
147 end else
148 if ImageUrl = '@alpha=keep-and-bleed' then
149 begin
150 Alpha := alphaKeepAndBleed;
151 Continue;
152 end;
153
154 { init other Image* variables }
155 ImageName := PascalNameFromUrl(ImageUrl);
156 Image := LoadImage(ImageUrl);
157 try
158 if Image.HasAlpha then
159 begin
160 case Alpha of
161 alphaStrip:
162 begin
163 Writeln(ErrOutput, 'Stripping alpha from ', ImageUrl);
164 TempImage := TRGBImage.Create;
165 TempImage.Assign(Image);
166 FreeAndNil(Image);
167 Image := TempImage;
168 TempImage := nil; {< for safety }
169 end;
170 alphaKeepAndBleed:
171 begin
172 Writeln(ErrOutput, 'Making alpha bleeding on ', ImageUrl);
173 // convert to TRGBAlphaImage as alpha bleeding is implemented only there
174 TempImage := TRGBAlphaImage.Create;
175 TempImage.Assign(Image);
176 TempImage.AlphaBleed;
177 FreeAndNil(Image);
178 Image := TempImage;
179 TempImage := nil; {< for safety }
180 end;
181 else { do nothing for alphaKeep };
182 end;
183 end;
184
185 Writeln(ErrOutput, Format('Generating %s (%s, alpha: %s)', [
186 ImageName,
187 Image.ClassName,
188 AlphaToString[Image.AlphaChannel]
189 ]));
190 Image.SaveToPascalCode(ImageName,
191 CodeInterface, CodeImplementation, CodeInitialization, CodeFinalization);
192 finally FreeAndNil(Image) end;
193 end;
194
195 { output full unit contents }
196 OutputUnit := TTextWriter.Create(OutputDirectory + LowerCase(UnitName) + '.pas');
197 OutputUnit.Write(
198 '{ -*- buffer-read-only: t -*- }' +NL+
199 nl+
200 '{ Unit automatically generated by image-to-pascal tool,' +NL+
201 ' to embed images in Pascal source code.' +NL+
202 ' @exclude (Exclude this unit from PasDoc documentation.) }' +NL+
203 'unit '+UnitName+';' +NL+
204 nl+
205 'interface' +NL+
206 nl+
207 'uses CastleImages;' +NL+
208 nl);
209 OutputUnit.Write(CodeInterface);
210 OutputUnit.Write(
211 'implementation' + nl +
212 nl+
213 'uses SysUtils, CastleInternalDataCompression;' + nl +
214 nl +
215 '{ Actual image data is included from another file, with a deliberately' +NL+
216 ' non-Pascal file extension ".image_data". This way online code analysis' +NL+
217 ' tools will NOT consider this source code as an uncommented Pascal code' +NL+
218 ' (which would be unfair --- the image data file is autogenerated' +NL+
219 ' and never supposed to be processed by a human). }' +NL+
220 '{$I ' + LowerCase(UnitName) + '.image_data}' +NL+
221 nl +
222 'initialization' +NL+
223 CodeInitialization +
224 'finalization' +NL+
225 CodeFinalization +
226 'end.');
227 FreeAndNil(OutputUnit);
228
229 OutputUnit := TTextWriter.Create(OutputDirectory + LowerCase(UnitName) + '.image_data');
230 OutputUnit.Write(CodeImplementation);
231 FreeAndNil(OutputUnit);
232 end.