forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtextureloader.cpp
More file actions
2831 lines (2351 loc) · 71.8 KB
/
Copy pathtextureloader.cpp
File metadata and controls
2831 lines (2351 loc) · 71.8 KB
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
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : DX8 Texture Manager *
* *
* $Archive:: /Commando/Code/ww3d2/textureloader.h $*
* *
* Original Author:: vss_sync *
* *
* Author : Kenny Mitchell *
* *
* $Modtime:: 08/05/02 10:03a $*
* *
* $Revision:: 3 $*
* *
* 06/27/02 KM Texture class abstraction *
* 08/05/02 KM Texture class redesign (revisited)
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include "textureloader.h"
#include "mutex.h"
#include "thread.h"
#include "wwdebug.h"
#include "texture.h"
#include "ffactory.h"
#include "wwstring.h"
#include "bufffile.h"
#include "ww3d.h"
#include "assetmgr.h"
#include "dx8wrapper.h"
#include "dx8caps.h"
#include "missingtexture.h"
#include "TARGA.h"
#include <d3dx8tex.h>
#include "wwmemlog.h"
#include "formconv.h"
#include "texturethumbnail.h"
#include "ddsfile.h"
#include "bitmaphandler.h"
#include "wwprofile.h"
bool TextureLoader::TextureLoadSuspended;
int TextureLoader::TextureInactiveOverrideTime = 0;
#define USE_MANAGED_TEXTURES
////////////////////////////////////////////////////////////////////////////////
//
// TextureLoadTaskListClass implementation
//
////////////////////////////////////////////////////////////////////////////////
TextureLoadTaskListClass::TextureLoadTaskListClass()
: Root()
{
Root.Next = Root.Prev = &Root;
}
void TextureLoadTaskListClass::Push_Front (TextureLoadTaskClass *task)
{
// task should non-null and not on any list
WWASSERT(task != nullptr && task->Next == nullptr && task->Prev == nullptr);
// update inserted task to point to list
task->Next = Root.Next;
task->Prev = &Root;
task->List = this;
// update list to point to inserted task
Root.Next->Prev = task;
Root.Next = task;
}
void TextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task)
{
// task should be non-null and not on any list
WWASSERT(task != nullptr && task->Next == nullptr && task->Prev == nullptr);
// update inserted task to point to list
task->Next = &Root;
task->Prev = Root.Prev;
task->List = this;
// update list to point to inserted task
Root.Prev->Next = task;
Root.Prev = task;
}
TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Front()
{
// exit early if list is empty
if (Is_Empty()) {
return nullptr;
}
// otherwise, grab first task and remove it.
TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Next;
Remove(task);
return task;
}
TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Back()
{
// exit early if list is empty
if (Is_Empty()) {
return nullptr;
}
// otherwise, grab last task and remove it.
TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Prev;
Remove(task);
return task;
}
void TextureLoadTaskListClass::Remove(TextureLoadTaskClass *task)
{
// exit early if task is not on this list.
if (task->List != this) {
return;
}
// update list to skip task
task->Prev->Next = task->Next;
task->Next->Prev = task->Prev;
// update task to no longer point at list
task->Prev = nullptr;
task->Next = nullptr;
task->List = nullptr;
}
////////////////////////////////////////////////////////////////////////////////
//
// SynchronizedTextureLoadTaskListClass implementation
//
////////////////////////////////////////////////////////////////////////////////
SynchronizedTextureLoadTaskListClass::SynchronizedTextureLoadTaskListClass()
: TextureLoadTaskListClass(),
CriticalSection()
{
}
void SynchronizedTextureLoadTaskListClass::Push_Front(TextureLoadTaskClass *task)
{
FastCriticalSectionClass::LockClass lock(CriticalSection);
TextureLoadTaskListClass::Push_Front(task);
}
void SynchronizedTextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task)
{
FastCriticalSectionClass::LockClass lock(CriticalSection);
TextureLoadTaskListClass::Push_Back(task);
}
TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Front()
{
// this duplicates code inside base class, but saves us an unnecessary lock.
if (Is_Empty()) {
return nullptr;
}
FastCriticalSectionClass::LockClass lock(CriticalSection);
return TextureLoadTaskListClass::Pop_Front();
}
TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Back()
{
// this duplicates code inside base class, but saves us an unnecessary lock.
if (Is_Empty()) {
return nullptr;
}
FastCriticalSectionClass::LockClass lock(CriticalSection);
return TextureLoadTaskListClass::Pop_Back();
}
void SynchronizedTextureLoadTaskListClass::Remove(TextureLoadTaskClass *task)
{
FastCriticalSectionClass::LockClass lock(CriticalSection);
TextureLoadTaskListClass::Remove(task);
}
// Locks
// To prevent deadlock, threads should acquire locks in the order in which
// they are defined below. No ordering is necessary for the task list locks,
// since one thread can never hold two at once.
static FastCriticalSectionClass _ForegroundCriticalSection;
static FastCriticalSectionClass _BackgroundCriticalSection;
// Lists
static SynchronizedTextureLoadTaskListClass _ForegroundQueue;
static SynchronizedTextureLoadTaskListClass _BackgroundQueue;
static TextureLoadTaskListClass _TexLoadFreeList;
static TextureLoadTaskListClass _CubeTexLoadFreeList;
static TextureLoadTaskListClass _VolTexLoadFreeList;
// The background texture loading thread.
static class LoaderThreadClass : public ThreadClass
{
public:
#ifdef Exception_Handler
LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name, &Exception_Handler) {}
#else
LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name) {}
#endif
virtual void Thread_Function() override;
} _TextureLoadThread;
// TODO: Legacy - remove this call!
IDirect3DTexture8* Load_Compressed_Texture(
const StringClass& filename,
unsigned reduction_factor,
MipCountType mip_level_count,
WW3DFormat dest_format)
{
// If DDS file isn't available, use TGA file to convert to DDS.
DDSFileClass dds_file(filename,reduction_factor);
if (!dds_file.Is_Available()) return nullptr;
if (!dds_file.Load()) return nullptr;
unsigned width=dds_file.Get_Width(0);
unsigned height=dds_file.Get_Height(0);
unsigned mips=dds_file.Get_Mip_Level_Count();
// If format isn't defined get the nearest valid texture format to the compressed file format
// Note that the nearest valid format could be anything, even uncompressed.
if (dest_format==WW3D_FORMAT_UNKNOWN) dest_format=Get_Valid_Texture_Format(dds_file.Get_Format(),true);
IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture
(
width,
height,
dest_format,
(MipCountType)mips
);
for (unsigned level=0;level<mips;++level) {
IDirect3DSurface8* d3d_surface=nullptr;
WWASSERT(d3d_texture);
DX8_ErrorCode(d3d_texture->GetSurfaceLevel(level/*-reduction_factor*/,&d3d_surface));
dds_file.Copy_Level_To_Surface(level,d3d_surface);
d3d_surface->Release();
}
return d3d_texture;
}
static bool Is_Format_Compressed(WW3DFormat texture_format,bool allow_compression)
{
// Verify that the user isn't requesting compressed texture without hardware support
bool compressed=false;
if (texture_format!=WW3D_FORMAT_UNKNOWN) {
if (!DX8Wrapper::Get_Current_Caps()->Support_DXTC() || !allow_compression) {
WWASSERT(texture_format!=WW3D_FORMAT_DXT1);
WWASSERT(texture_format!=WW3D_FORMAT_DXT2);
WWASSERT(texture_format!=WW3D_FORMAT_DXT3);
WWASSERT(texture_format!=WW3D_FORMAT_DXT4);
WWASSERT(texture_format!=WW3D_FORMAT_DXT5);
}
if (texture_format==WW3D_FORMAT_DXT1 ||
texture_format==WW3D_FORMAT_DXT2 ||
texture_format==WW3D_FORMAT_DXT3 ||
texture_format==WW3D_FORMAT_DXT4 ||
texture_format==WW3D_FORMAT_DXT5) {
compressed=true;
}
}
// If hardware supports DXTC compression, load a compressed texture. Proceed only if the texture format hasn't been
// defined as non-compressed.
compressed|=(
texture_format==WW3D_FORMAT_UNKNOWN &&
DX8Wrapper::Get_Current_Caps()->Support_DXTC() &&
allow_compression);
return compressed;
}
////////////////////////////////////////////////////////////////////////////////
//
// TextureLoader implementation
//
////////////////////////////////////////////////////////////////////////////////
void TextureLoader::Init()
{
WWASSERT(!_TextureLoadThread.Is_Running());
ThumbnailManagerClass::Init();
_TextureLoadThread.Execute();
_TextureLoadThread.Set_Priority(-4);
TextureInactiveOverrideTime = 0;
}
void TextureLoader::Deinit()
{
FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection);
_TextureLoadThread.Stop();
ThumbnailManagerClass::Deinit();
TextureLoadTaskClass::Delete_Free_Pool();
}
bool TextureLoader::Is_DX8_Thread()
{
return (ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID());
}
// ----------------------------------------------------------------------------
//
// Modify given texture size to nearest valid size on current hardware.
//
// ----------------------------------------------------------------------------
void TextureLoader::Validate_Texture_Size
(
unsigned& width,
unsigned& height,
unsigned& depth
)
{
const D3DCAPS8& dx8caps=DX8Wrapper::Get_Current_Caps()->Get_DX8_Caps();
unsigned poweroftwowidth = 1;
while (poweroftwowidth < width)
{
poweroftwowidth <<= 1;
}
unsigned poweroftwoheight = 1;
while (poweroftwoheight < height)
{
poweroftwoheight <<= 1;
}
unsigned poweroftwodepth = 1;
while (poweroftwodepth< depth)
{
poweroftwodepth <<= 1;
}
if (poweroftwowidth>dx8caps.MaxTextureWidth)
{
poweroftwowidth=dx8caps.MaxTextureWidth;
}
if (poweroftwoheight>dx8caps.MaxTextureHeight)
{
poweroftwoheight=dx8caps.MaxTextureHeight;
}
if (poweroftwodepth>dx8caps.MaxVolumeExtent)
{
poweroftwodepth=dx8caps.MaxVolumeExtent;
}
if (poweroftwowidth>poweroftwoheight)
{
while (poweroftwowidth/poweroftwoheight>8)
{
poweroftwoheight*=2;
}
}
else
{
while (poweroftwoheight/poweroftwowidth>8)
{
poweroftwowidth*=2;
}
}
width=poweroftwowidth;
height=poweroftwoheight;
depth=poweroftwodepth;
}
IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename, const Vector3& hsv_shift)//,WW3DFormat texture_format)
{
WWASSERT(Is_DX8_Thread());
ThumbnailClass* thumb=nullptr;
thumb=ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(filename);
// If no thumb is found return a missing texture
if (!thumb) {
return MissingTexture::_Get_Missing_Texture();
}
WWASSERT(thumb->Get_Format()==WW3D_FORMAT_A4R4G4B4);
unsigned src_pitch=thumb->Get_Width()*2; // Thumbs are always 16 bits
WW3DFormat dest_format;
WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN;
if (texture_format==WW3D_FORMAT_UNKNOWN) {
dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A4R4G4B4,false); // no compressed formats please
}
else {
dest_format=Get_Valid_Texture_Format(texture_format,false); // no compressed formats please
WWASSERT(dest_format==texture_format);
}
IDirect3DTexture8* sysmem_texture = DX8Wrapper::_Create_DX8_Texture(
thumb->Get_Width(),
thumb->Get_Height(),
dest_format,
MIP_LEVELS_ALL,
#ifdef USE_MANAGED_TEXTURES
D3DPOOL_MANAGED);
#else
D3DPOOL_SYSTEMMEM);
#endif
unsigned level=0;
D3DLOCKED_RECT locked_rects[12]={0};
WWASSERT(sysmem_texture->GetLevelCount()<=12);
// Lock all surfaces
for (level=0;level<sysmem_texture->GetLevelCount();++level) {
DX8_ErrorCode(
sysmem_texture->LockRect(
level,
&locked_rects[level],
nullptr,
0));
}
unsigned char* src_surface=thumb->Peek_Bitmap();
WW3DFormat src_format=thumb->Get_Format();
unsigned width=thumb->Get_Width();
unsigned height=thumb->Get_Height();
Vector3 hsv=hsv_shift;
for (level=0;level<sysmem_texture->GetLevelCount()-1;++level) {
BitmapHandlerClass::Copy_Image_Generate_Mipmap(
width,
height,
(unsigned char*)locked_rects[level].pBits,
locked_rects[level].Pitch,
dest_format,
src_surface,
src_pitch,
src_format,
(unsigned char*)locked_rects[level+1].pBits, // mipmap
locked_rects[level+1].Pitch,
hsv);
hsv=Vector3(0.0f,0.0f,0.0f); // Only do the shift for the first level, as the mipmaps are based on it.
src_format=dest_format;
src_surface=(unsigned char*)locked_rects[level].pBits;
src_pitch=locked_rects[level].Pitch;
width>>=1;
height>>=1;
}
// Unlock all surfaces
for (level=0;level<sysmem_texture->GetLevelCount();++level) {
DX8_ErrorCode(sysmem_texture->UnlockRect(level));
}
#ifdef USE_MANAGED_TEXTURES
return sysmem_texture;
#else
IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture(
thumb->Get_Width(),
thumb->Get_Height(),
dest_format,
TextureBaseClass::MIP_LEVELS_ALL,
D3DPOOL_DEFAULT);
DX8CALL(UpdateTexture(sysmem_texture,d3d_texture));
sysmem_texture->Release();
WWDEBUG_SAY(("Created non-managed texture (%s)",filename));
return d3d_texture;
#endif
}
// ----------------------------------------------------------------------------
//
// Load image to a surface. The function tries to create texture that matches
// targa format. If suitable format is not available, it selects closest matching
// format and performs color space conversion.
//
// ----------------------------------------------------------------------------
IDirect3DSurface8* TextureLoader::Load_Surface_Immediate(
const StringClass& filename,
WW3DFormat texture_format,
bool allow_compression)
{
WWASSERT(Is_DX8_Thread());
bool compressed=Is_Format_Compressed(texture_format,allow_compression);
if (compressed) {
IDirect3DTexture8* comp_tex=Load_Compressed_Texture(filename,0,MIP_LEVELS_1,WW3D_FORMAT_UNKNOWN);
if (comp_tex) {
IDirect3DSurface8* d3d_surface=nullptr;
DX8_ErrorCode(comp_tex->GetSurfaceLevel(0,&d3d_surface));
comp_tex->Release();
return d3d_surface;
}
}
// Make sure the file can be opened. If not, return missing texture.
Targa targa;
if (TARGA_ERROR_HANDLER(targa.Open(filename, TGA_READMODE),filename)) return MissingTexture::_Create_Missing_Surface();
// DX8 uses image upside down compared to TGA
targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN;
WW3DFormat src_format,dest_format;
unsigned src_bpp=0;
Get_WW3D_Format(dest_format,src_format,src_bpp,targa);
if (texture_format!=WW3D_FORMAT_UNKNOWN) {
dest_format=texture_format;
}
// Destination size will be the next power of two square from the larger width and height...
unsigned width, height;
width=targa.Header.Width;
height=targa.Header.Height;
unsigned src_width=targa.Header.Width;
unsigned src_height=targa.Header.Height;
// NOTE: We load the palette but we do not yet support paletted textures!
char palette[256*4];
targa.SetPalette(palette);
if (TARGA_ERROR_HANDLER(targa.Load(filename, TGAF_IMAGE, false),filename)) return MissingTexture::_Create_Missing_Surface();
unsigned char* src_surface=(unsigned char*)targa.GetImage();
// No paletted destination format allowed
unsigned char* converted_surface=nullptr;
if (src_format==WW3D_FORMAT_A1R5G5B5 || src_format==WW3D_FORMAT_R5G6B5 || src_format==WW3D_FORMAT_A4R4G4B4 ||
src_format==WW3D_FORMAT_P8 || src_format==WW3D_FORMAT_L8 || src_width!=width || src_height!=height) {
converted_surface=W3DNEWARRAY unsigned char[width*height*4];
dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8,false);
BitmapHandlerClass::Copy_Image(
converted_surface,
width,
height,
width*4,
WW3D_FORMAT_A8R8G8B8,//dest_format,
src_surface,
src_width,
src_height,
src_width*src_bpp,
src_format,
(unsigned char*)targa.GetPalette(),
targa.Header.CMapDepth>>3,
false);
src_surface=converted_surface;
src_format=WW3D_FORMAT_A8R8G8B8;//dest_format;
src_width=width;
src_height=height;
src_bpp=Get_Bytes_Per_Pixel(src_format);
}
unsigned src_pitch=src_width*src_bpp;
IDirect3DSurface8* d3d_surface = DX8Wrapper::_Create_DX8_Surface(width,height,dest_format);
WWASSERT(d3d_surface);
D3DLOCKED_RECT locked_rect;
DX8_ErrorCode(
d3d_surface->LockRect(
&locked_rect,
nullptr,
0));
BitmapHandlerClass::Copy_Image(
(unsigned char*)locked_rect.pBits,
width,
height,
locked_rect.Pitch,
dest_format,
src_surface,
src_width,
src_height,
src_pitch,
src_format,
(unsigned char*)targa.GetPalette(),
targa.Header.CMapDepth>>3,
false); // No mipmap
DX8_ErrorCode(d3d_surface->UnlockRect());
delete[] converted_surface;
return d3d_surface;
}
void TextureLoader::Request_Thumbnail(TextureBaseClass *tc)
{
// Grab the foreground lock. This prevents the foreground thread
// from retiring any tasks related to this texture. It also
// serializes calls to Request_Thumbnail from multiple threads.
FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection);
// Has a Direct3D texture already been loaded?
if (tc->Peek_D3D_Base_Texture()) {
return;
}
TextureLoadTaskClass *task = tc->ThumbnailLoadTask;
if (Is_DX8_Thread()) {
// load the thumbnail immediately
TextureLoader::Load_Thumbnail(tc);
// clear any pending thumbnail load
if (task) {
_ForegroundQueue.Remove(task);
task->Destroy();
}
} else {
TextureLoadTaskClass *load_task = tc->TextureLoadTask;
// if texture is not already loading a thumbnail and there is no
// background load near completion. (a background load waiting
// to be applied will be ready at the same time as a queued thumbnail.
// Why do the extra work?)
if (!task && (!load_task || load_task->Get_State() < TextureLoadTaskClass::STATE_LOAD_MIPMAP)) {
// create a thumbnail load task and add to foreground queue.
task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_THUMBNAIL, TextureLoadTaskClass::PRIORITY_LOW);
_ForegroundQueue.Push_Back(task);
}
}
}
void TextureLoader::Request_Background_Loading(TextureBaseClass *tc)
{
WWPROFILE(("TextureLoader::Request_Background_Loading()"));
// Grab the foreground lock. This prevents the foreground thread
// from retiring any tasks related to this texture. It also
// serializes calls to Request_Background_Loading from other
// threads.
FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection);
// Has the texture already been loaded?
if (tc->Is_Initialized()) {
return;
}
TextureLoadTaskClass *task = tc->TextureLoadTask;
// if texture already has a load task, we don't need to create another one.
if (task) {
return;
}
task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_LOW);
if (Is_DX8_Thread()) {
Begin_Load_And_Queue(task);
} else {
_ForegroundQueue.Push_Back(task);
}
}
void TextureLoader::Request_Foreground_Loading(TextureBaseClass *tc)
{
WWPROFILE(("TextureLoader::Request_Foreground_Loading()"));
// Grab the foreground lock. This prevents the foreground thread
// from retiring the load tasks for this texture. It also
// serializes calls to Request_Foreground_Loading from other
// threads.
FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection);
// Has the texture already been loaded?
if (tc->Is_Initialized()) {
return;
}
TextureLoadTaskClass *task = tc->TextureLoadTask;
TextureLoadTaskClass *task_thumb = tc->ThumbnailLoadTask;
if (Is_DX8_Thread()) {
// since we're in the DX8 thread, we can load the entire
// texture right now.
// if we have a thumbnail task waiting, kill it.
if (task_thumb) {
_ForegroundQueue.Remove(task_thumb);
task_thumb->Destroy();
}
if (task) {
// we need to remove the task from any queue, since we're going
// to finish it up right now.
// halt background thread. After we're holding this lock,
// we know the background thread cannot begin loading
// mipmap levels for this texture.
FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection);
_ForegroundQueue.Remove(task);
_BackgroundQueue.Remove(task);
} else {
// Since the task manages all the state associated with loading
// a texture, we temporarily create one.
task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH);
}
// finish loading the task and destroy it.
task->Finish_Load();
task->Destroy();
} else {
// we are not in the DX8 thread. We need to add a high-priority loading
// task to the foreground queue.
// Grab the background lock. After we're holding this lock, we
// know the background thread cannot begin loading mipmap levels
// for this texture.
FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection);
// if we have a thumbnail task, we should cancel it. Since we are not
// the foreground thread, we are not allowed to call Destroy(). Instead,
// leave it queued in the completed state so it will be destroyed by Update().
if (task_thumb) {
task_thumb->Set_State(TextureLoadTaskClass::STATE_COMPLETE);
}
if (task) {
// if a load task is waiting on the background queue, we need to
// move it to the foreground queue.
if (task->Get_List() == &_BackgroundQueue) {
// remove task from list
_BackgroundQueue.Remove(task);
// add to foreground queue.
_ForegroundQueue.Push_Back(task);
}
// upgrade the task priority
task->Set_Priority(TextureLoadTaskClass::PRIORITY_HIGH);
} else {
// allocate high priority load task
task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH);
// add to back of foreground queue.
_ForegroundQueue.Push_Back(task);
}
}
}
void TextureLoader::Flush_Pending_Load_Tasks()
{
// This function can only be called from the main thread.
// (Only the main thread can make the DX8 calls necessary
// to complete texture loading. If we wanted to flush
// the pending tasks from another thread, we'd probably
// want to set a bool that is checked by Update().
WWASSERT(Is_DX8_Thread());
for (;;) {
bool done = false;
{
// we have no pending load tasks when both queues are empty
// and the background thread is not processing a texture.
// Grab the background lock. Once we're holding it, we
// know that the background thread is not processing any
// textures.
// NOTE: It's important that we do only hold on to the background
// lock while we check for completion. Otherwise, we will either
// violate the lock order when we call Update() (which grabs
// the foreground lock) or never give the background thread
// a chance to empty its queue.
FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection);
done = _BackgroundQueue.Is_Empty() && _ForegroundQueue.Is_Empty();
}
// exit loop if no entries in list
if (done) {
break;
}
Update();
ThreadClass::Switch_Thread();
}
}
// Nework update macro for texture loader.
#pragma warning(disable:4201) // warning C4201: nonstandard extension used : nameless struct/union
#include <mmsystem.h>
#define UPDATE_NETWORK \
if (network_callback) { \
unsigned long time2 = timeGetTime(); \
if (time2 - time > 20) { \
network_callback(); \
time = time2; \
} \
} \
void TextureLoader::Update(void (*network_callback)())
{
WWASSERT_PRINT(Is_DX8_Thread(), "TextureLoader::Update must be called from the main thread!");
if (TextureLoadSuspended) {
return;
}
// grab foreground lock to prevent any other thread from
// modifying texture tasks.
FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection);
unsigned long time = timeGetTime();
// while we have tasks on the foreground queue
while (TextureLoadTaskClass *task = _ForegroundQueue.Pop_Front()) {
UPDATE_NETWORK;
// dispatch to proper task handler
switch (task->Get_Type()) {
case TextureLoadTaskClass::TASK_THUMBNAIL:
Process_Foreground_Thumbnail(task);
break;
case TextureLoadTaskClass::TASK_LOAD:
Process_Foreground_Load(task);
break;
}
}
TextureBaseClass::Invalidate_Old_Unused_Textures(TextureInactiveOverrideTime);
}
void TextureLoader::Suspend_Texture_Load()
{
WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Suspend_Texture_Load must be called from the main thread!");
TextureLoadSuspended=true;
}
void TextureLoader::Continue_Texture_Load()
{
WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Continue_Texture_Load must be called from the main thread!");
TextureLoadSuspended=false;
}
void TextureLoader::Process_Foreground_Thumbnail(TextureLoadTaskClass *task)
{
switch (task->Get_State()) {
case TextureLoadTaskClass::STATE_NONE:
Load_Thumbnail(task->Peek_Texture());
FALLTHROUGH; // NOTE: fall-through is intentional
case TextureLoadTaskClass::STATE_COMPLETE:
task->Destroy();
break;
}
}
void TextureLoader::Process_Foreground_Load(TextureLoadTaskClass *task)
{
// Is high-priority task?
if (task->Get_Priority() == TextureLoadTaskClass::PRIORITY_HIGH) {
task->Finish_Load();
task->Destroy();
return;
}
// otherwise, must be a low-priority task.
switch (task->Get_State()) {
case TextureLoadTaskClass::STATE_NONE:
Begin_Load_And_Queue(task);
break;
case TextureLoadTaskClass::STATE_LOAD_MIPMAP:
task->End_Load();
task->Destroy();
break;
}
}
void TextureLoader::Begin_Load_And_Queue(TextureLoadTaskClass *task)
{
// should only be called from the DX8 thread.
WWASSERT(Is_DX8_Thread());
if (task->Begin_Load()) {
// add to front of background queue. This means the
// background load thread will service tasks in LIFO
// (last in, first out) order.
// NOTE: this was how the old code did it, with a
// comment that mentioned good reasons for doing so,
// without actually listing the reasons. I suspect
// it has something to do with visually important textures,
// like those in the foreground, starting their load last.
_BackgroundQueue.Push_Front(task);
} else {
// unable to load.
task->Apply_Missing_Texture();
task->Destroy();
}
}
void TextureLoader::Load_Thumbnail(TextureBaseClass *tc)
{
// All D3D operations must run from main thread
WWASSERT(Is_DX8_Thread());
// load thumbnail texture
IDirect3DTexture8 *d3d_texture = Load_Thumbnail(tc->Get_Full_Path(),tc->Get_HSV_Shift());
// apply thumbnail to texture
if (tc->Get_Asset_Type()==TextureBaseClass::TEX_REGULAR)
{
tc->Apply_New_Surface(d3d_texture, false);
}
// release our reference to thumbnail texture
d3d_texture->Release();
d3d_texture = nullptr;
}
void LoaderThreadClass::Thread_Function()
{
while (running) {
// if there are no tasks on the background queue, no need to grab background lock.
if (!_BackgroundQueue.Is_Empty()) {
// Grab background load so other threads know we could be
// loading a texture.
FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection);
// try to remove a task from the background queue. This could fail
// if another thread modified the queue between our test above and
// grabbing the lock.
TextureLoadTaskClass* task = _BackgroundQueue.Pop_Front();
if (task) {
// verify task is in proper state for background processing.
WWASSERT(task->Get_Type() == TextureLoadTaskClass::TASK_LOAD);
WWASSERT(task->Get_State() == TextureLoadTaskClass::STATE_LOAD_BEGUN);
// load mip map levels and return to foreground queue for final step.
task->Load();
_ForegroundQueue.Push_Back(task);
}
}
Switch_Thread();
}
}
////////////////////////////////////////////////////////////////////////////////
//