forked from TES5Edit/TES5Edit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wbLOD.pas
3771 lines (3348 loc) · 135 KB
/
wbLOD.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{*******************************************************************************
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
*******************************************************************************}
unit wbLOD;
interface
uses
Windows,
Classes,
SysUtils,
IniFiles,
Forms,
IOUtils,
Masks,
wbInterface,
wbImplementation,
wbHelpers,
wbSort,
wbStreams,
wbDataFormat,
wbDataFormatNif,
wbDataFormatMaterial,
ImagingTypes,
ImagingFormats,
ImagingCanvases,
Imaging;
const
{$IFDEF WIN64}
sLODGenName = 'LODGenx64.exe';
sTexconv = 'Texconvx64.exe';
{$ELSE}
sLODGenName = 'LODGen.exe';
sTexconv = 'Texconv.exe';
{$ENDIF}
BooleanText: array[boolean] of string = ('False', 'True');
iBillboardFlag = 4096; // mark texture as a tree billboard in atlas images
var
iDefaultAtlasWidth: Integer = 2048;
iDefaultAtlasHeight: Integer = 2048;
fDefaultUVRange: Single = 1.5;
iDefaultAtlasDiffuseFormat: TImageFormat = ifDXT3;
iDefaultAtlasNormalFormat: TImageFormat = ifDXT1;
iDefaultAtlasSpecularFormat: TImageFormat = ifATI2n;
iDefaultAlphaThreshold: Integer = 128;
type
PBinNode = ^TBinNode;
TBinNode = record
used: Boolean;
x, y, w, h: Integer;
down: PBinNode;
right: PBinNode;
end;
TBinBlock = record
Index: Integer;
fit: Boolean;
x, y, w, h: Integer;
Data: Integer;
end;
TDynBinBlockArray = array of TBinBlock;
// Based on http://codeincomplete.com/posts/2011/5/7/bin_packing/
TwbBinPacker = class
private
fWidth, fHeight: Integer;
fPaddingX: Integer;
fPaddingY: Integer;
fRoot: PBinNode;
protected
procedure Clear(Node: PBinNode);
procedure NewNode(var Node: PBinNode);
function FindNode(root: PBinNode; w, h: Integer): PBinNode;
function SplitNode(node: PBinNode; w, h: Integer): PBinNode;
public
constructor Create;
function Fit(var Blocks: TDynBinBlockArray): Boolean;
property Width: Integer read fWidth write fWidth;
property Height: Integer read fHeight write fHeight;
property PaddingX: Integer read fPaddingX write fPaddingX;
property PaddingY: Integer read fPaddingY write fPaddingY;
end;
TLODType = (lodTerrain, lodTrees, lodObjects);
TLODTypes = set of TLODType;
TAtlasRect = record
x, y, w, h: Integer;
end;
TwbLodSettings = record
SWCell, NECell: TwbGridCell;
Stride, LODLevelMin, LODLevelMax, ObjectLevel: Integer;
procedure Init;
function GetSize: Integer;
function BlockForCell(Cell: TwbGridCell; LODLevel: Integer): TwbGridCell;
procedure LoadFromData(aData: TBytes);
property Size: Integer read GetSize;
end;
TGameResourceType = (resMesh, resTexture, resSound, resMusic, resMaterial);
// source texture for atlas builder
TSourceAtlasTexture = record
Name: string;
Name_n: string;
Name_s: string;
Image: TImageData;
Image_n: TImageData;
Image_s: TImageData;
AtlasName: string;
X, Y, W, H: integer;
end;
TSourceAtlasTextures = array of TSourceAtlasTexture;
{============================== Skyrim LOD ===================================}
// entry in LST file
TwbLodTES5TreeType = packed record
Index: Integer;
Width: Single;
Height: Single;
UVMinX, UVMinY: Single;
UVMaxX, UVMaxY: Single;
Unknown: Integer;
end;
// entry in BTT file
TwbLodTES5TreeRef = packed record
X, Y, Z: Single;
Rotation: Single; // 0..2*Pi
Scale: Single;
RefFormID: TwbFormID;
Unknown1: Integer;
Unknown2: Integer;
end;
// tree data when building lod
TwbLodTES5Tree = record
Index : Integer;
FormID: TwbFormID;
Billboard: string;
CRC32: Integer;
Width, Height: Single;
ShiftX, ShiftY, ShiftZ, ScaleFactor: Single;
Image: TImageData;
function LoadFromData(aData: TBytes): Boolean;
end;
PwbLodTES5Tree = ^TwbLodTES5Tree;
// handling atlas and LST file
TwbLodTES5TreeList = class
private
fWorldspaceID: string;
// structure for LST file
fTreesList: array of TwbLodTES5TreeType;
// list of trees when building a new LOD
fTrees: array of TwbLodTES5Tree;
fAtlas: TImageData;
// list of tree references FormID numbers to avoid duplicates
fRefFormIDs: TList;
fRefAllowDuplicates: Boolean;
protected
function GetListFileName: string;
function GetAtlasFileName: string;
function GetTreesListCount: Integer;
function GetTreesList(Index: Integer): TwbLodTES5TreeType;
function GetAtlasRect(Index: Integer): TAtlasRect;
function GetTreeByFormID(aFormID: TwbFormID): PwbLodTES5Tree;
public
constructor Create(WorldspaceID: string);
destructor Destroy; override;
procedure LoadFromData(aData: TBytes);
procedure SaveToFile(aFileName: string);
procedure LoadAtlas(aData: TBytes);
function SaveAtlas(aFileName: string): Boolean;
procedure ChangeAtlasBrightness(aBrightness: integer);
procedure SaveFromAtlas(aIndex: Integer; aFileName: string);
procedure CopyFromAtlas(aIndex: Integer; var Img: TImageData; ImgX, ImgY: Integer);
function BuildAtlas(MaxAtlasSize: Integer): Boolean;
function BillboardFileName(aFileName, aModelName: string; aFormID: TwbFormID): string;
function AddTree(aFileName, aModelName: string; aFormID: TwbFormID; aWidth, aHeight: Single): PwbLodTES5Tree;
property WorldspaceID: string read fWorldspaceID write fWorldspaceID;
property ListFileName: string read GetListFileName;
property AtlasFileName: string read GetAtlasFileName;
property TreesListCount: Integer read GetTreesListCount;
property TreesList[Index: Integer]: TwbLodTES5TreeType read GetTreesList;
property AtlasRect[Index: Integer]: TAtlasRect read GetAtlasRect;
property Atlas: TImageData read fAtlas;
property TreeByFormID[aFormID: TwbFormID]: PwbLodTES5Tree read GetTreeByFormID;
property RefAllowDuplicates: Boolean read fRefAllowDuplicates write fRefAllowDuplicates;
property RefFormIDs: TList read fRefFormIDs;
end;
// handling BTT file
TwbLodTES5TreeBlock = record
TreeList: TwbLodTES5TreeList;
Cell: TwbGridCell;
LODLevel: Integer;
Types: array of record Index, Count: Integer; end;
Refs: array of array of TwbLodTES5TreeRef;
function GetBlockFileName: string;
procedure Init(Trees: TwbLodTES5TreeList; aCell: TwbGridCell; aLODLevel: Integer = 4);
procedure Clear;
procedure LoadFromData(aData: TBytes);
procedure SaveToFile(aFileName: string);
function AddReference(aFormID: TwbFormID; aTreeIndex: Integer;
Pos: TwbVector; Scale: Single): Boolean;
property FileName: string read GetBlockFileName;
end;
function wbLODExtraOptionsFileName(const PluginName, WorldspaceID: string): string;
function wbLODSettingsFileName(const WorldspaceID: string): string;
function wbLODTreeBlockFileExt: string;
function wbNormalizeResourceName(const aName: string; aResType: TGameResourceType): string;
function wbDefaultNormalTexture(aGameMode: TwbGameMode): string;
function wbDefaultSpecularTexture(aGameMode: TwbGameMode): string;
procedure wbPrepareImageAlpha(img: TImageData; fmt: TImageFormat; threshold: Integer = 0);
procedure wbGetUVRangeTexturesList(slMeshes, slTextures: TStrings; UVRange: Single = 1.2);
procedure wbBuildAtlas(
var Images: TSourceAtlasTextures;
aWidth, aHeight: Integer;
aName: string;
fmtDiffuse, fmtNormal, fmtSpecular: TImageFormat;
alphaThreshold: Integer
);
procedure wbBuildAtlasFromTexturesList(
slTextures: TStrings;
aMaxTextureSize,
aMaxTileSize,
aWidth, aHeight: integer;
aName, aMapName: string;
const Settings: TCustomIniFile
);
procedure wbBuildAtlasFromAtlasMap(slMap: TStrings; aBrightness: integer;
GammaR, GammaG, GammaB: Single; const Settings: TCustomIniFile);
procedure wbGenerateLODTES4(const aWorldspace: IwbMainRecord; const Settings: TCustomIniFile);
procedure wbSplitTreeLOD(const aWorldspace: IwbMainRecord; const Files: TDynFiles);
procedure wbGenerateLODTES5(
const aWorldspace: IwbMainRecord;
const LODTypes: TLODTypes;
const Files: TDynFiles;
const Settings: TCustomIniFile
);
procedure wbGenerateLODFO4(
const aWorldspace: IwbMainRecord;
const Files: TDynFiles;
const Settings: TCustomIniFile
);
const
// vanilla lOD meshes having translation/rotation that must be ignored
sMeshIgnoreTranslationTES5 =
'meshes\lod\solitude\cwtower01_lod.nif' + ',' +
'meshes\lod\solitude\sfarmhousesilo_lod.nif' + ',' +
'meshes\lod\solitude\slumbermill01_lod.nif' + ',' +
'meshes\lod\solitude\spatiowall02_lod.nif' + ',' +
'meshes\lod\solitude\spatiowall03_lod.nif' + ',' +
'meshes\lod\solitude\spatiowall30_lod.nif' + ',' +
'meshes\lod\solitude\spatiowallsteps01_lod.nif' + ',' +
'meshes\lod\solitude\spatiowallsteps02_lod.nif' + ',' +
'meshes\lod\solitude\sstyrrshouse_lod.nif' + ',' +
'meshes\lod\solitude\sthe winking skeever_lod.nif' + ',' +
'meshes\lod\windhelm\wharena_lod.nif' + ',' +
'meshes\lod\windhelm\whbrunwulfsq_lod.nif' + ',' +
'meshes\lod\windhelm\whgrayquarter_lod.nif' + ',' +
'meshes\lod\windhelm\whinnerwall01_lod.nif' + ',' +
'meshes\lod\windhelm\whinnerwall02_lod.nif' + ',' +
'meshes\lod\windhelm\whinnland_lod.nif' + ',' +
'meshes\lod\windhelm\whmaingate_lod.nif' + ',' +
'meshes\lod\windhelm\whmarket01_lod.nif' + ',' +
'meshes\lod\windhelm\whouterwall3_lod.nif' + ',' +
'meshes\lod\windhelm\whpalace_lod.nif' + ',' +
'meshes\lod\windhelm\whtempletalos_lod.nif' + ',' +
'meshes\lod\windhelm\whvalunstrad_lod.nif';
sMeshIgnoreTranslationFNV = 'nif'; // all LOD meshes
// vanilla lOD meshes to treat as untiled even though they have large UV values
sMeshForceUntiled =
// Skyrim
'meshes\lod\whiterun\wrplainsdistrictterrainlod_lod.nif' +
',meshes\lod\whiterun\wrplainsdistrictterrainlod_lod_2.nif' +
// Fallout 4
',meshes\lod\landscape\roads\bridge\roadstrbridgemidend02_lod_0.nif' +
',meshes\lod\neighborhoods\esplanade\esplanade_bld20lod.nif';
implementation
uses
Math;
function wbLODExtraOptionsFileName(const PluginName, WorldspaceID: string): string;
begin
Result := wbAppName + 'LODGen_' + PluginName + '_' + WorldSpaceID + '_Options.txt';
end;
function wbLODSettingsFileName(const WorldspaceID: string): string;
begin
if wbGameMode = gmTES4 then
Result := ''
else if wbIsFallout3 then
Result := 'lodsettings\' + WorldspaceID + '.dlodsettings'
else
Result := 'lodsettings\' + WorldspaceID + '.lod';
end;
function wbLODTreeBlockFileExt: string;
begin
if wbIsSkyrim then
Result := 'btt'
else if wbIsFallout3 then
Result := 'dtl'
else
Result := '';
end;
function wbDefaultNormalTexture(aGameMode: TwbGameMode): string;
begin
if wbIsFallout4 then
Result := 'textures\shared\flatflat_n.dds'
else if wbIsSkyrim then
Result := 'textures\default_n.dds'
else if wbIsFallout3 then
Result := 'textures\shared\shadefade01_n.dds'
else
Result := '';
end;
function wbDefaultSpecularTexture(aGameMode: TwbGameMode): string;
begin
if wbIsFallout4 then
Result := 'textures\shared\white01_s.dds'
else
Result := '';
end;
{ TwbLodSettings }
procedure TwbLodSettings.Init;
begin
LODLevelMin := 4;
LODLevelMax := 32;
end;
function TwbLodSettings.GetSize: Integer;
begin
Result := Ceil(Stride/sqrt(2));
end;
function TwbLodSettings.BlockForCell(Cell: TwbGridCell; LODLevel: Integer): TwbGridCell;
begin
Result.x := SWCell.x + ((Cell.x - SWCell.x) div LODLevel) * LODLevel;
Result.y := SWCell.y + ((Cell.y - SWCell.y) div LODLevel) * LODLevel;
end;
procedure TwbLodSettings.LoadFromData(aData: TBytes);
const
sError = 'Invalid lodsettings file';
begin
// Fallouts
if wbIsFallout3 then begin
if Length(aData) <> 24 then
raise Exception.Create(sError);
LODLevelMin := PInteger(@aData[0])^;
LODLevelMax := PInteger(@aData[4])^;
Stride := PInteger(@aData[8])^;
SWCell.x := PSmallInt(@aData[12])^;
SWCell.y := PSmallInt(@aData[14])^;
NECell.x := PSmallInt(@aData[16])^;
NECell.y := PSmallInt(@aData[18])^;
ObjectLevel := PInteger(@aData[20])^;
end
// Skyrim
else begin
if Length(aData) <> 16 then
raise Exception.Create(sError);
SWCell.x := PSmallInt(@aData[0])^;
SWCell.y := PSmallInt(@aData[2])^;
Stride := PInteger(@aData[4])^;
LODLevelMin := PInteger(@aData[8])^;
LODLevelMax := PInteger(@aData[12])^;
end;
end;
{ TwbBinPacker }
constructor TwbBinPacker.Create;
begin
fWidth := 1024;
fHeight := 1024;
fPaddingX := 0;
fPaddingY := 0;
end;
procedure TwbBinPacker.Clear(Node: PBinNode);
begin
if Assigned(Node) then begin
Clear(Node^.right);
Clear(Node^.down);
Dispose(Node);
end;
end;
procedure TwbBinPacker.NewNode(var Node: PBinNode);
begin
New(Node);
FillChar(Node^, SizeOf(TBinNode), 0);
end;
function TwbBinPacker.FindNode(root: PBinNode; w, h: Integer): PBinNode;
begin
if root^.used then begin
Result := FindNode(root^.right, w, h);
if not Assigned(Result) then
Result := FindNode(root^.down, w, h);
end
else if (w <= root^.w) and (h <= root^.h) then
Result := root
else
Result := nil;
end;
function TwbBinPacker.SplitNode(node: PBinNode; w, h: Integer): PBinNode;
begin
node^.used := True;
NewNode(node^.down);
node^.down^.x := node^.x;
node^.down^.y := node^.y + h + fPaddingY;
node^.down^.w := node^.w;
node^.down^.h := node^.h - h - fPaddingY;
NewNode(node^.right);
node^.right^.x := node^.x + w + fPaddingX;
node^.right^.y := node^.y;
node^.right^.w := node^.w - w - fPaddingX;
node^.right^.h := h;
Result := node;
end;
function TwbBinPacker.Fit(var Blocks: TDynBinBlockArray): Boolean;
procedure MaxSideSort(var Blocks: TDynBinBlockArray);
var
i: Integer;
changed: Boolean;
temp: TBinBlock;
begin
changed := True;
while changed do begin
changed := False;
for i := Low(Blocks) to Pred(High(Blocks)) do
if Max(Blocks[i].w, Blocks[i].h) < Max(Blocks[i+1].w, Blocks[i+1].h) then begin
//if Blocks[i].w * Blocks[i].h < Blocks[i+1].w * Blocks[i+1].h then begin
temp := Blocks[i+1];
Blocks[i+1] := Blocks[i];
Blocks[i] := temp;
changed := True;
end;
end;
end;
var
i: integer;
node: PBinNode;
begin
Result := True;
NewNode(fRoot);
fRoot^.w := fWidth;
fRoot^.h := fHeight;
MaxSideSort(Blocks);
for i := Low(Blocks) to High(Blocks) do begin
node := FindNode(fRoot, Blocks[i].w, Blocks[i].h);
if Assigned(node) then begin
node := SplitNode(node, Blocks[i].w, Blocks[i].h);
Blocks[i].x := node^.x;
Blocks[i].y := node^.y;
Blocks[i].fit := True;
end else
Result := False;
end;
Clear(fRoot);
fRoot := nil;
end;
{============================== Skyrim LOD ===================================}
{ TwbLodTES5Tree }
function TwbLodTES5Tree.LoadFromData(aData: TBytes): Boolean;
begin
InitImage(Image);
Result := LoadImageFromMemory(@aData[0], Length(aData), Image);
end;
{ TwbLodTES5TreeList }
constructor TwbLodTES5TreeList.Create(WorldspaceID: string);
begin
fWorldspaceID := WorldspaceID;
if fWorldspaceID = '' then
fWorldspaceID := 'Tamriel';
RefAllowDuplicates := False;
fRefFormIDs := TList.Create;
end;
destructor TwbLodTES5TreeList.Destroy;
var
i: Integer;
begin
if fAtlas.Format <> ifUnknown then
FreeImage(fAtlas);
for i := Low(fTrees) to High(fTrees) do
if fTrees[i].Image.Format <> ifUnknown then
FreeImage(fTrees[i].Image);
fRefFormIDs.Free;
inherited;
end;
function TwbLodTES5TreeList.GetListFileName: string;
begin
if wbIsSkyrim then
Result := 'Meshes\Terrain\' + fWorldspaceID + '\Trees\' + fWorldspaceID + '.lst'
else if wbIsFallout3 then
Result := 'Meshes\Landscape\LOD\' + fWorldspaceID + '\Trees\TreeTypes.lst'
else
Result := '';
end;
function TwbLodTES5TreeList.GetAtlasFileName: string;
begin
if wbIsSkyrim then
Result := 'Textures\Terrain\' + fWorldspaceID + '\Trees\' + fWorldspaceID + 'TreeLod.dds'
else if wbIsFallout3 then begin
if SameText(Copy(fWorldspaceID, 1, 4), 'DLC4') then
Result := 'Textures\Landscape\Trees\TreeSwampLod.dds'
else
Result := 'Textures\Landscape\Trees\TreeDeadLod.dds';
end else
Result := '';
end;
function TwbLodTES5TreeList.GetTreesListCount: Integer;
begin
Result := Length(fTreesList);
end;
function TwbLodTES5TreeList.GetTreesList(Index: Integer): TwbLodTES5TreeType;
begin
Result := fTreesList[Index];
end;
function TwbLodTES5TreeList.GetAtlasRect(Index: Integer): TAtlasRect;
begin
if fAtlas.Format = ifUnknown then
Exit;
with TreesList[Index] do begin
Result.x := Round(fAtlas.Width * UVMinX);
Result.y := Round(fAtlas.Height * UVMinY);
Result.w := Round(fAtlas.Width * (UVMaxX - UVMinX));
Result.h := Round(fAtlas.Height * (UVMaxY - UVMinY));
end;
end;
function TwbLodTES5TreeList.GetTreeByFormID(aFormID: TwbFormID): PwbLodTES5Tree;
var
i: Integer;
begin
Result := nil;
for i := Low(fTrees) to High(fTrees) do
if fTrees[i].FormID = aFormID then begin
Result := @fTrees[i];
Break;
end;
end;
function TwbLodTES5TreeList.BillboardFileName(aFileName, aModelName: string; aFormID: TwbFormID): string;
begin
Result := Format('Textures\Terrain\LODGen\%s\%s_%s.dds', [
aFileName,
ChangeFileExt(ExtractFileName(aModelName), ''),
aFormID.ChangeFileID(TwbFileID.Null).ToString(False)
]);
end;
function TwbLodTES5TreeList.AddTree(aFileName, aModelName: string; aFormID: TwbFormID; aWidth, aHeight: Single): PwbLodTES5Tree;
var
i, idx: integer;
begin
idx := -1;
for i := Low(fTrees) to High(fTrees) do
if fTrees[i].Index > idx then idx := fTrees[i].Index;
SetLength(fTrees, Succ(Length(fTrees)));
Result := @fTrees[Pred(Length(fTrees))];
Result^.Index := Succ(idx);
Result^.FormID := aFormID;
Result^.BillBoard := BillboardFileName(aFileName, aModelName, aFormID);
Result^.Width := aWidth;
Result^.Height := aHeight;
Result^.ShiftX := 0.0;
Result^.ShiftY := 0.0;
Result^.ShiftZ := 0.0;
Result^.ScaleFactor := 1.0;
end;
procedure TwbLodTES5TreeList.LoadFromData(aData: TBytes);
var
TreesNum: integer;
begin
if Length(aData) < SizeOf(Integer) then begin
SetLength(fTreesList, 0);
Exit;
end;
TreesNum := PInteger(@aData[0])^;
if Length(aData) - 4 < SizeOf(TwbLodTES5TreeType) * TreesNum then
raise Exception.Create('Invalid LST file');
SetLength(fTreesList, TreesNum);
Move(aData[4], fTreesList[0], SizeOf(TwbLodTES5TreeType) * TreesNum);
end;
procedure TwbLodTES5TreeList.SaveToFile(aFileName: string);
var
Value: Integer;
begin
if TreesListCount > 0 then
with TFileStream.Create(aFileName, fmCreate) do try
Value := TreesListCount;
Write(Value, SizeOf(Value));
Write(fTreesList[0], SizeOf(TwbLodTES5TreeType) * TreesListCount);
finally
Free;
end;
end;
procedure TwbLodTES5TreeList.LoadAtlas(aData: TBytes);
begin
InitImage(fAtlas);
LoadImageFromMemory(@aData[0], Length(aData), fAtlas);
end;
function TwbLodTES5TreeList.SaveAtlas(aFileName: string): Boolean;
var
MipmapImg: TDynImageDataArray;
begin
SetOption(ImagingMipMapFilter, Ord(sfLanczos));
try
Result := ConvertImage(fAtlas, ifDXT3);
if not Result then
raise Exception.Create('Can''t compress atlas')
else
Result := GenerateMipMaps(fAtlas, 0, MipmapImg);
if not Result then
raise Exception.Create('Can''t generate mipmaps')
else
Result := SaveMultiImageToFile(aFileName, MipmapImg);
finally
FreeImagesInArray(MipmapImg);
end;
end;
procedure TwbLodTES5TreeList.ChangeAtlasBrightness(aBrightness: integer);
var
Canvas: TImagingCanvas;
begin
if aBrightness = 0 then
Exit;
Canvas := TImagingCanvas.CreateForData(@fAtlas);
try
Canvas.ModifyContrastBrightness(aBrightness / 10, aBrightness);
finally
Canvas.Free;
end;
end;
procedure TwbLodTES5TreeList.SaveFromAtlas(aIndex: Integer; aFileName: string);
var
img: TImageData;
begin
if fAtlas.Format = ifUnknown then
Exit;
with AtlasRect[aIndex] do begin
NewImage(w, h, ifDXT3, img);
try
CopyRect(fAtlas, x, y, w, h, img, 0, 0);
SaveImageToFile(aFileName, img);
finally
FreeImage(img);
end;
end;
end;
procedure TwbLodTES5TreeList.CopyFromAtlas(aIndex: Integer; var Img: TImageData; ImgX, ImgY: Integer);
begin
if fAtlas.Format = ifUnknown then
Exit;
with AtlasRect[aIndex] do
CopyRect(fAtlas, x, y, w, h, Img, ImgX, ImgY);
end;
function TwbLodTES5TreeList.BuildAtlas(MaxAtlasSize: Integer): Boolean;
var
i, j, k: Integer;
Blocks: TDynBinBlockArray;
begin
for i := Low(fTrees) to High(fTrees) do begin
// skip trees with missing/invalid textures
if fTrees[i].Index = -1 then
Continue;
// exclude duplicate textures by checksum
k := -1;
for j := Low(fTrees) to i - 1 do
if fTrees[j].CRC32 = fTrees[i].CRC32 then begin
k := j;
Break;
end;
if k <> -1 then
Continue;
SetLength(Blocks, Succ(Length(Blocks)));
with Blocks[Pred(Length(Blocks))] do begin
Index := fTrees[i].Index;
w := fTrees[i].Image.Width;
h := fTrees[i].Image.Height;
Data := fTrees[i].CRC32;
end;
end;
Result := False;
if Length(Blocks) = 0 then
Exit;
with TwbBinPacker.Create do try
Width := Min(512, MaxAtlasSize);
Height := Min(512, MaxAtlasSize);
PaddingX := 2;
PaddingY := 2;
// increase atlas size until all blocks fit
while not Fit(Blocks) do begin
if Width <= Height then
Width := Width * 2
else
Height := Height * 2;
if (Width > MaxAtlasSize) or (Height > MaxAtlasSize) then
raise Exception.Create('Can''t fit billboards on atlas, not enough space');
end;
NewImage(Width, Height, ifDefault, fAtlas);
finally
Free;
end;
// drawing atlas and creating a list of trees with UVs
for i := Low(fTrees) to High(fTrees) do begin
if fTrees[i].Index = -1 then
Continue;
// getting atlas block by checksum
for j := Low(Blocks) to High(Blocks) do
if Blocks[j].Data = fTrees[i].CRC32 then
Break;
if not CopyRect(fTrees[i].Image, 0, 0, Blocks[j].w, Blocks[j].h, fAtlas, Blocks[j].x, Blocks[j].y) then
raise Exception.Create('Error when drawing atlas');
SetLength(fTreesList, Succ(Length(fTreesList)));
with fTreesList[Pred(Length(fTreesList))] do begin
Index := fTrees[i].Index;
Width := fTrees[i].Width;
Height := fTrees[i].Height;
UVMinX := Blocks[j].x / fAtlas.Width;
UVMaxX := (Blocks[j].x + Blocks[j].w) / fAtlas.Width;
UVMinY := Blocks[j].y / fAtlas.Height;
UVMaxY := (Blocks[j].y + Blocks[j].h) / fAtlas.Height;
end;
end;
Result := True;
end;
{ TwbLodTES5TreeBlock }
procedure TwbLodTES5TreeBlock.Init(Trees: TwbLodTES5TreeList; aCell: TwbGridCell; aLODLevel: Integer = 4);
begin
TreeList := Trees;
Cell := aCell;
LODLevel := aLODLevel;
end;
procedure TwbLodTES5TreeBlock.Clear;
begin
SetLength(Types, 0);
SetLength(Refs, 0);
end;
function TwbLodTES5TreeBlock.GetBlockFileName: string;
begin
Result := '';
if wbIsSkyrim then
Result := 'meshes\terrain\%s\trees\%s.%d.%d.%d.' + wbLODTreeBlockFileExt
else if wbIsFallout3 then
Result := 'meshes\landscape\lod\%s\trees\%s.level%d.x%d.y%d.' + wbLODTreeBlockFileExt
else
Exit;
Result := Format(Result, [
TreeList.WorldspaceID,
TreeList.WorldspaceID,
LODLevel,
Cell.x,
Cell.y
]);
end;
procedure TwbLodTES5TreeBlock.LoadFromData(aData: TBytes);
const
sError = 'Invalid tree LOD block file';
var
TypesNum, TreesNum, i, p: integer;
begin
if Length(aData) < SizeOf(Integer) then begin
Clear;
Exit;
end;
p := 0;
TypesNum := PInteger(@aData[p])^;
Inc(p, SizeOf(Integer));
SetLength(Types, TypesNum);
SetLength(Refs, TypesNum);
for i := 0 to TypesNum - 1 do begin
if p >= Length(aData) then
raise Exception.Create(sError);
// tree type
Types[i].Index := PInteger(@aData[p])^;
Inc(p, SizeOf(Integer));
if p >= Length(aData) then
raise Exception.Create(sError);
// number of trees
TreesNum := PInteger(@aData[p])^;
Types[i].Count := TreesNum;
Inc(p, SizeOf(Integer));
if p >= Length(aData) then
raise Exception.Create(sError);
// ref array
SetLength(Refs[i], TreesNum);
Move(aData[p], Refs[i][0], SizeOf(TwbLodTES5TreeRef) * TreesNum);
Inc(p, SizeOf(TwbLodTES5TreeRef) * TreesNum);
end;
end;
procedure TwbLodTES5TreeBlock.SaveToFile(aFileName: string);
var
Value, i: Integer;
fs: TFileStream;
begin
with TMemoryStream.Create do try
Value := Length(Types);
Write(Value, SizeOf(Value));
for i := 0 to Pred(Length(Types)) do begin
Write(Types[i].Index , SizeOf(Types[i].Index));
Write(Types[i].Count , SizeOf(Types[i].Count));
Write(Refs[i][0], SizeOf(TwbLodTES5TreeRef) * Types[i].Count);
end;
fs := TFileStream.Create(aFileName, fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
finally
Free;
end;
end;
function TwbLodTES5TreeBlock.AddReference(aFormID: TwbFormID; aTreeIndex: Integer;
Pos: TwbVector; Scale: Single): Boolean;
var
i, j: integer;
begin
// check that FormID number is not duplicate
if (not TreeList.RefAllowDuplicates) and (TreeList.RefFormIDs.IndexOf(Pointer(aFormID.ObjectID)) <> -1) then begin
Result := False;
Exit;
end;
j := -1;
for i := Low(Types) to High(Types) do
if Types[i].Index = aTreeIndex then begin
j := i;
Break;
end;
if j = -1 then begin
SetLength(Types, Succ(Length(Types)));
j := Pred(Length(Types));
Types[j].Index := aTreeIndex;
SetLength(Refs, Succ(Length(Refs)));
end;
Inc(Types[j].Count);
if Types[j].Count > Length(Refs[j]) then
SetLength(Refs[j], Length(Refs[j]) + 64);
i := Pred(Types[j].Count);
Refs[j][i].RefFormID := aFormID;
Refs[j][i].X := Pos.x;
Refs[j][i].Y := Pos.y;
Refs[j][i].Z := Pos.z;
Refs[j][i].Scale := Scale;
Refs[j][i].Rotation := 2*Pi*Random;
TreeList.RefFormIDs.Add(Pointer(aFormID.ObjectID));
Result := True;
end;
function wbNormalizeResourceName(const aName: string; aResType: TGameResourceType): string;
var
i: integer;
begin
Result := Trim(StringReplace(LowerCase(aName), '/', '\', [rfReplaceAll]));
if Length(Result) < 2 then
Exit;
// absolute path, cut everything before Data or leave only file name
if Result[2] = ':' then begin
i := Pos('data\', Result);
if i <> 0 then
Delete(Result, 1, Pred(i))
else
Result := ExtractFileName(Result);
end;
// starts with slash, remove it
if Result[1] = '\' then Delete(Result, 1, 1);
// starts with Data, remove it
if Copy(Result, 1, 5) = 'data\' then Delete(Result, 1, 5);
// root folder in Data for different resource types
if (aResType = resMesh) and (Copy(Result, 1, 7) <> 'meshes\') then
Result := 'meshes\' + Result
else if (aResType = resTexture) and (Copy(Result, 1, 9) <> 'textures\') then
Result := 'textures\' + Result
else if (aResType = resSound) and (Copy(Result, 1, 6) <> 'sound\') then
Result := 'sound\' + Result
else if (aResType = resMusic) and (Copy(Result, 1, 6) <> 'music\') then
Result := 'music\' + Result
else if (aResType = resMaterial) and (Copy(Result, 1, 10) <> 'materials\') then
Result := 'materials\' + Result;
end;
procedure wbPrepareImageAlpha(img: TImageData; fmt: TImageFormat; threshold: Integer = 0);
var
x, y: integer;
c: TColor32Rec;
fmtInfo: TImageFormatInfo;
begin
// threshold = 0, convert to max alpha for formats saved without alpha, otherwise they will become black
// threshold <> 0, convert alpha to 0/1 transparency
GetImageFormatInfo(fmt, fmtInfo);
// do not convert formats that support alpha (DXT1 supports 0/1 transparancy)
if fmtINfo.HasAlphaChannel and not (fmt in [ifDXT1]) then
Exit;
// always convert formats that do not support alpha to max alpha
if not fmtINfo.HasAlphaChannel then
threshold := 0;
for x := 0 to Pred(img.Width) do
for y := 0 to Pred(img.Height) do begin