-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd3d.cpp
More file actions
1950 lines (1752 loc) · 59.4 KB
/
Copy pathd3d.cpp
File metadata and controls
1950 lines (1752 loc) · 59.4 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
//-----------------------------------------------------------------------------
// File: d3d.cpp
//
// Implementation of d3ddev_t.
// Shaders vs Textures.
// There are two types of shader, textures and shaders, a shader is a shader
// as defined by a script in a shader file, a texture represents a single
// texture applied to a surface. These are all defined as a single resource
// type the shader however the terms shader and texture are used in the comments
// and the appropriate handle types are used throughout the code
//-----------------------------------------------------------------------------
#include "d3d.h"
#include "console.h"
#include "pak.h"
#include "util.h"
#include "timer.h"
#include "ui.h"
#include <memory>
#include "win.h"
#include "exec.h"
#include "mem.h"
#include <d3dx8.h>
#define new mem_new
#undef d3d
using std::auto_ptr;
cvstr_t
shaders_callback(int argc, cvstr_t* args)
{
d3d_t::get_instance().list_shaders(0, 0);
return cvstr_t();
}
cfunc_t cf_shaders("shaders", shaders_callback);
// General Purpose cvars
cvar_int_t showtris("showtris", 0, CVF_NONE, 0, 2);
cvar_int_t display_width("display_width", 640, CVF_CONST);
cvar_int_t display_height("display_height", 480, CVF_CONST);
cvar_int_t display_color_depth("display_color_depth", 32, CVF_CONST);
cvar_int_t display_z_depth("display_z_depth", 24, CVF_CONST);
cvar_int_t display_stencil_depth("display_stencil_depth", 8, CVF_CONST);
cvar_int_t display_back_buffers("display_back_buffers", 2, CVF_CONST, 2, 3);
cvar_int_t display_fullscreen("display_fullscreen", 0, CVF_CONST, 0, 1);
cvar_int_t display_vsync("display_vsync", 0, CVF_CONST, 0, 1);
cvar_int_t d3d_adapter("d3d_adapter", 0, CVF_CONST, 0);
cvar_int_t d3d_device("d3d_device", 0, CVF_CONST, 0, 1);
// 0 = use the hardware device
// 1 = use the reference device
// Configuration cvars, highly unlikely to change, changes to these may cause
// some nasty behaviour
cvar_int_t max_shaders("max_shaders", 4096, CVF_CONST);
cvar_int_t max_shader_passes("max_shader_passes", 4096, CVF_CONST);
cvar_int_t max_static_verts("max_static_verts", 60000, CVF_CONST);
cvar_int_t max_static_inds("max_static_inds", 120000, CVF_CONST);
cvar_int_t max_dynamic_verts("max_dynamic_verts", 20000, CVF_CONST);
cvar_int_t max_dynamic_inds("max_dynamic_inds", 20000, CVF_CONST);
// Surface flags
const uint SF_PRECACHE = 0x01; // Precache this shader
const uint SF_CACHED = 0x02; // Texture is loaded into memory
const uint SF_RETAIN = 0x04; // Never unload this shader
const uint SF_NOMIPMAPS = 0x08; // No mipmaps for this shader
const uint SF_NOPICMIP = 0x10; // Never picmip this shader
const uint SF_CULLFRONT = 0x20; // Cull front faces
const uint SF_CULLBACK = 0x40; // Cull back faces (default)
namespace {
// Most textures for an anim map
const int MAX_PASS_MAPS = 8;
// Most texture coordinate mods for a pass
const int MAX_PASS_TCMODS = 3;
const DWORD FIXED_VERTEX_FORMAT = D3DFVF_XYZ
| D3DFVF_DIFFUSE
| D3DFVF_NORMAL
| D3DFVF_TEX2
| D3DFVF_TEXCOORDSIZE2(0)
| D3DFVF_TEXCOORDSIZE2(1);
// Sort orders
const int SORT_PORTAL = 1;
const int SORT_SKY = 2;
const int SORT_OPAQUE = 3;
const int SORT_BANNER = 6;
const int SORT_UNDERWATER = 8;
const int SORT_ADDITIVE = 9;
const int SORT_NEAREST = 16;
// 0 = null shader, just use 0, no define
const htexture_t HT_NOSHADER = 1; // Texture handle to refer to the whiteimage
const htexture_t HT_WHITEIMAGE = 2; // Texture handle to refer to the whiteimage
const htexture_t HT_LIGHTMAP = 3; // Texture handle to refer to the current face lightmap
const int NUM_RESERVED_SHADERS = 4; // Number of shader slots reserved for programatically defined shaders
// const DWORD vertex_shader_decl[] = {
// D3DVSD_STREAM(0),
// D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3),
// D3DVSD_REG(D3DVSDE_NORMAL, D3DVSDT_FLOAT3),
// D3DVSD_REG(D3DVSDE_DIFFUSE, D3DVSDT_D3DCOLOR),
// D3DVSD_REG(D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2),
// D3DVSD_REG(D3DVSDE_TEXCOORD1, D3DVSDT_FLOAT2),
// D3DVSD_END(),
// };
//
// const int VSCONST_CLIP_MATRIX = 4; // Clip matrix starts at const 4
//
// const char vertex_shader_src[] =
// "vs.1.1 // Shader version 1.1\n"
// "m4x4 oPos, v0, c4 // Transform pos\n"
// "mov oD0, v5 // Vertex Diffuse color\n"
// "mov oT0.xy, v7 // Tex-coord 0\n"
// "mov oT1.xy, v8 // Tex-coord 1\n";
// Pass flags
const int PF_ALPHABLEND = 0x01; // Alpha blending enabled
const int PF_ALPHATEST = 0x02; // Pass requires that alpha test be enabled
const int PF_CLAMP = 0x04; // Clamp texture co-ords for this pass
const int PF_ENVIRONMENT= 0x08; // Environment map
const int PF_NOZWRITE = 0x10; // Z write should be disabled for this pass
const int PF_USETC1 = 0x20; // Use the lightmap texture co-ords
inline bool
shader_name_cmp(const char* name1, const char* name2)
// Compare two shader names
{
const char* n1 = name1;
const char* n2 = name2;
// Compare the two without case sensitivity
while (*n1 && u_tolower(*n1) == u_tolower(*n2)) {
++n1;
++n2;
}
// If at the end of both they match
if (*n1 == '\0' && *n2 == '\0')
return true;
if (n1 != name1 && *(n1 - 1) == '.') {
// If name1 ends in .tga and name2 is ended or ends in "jpg" its a match
if (u_fncmp(n1, "tga") == 0)
if (*n2 == '\0' || u_fncmp(n2, "jpg") == 0)
return true;
// If name1 ends in .tga and name2 is ended or ends in ".jpg" its a match
if (u_fncmp(n1, "jpg") == 0)
if (*n2 == '\0' || u_fncmp(n2, "tga") == 0)
return true;
} else if (*n1 == '\0') {
if (u_fncmp(n2, ".jpg") == 0 || u_fncmp(n2, ".tga") == 0)
return true;
} else if (*n2 == '\0') {
if (u_fncmp(n1, ".jpg") == 0 || u_fncmp(n1, ".tga") == 0)
return true;
}
return false;
}
}
enum wave_type_t {
WAVE_INVERSESAWTOOTH,
WAVE_NOISE,
WAVE_SAWTOOTH,
WAVE_SIN,
WAVE_SQUARE,
WAVE_TRIANGLE,
};
struct wavefunc_t {
wave_type_t type;
float base;
float amplitude;
float phase;
float frequency;
float clamp_value(float time) const {
float pos = time * frequency + phase;
switch (type) {
case WAVE_INVERSESAWTOOTH:
return m_clamp(base + amplitude * m_inversesawtooth_wave(pos));
case WAVE_SAWTOOTH:
return m_clamp(base + amplitude * m_sawtooth_wave(pos));
case WAVE_SIN:
return m_clamp(base + amplitude * m_sin_wave(pos));
case WAVE_SQUARE:
return m_clamp(base + amplitude * m_square_wave(pos));
case WAVE_TRIANGLE:
return m_clamp(base + amplitude * m_triangle_wave(pos));
}
return 0.5f; // keep the compiler happy
}
float value(float time) const {
float pos = time * frequency + phase;
switch (type) {
case WAVE_INVERSESAWTOOTH:
return base + amplitude * m_inversesawtooth_wave(pos);
case WAVE_SAWTOOTH:
return base + amplitude * m_sawtooth_wave(pos);
case WAVE_SIN:
return base + amplitude * m_sin_wave(pos);
case WAVE_SQUARE:
return base + amplitude * m_square_wave(pos);
case WAVE_TRIANGLE:
return base + amplitude * m_triangle_wave(pos);
}
return 0.5f; // keep the compiler happy
}
};
enum tcmod_type_t {
TCMOD_ROTATE,
TCMOD_SCALE,
TCMOD_SCROLL,
TCMOD_STRETCH,
};
enum rgbgen_type_t {
RGBGEN_IDENTITY,
RGBGEN_IDENTITYLIGHTING,
RGBGEN_VERTEX,
RGBGEN_WAVE,
};
enum alphagen_type_t {
ALPHAGEN_IDENTITY,
ALPHAGEN_VERTEX,
ALPHAGEN_WAVE,
};
struct tcmod_t {
tcmod_type_t type;
union {
float angle; // used for rotate
struct {
float x; // used for scale and scroll
float y; // used for scale and scroll
};
wavefunc_t wave; // used for stretch
};
};
enum shader_type_t {
STYPE_TEXTURE, // Simple lightmap lit texture
STYPE_SHADER // Fully defined shader
};
struct d3d_t::shader_t {
int type; // Shader type
str_t<64> name; // Shader name
int flags; // Shader flags
int sort; // Sort order
com_ptr_t<IDirect3DTexture8> texture; // D3D texture, STYPE_TEXTURE only
// not in union to ensure destructor
int num_passes; // Number of passes for STYPE_SHADER
union {
int first_pass; // First pass for STYPE_SHADER
hshader_t texture; // Texture index for STYPE_TEXTURE
};
};
struct d3d_t::shader_pass_t {
alphagen_type_t alphagen;
wavefunc_t alphagen_wave;
rgbgen_type_t rgbgen;
wavefunc_t rgbgen_wave;
int flags;
D3DCMPFUNC alpha_func;
uint alpha_ref;
D3DBLEND src_blend;
D3DBLEND dest_blend;
D3DCMPFUNC depth_func;
float anim_freq; // Animation frequency
int num_maps; // Number of texture handles
htexture_t maps[MAX_PASS_MAPS];
int num_tcmods;
tcmod_t tcmods[MAX_PASS_TCMODS];
htexture_t map() const
{
if (num_maps == 0)
return 0;
else if (num_maps == 1)
return maps[0];
else
return maps[m_ftoi(timer.time(TID_APP) * anim_freq) % num_maps];
}
};
d3d_t::d3d_t() :
num_shaders(0),
num_passes(0),
shaders(0),
passes(0),
num_static_verts(0),
num_static_inds(0)
{
u_zeromem(&d3dpp, sizeof(d3dpp));
}
d3d_t&
d3d_t::get_instance()
{
static std::auto_ptr<d3d_t> instance(new d3d_t());
return *instance;
}
uint
d3d_t::get_surface_flags(hshader_t shader)
{
u_assert(shader >= 0 && shader < num_shaders);
return shaders[shader].flags;
}
result_t
d3d_t::init()
// Initialises the device, scans for available display modes etc, does not
// actually set a display mode
{
shaders = new shader_t[*max_shaders];
passes = new shader_pass_t[*max_shader_passes];
// Declare some programatically generated shaders
// Null shader, just allows use of 0 as a null handle without the need to
// constantly offset by 1
shaders[0].name = "<null>";
shaders[0].type = STYPE_TEXTURE;
shaders[0].flags = SF_RETAIN;
// Specific noshader shader
shaders[1].name = "noshader";
shaders[1].type = STYPE_TEXTURE;
shaders[1].flags = SF_RETAIN;
// A plain white texture, generated in create
shaders[2].name = "$whiteimage";
shaders[2].type = STYPE_TEXTURE;
shaders[2].flags = SF_RETAIN;
// Shader handle set asside for lightmap textures
shaders[3].name = "$lightmap";
shaders[3].type = STYPE_TEXTURE;
shaders[3].flags = SF_RETAIN;
num_shaders = NUM_RESERVED_SHADERS;
return info.create();
}
result_t
d3d_t::create()
// Create the Direct 3d device, returns success or failure
{
if (!choose_present_params())
return result_t::last;
uint behaviour = D3DCREATE_HARDWARE_VERTEXPROCESSING;
if (back_buffer_format->format->device->caps.DevCaps & D3DDEVCAPS_PUREDEVICE)
behaviour |= D3DCREATE_PUREDEVICE; // Create a pure device if available
// if (chosen_device->caps.VertexShaderVersion < D3DVS_VERSION(1, 1))
// return "Vertex Shader version 1.1 not supported";
HRESULT hr;
hr = info->CreateDevice(
back_buffer_format->format->device->adapter->ordinal,
back_buffer_format->format->device->type,
hwnd,
behaviour,
&d3dpp,
&d3ddev
);
if (FAILED(hr))
return "IDirect3D8->CreateDevice() failed";
// Create the dynamic usage index buffer
hr = d3ddev->CreateIndexBuffer(
*max_dynamic_inds * sizeof(index_t),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_DEFAULT,
&ibuf
);
if (FAILED(hr))
return "IDirect3D8->CreateIndexBuffer() failed for dynamic index buffer";
// Create the dynamic usage vertex buffer
hr = d3ddev->CreateVertexBuffer(
*max_dynamic_verts * sizeof(vertex_t),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY,
FIXED_VERTEX_FORMAT,
D3DPOOL_DEFAULT,
&vbuf
);
if (FAILED(hr))
return "IDirect3D8->CreateVertexBuffer() failed for dynamic vertex buffer";
// Create the static usage index buffer
d3ddev->CreateIndexBuffer(
*max_static_inds * sizeof(index_t),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_DEFAULT,
&sibuf
);
if (FAILED(hr))
return "IDirect3D8->CreateIndexBuffer() failed for static index buffer";
// Create the static usage vertex buffer
d3ddev->CreateVertexBuffer(
*max_static_verts * sizeof(vertex_t),
D3DUSAGE_WRITEONLY,
FIXED_VERTEX_FORMAT,
D3DPOOL_DEFAULT,
&svbuf
);
if (FAILED(hr))
return "IDirect3D8->CreateVertexBuffer() failed for static vertex buffer";
// One time state changes
// d3ddev->SetRenderState(D3DRS_DITHERENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
d3ddev->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
// Texture filtering options
d3ddev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(1, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(1, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(1, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
d3ddev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0);
d3ddev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
d3ddev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
d3ddev->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
d3ddev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
d3ddev->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
d3ddev->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
d3ddev->SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
d3ddev->SetTextureStageState(1, D3DTSS_ALPHAARG2, D3DTA_CURRENT);
d3ddev->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
d3ddev->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
d3ddev->SetStreamSource(0, vbuf, sizeof(vertex_t));
d3ddev->SetVertexShader(FIXED_VERTEX_FORMAT);
// Create $whiteimage here
// // Compile the vertex shader
// com_ptr_t<ID3DXBuffer> assembled_shader;
// com_ptr_t<ID3DXBuffer> assembler_errors;
//
// HRESULT hr = D3DXAssembleShader(
// vertex_shader_src,
// sizeof(vertex_shader_src) - 1,
// 0,
// 0,
// &assembled_shader,
// &assembler_errors
// );
// if (FAILED(hr)) {
// console.print("Failed to assemble vertex shader:\n");
// console.print(static_cast<char*>(assembler_errors->GetBufferPointer()));
// return "Failed to assemble vertex shader";
// }
// hr = d3ddev->CreateVertexShader(
// vertex_shader_decl,
// static_cast<DWORD*>(assembled_shader->GetBufferPointer()),
// &vertex_shader,
// 0
// );
// if (FAILED(hr)) {
// console.print("IDirect3DDevice8->CreateVertexShader() failed:\n");
// console.printf("%s\n", get_error_string(hr));
// return "Failed to create vertex shader";
// }
// d3ddev->SetVertexShader(vertex_shader);
float gamma = 0.75f;
D3DGAMMARAMP ramp;
for (int i=0 ; i<256 ; i++)
{
//int val = pow(m_itof(i), 1.0f / gamma);
int val = i * (512 - i);
ramp.red[i] = u_min(val, 65535);
ramp.green[i] = u_min(val, 65535);
ramp.blue[i] = u_min(val, 65535);
}
d3ddev->SetGammaRamp(D3DSGR_NO_CALIBRATION, &ramp);
return true;
}
const char*
d3d_t::get_error_string(HRESULT hr)
{
const int MAX_ERROR_STRING_LENGTH = 1024;
static char str[MAX_ERROR_STRING_LENGTH];
HRESULT hre = D3DXGetErrorString(hr, str, MAX_ERROR_STRING_LENGTH);
if (FAILED(hre))
u_snprintf(str, MAX_ERROR_STRING_LENGTH, "D3DXGetErrorString() failed for hresult %#x", hr);
return str;
}
void
d3d_t::destroy()
// Free any resources used by the device
{
delete [] shaders;
num_shaders = 0;
shaders = 0;
delete [] passes;
num_passes = 0;
passes = 0;
if (d3ddev) {
d3ddev->SetIndices(NULL, 0);
d3ddev->SetStreamSource(0, NULL, 0);
d3ddev->SetTexture(0, NULL);
d3ddev->SetTexture(1, NULL);
}
ibuf = 0;
sibuf = 0;
vbuf = 0;
svbuf = 0;
d3ddev = 0;
info.destroy();
}
bool
d3d_t::lost()
// Returns true if the device has been lost, for example if someone uses
// alt+tab to go to a different window while in full screen mode. If this
// happens then all video memory resources should be freed and recreated
{
HRESULT hr = d3ddev->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST)
return true;
return false;
}
int next_index = 0;
int next_vertex = 0;
bool
d3d_t::begin()
{
// d3ddev->SetTransform(D3DTS_WORLD, NULL);
// d3ddev->SetTransform(D3DTS_VIEW, NULL);
// d3ddev->SetTransform(D3DTS_PROJECTION, NULL);
next_vertex = 0;
next_index = 0;
return SUCCEEDED(d3ddev->BeginScene());
}
void
d3d_t::end()
{
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);
}
matrix_t world_matrix;
void
d3d_t::set_camera(const camera_t& camera)
// Set the camera to be used for upcoming rendering
{
d3ddev->SetTransform(D3DTS_WORLD, reinterpret_cast<const D3DMATRIX*>(&camera.mat_world));
d3ddev->SetTransform(D3DTS_VIEW, reinterpret_cast<const D3DMATRIX*>(&camera.mat_view));
d3ddev->SetTransform(D3DTS_PROJECTION, reinterpret_cast<const D3DMATRIX*>(&camera.mat_proj));
world_matrix = camera.mat_world;
// matrix_t clip_mat = camera.mat_world * camera.mat_view * camera.mat_proj ;
// clip_mat.transpose();
// d3ddev->SetVertexShaderConstant(VSCONST_CLIP_MATRIX, &clip_mat, 4);
// d3ddev->SetTransform(D3DTS_TEXTURE0, reinterpret_cast<const D3DXMATRIX*>(&rot));
// d3ddev->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );
}
int
compare_faces(const void* f1, const void* f2)
{
const face_t* face1 = static_cast<const face_t*>(f1);
const face_t* face2 = static_cast<const face_t*>(f2);
const d3d_t& inst = d3d_t::get_instance();
// Sort by sort order, then shader, then lightmap
if (inst.shaders[face1->shader].sort != inst.shaders[face2->shader].sort)
return inst.shaders[face1->shader].sort - inst.shaders[face2->shader].sort;
else if (face1->shader != face2->shader)
return face1->shader - face2->shader;
else
return face1->lightmap - face2->lightmap;
}
render_stats_t
d3d_t::render_list(display_list_t& dl)
// Render the face in question
{
qsort(dl.face_buffer(), dl.num_faces(), sizeof(face_t), compare_faces);
render_stats_t stats;
const face_t* face;
for (const face_t* f = dl.face_buffer(); f != dl.face_buffer_end(); f = (face == f ? f + 1 : face)) {
face = f;
begin_shader(f->shader, f->lightmap);
for (int pass = 0; pass < shaders[f->shader].num_passes; ++pass) {
begin_pass(f->shader, f->lightmap, pass);
for (face = f; face->shader == f->shader && face->lightmap == f->lightmap && face != dl.face_buffer_end(); ++face) {
// Update render stats
stats += render_stats_t(1, face->num_verts, face->num_inds);
// Setup the vertex data
int base_vertex;
if (face->verts) {
base_vertex = upload_dynamic_verts(face->verts, face->num_verts);
d3ddev->SetStreamSource(0, vbuf, sizeof(vertex_t));
} else {
d3ddev->SetStreamSource(0, svbuf, sizeof(vertex_t));
base_vertex = face->base_vert;
}
// Setup the index data
int base_index;
if (face->inds) {
base_index = upload_dynamic_inds(face->inds, face->num_inds);
d3ddev->SetIndices(ibuf, base_vertex);
} else {
d3ddev->SetIndices(sibuf, base_vertex);
base_index = face->base_ind;
}
// Now do the drawing
HRESULT hr = d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, face->num_verts, base_index, face->num_inds / 3);
u_assert(SUCCEEDED(hr));
}
end_pass(f->shader, f->lightmap, pass);
}
end_shader(f->shader, f->lightmap);
}
if (*showtris)
show_tris(dl);
return stats;
}
void
d3d_t::show_tris(display_list_t& dl)
// Render the face in question
{
// Set up the render states for showtris
d3ddev->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
if (*showtris == 1) { // White lines
d3ddev->SetRenderState(D3DRS_TEXTUREFACTOR, color_t::white);
} else { // Blend diffuse colour with white for lines
d3ddev->SetRenderState(D3DRS_TEXTUREFACTOR, 0x1fffffff);
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
d3ddev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_BLENDFACTORALPHA); // use diffuse color
}
for (const face_t* face = dl.face_buffer(); face != dl.face_buffer_end(); ++face) {
// Setup the vertex data
int base_vertex;
if (face->verts) {
base_vertex = upload_dynamic_verts(face->verts, face->num_verts);
d3ddev->SetStreamSource(0, vbuf, sizeof(vertex_t));
} else {
d3ddev->SetStreamSource(0, svbuf, sizeof(vertex_t));
base_vertex = face->base_vert;
}
// Setup the index data
int base_index;
if (face->inds) {
base_index = upload_dynamic_inds(face->inds, face->num_inds);
d3ddev->SetIndices(ibuf, base_vertex);
} else {
d3ddev->SetIndices(sibuf, base_vertex);
base_index = face->base_ind;
}
// Now do the drawing
HRESULT hr = d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, face->num_verts, base_index, face->num_inds / 3);
u_assert(SUCCEEDED(hr));
}
// Reset the render states to defaults
if (*showtris == 2)
d3ddev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
d3ddev->SetRenderState(D3DRS_TEXTUREFACTOR, 0xffffffff);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
d3ddev->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
}
htexture_t
d3d_t::define_texture(const char* name, bool parsing)
// Stores a texture name, makes sure the file exists on disk but does NOT
// load the texture into memory. Parsing says whether this texture is being
// loaded as part of shader parsing at startup, if so then the error messages
// are not printed if c_verbose_shader_parsing is false
{
u_assert(num_shaders < *max_shaders);
htexture_t ht = get_texture(name);
if (ht != 0)
return ht;
shader_t& shader = shaders[num_shaders];
// Set the defaults for STYPE_TEXTURE shaders
shader.type = STYPE_TEXTURE;
shader.name = name; // First token is the shader name
shader.flags = SF_CULLBACK;
shader.sort = SORT_OPAQUE;
shader.texture = 0;
shader.num_passes = 1;
shader.first_pass = -1;
if (pak.file_exists(shader.name))
return num_shaders++;
int length = shader.name.length();
if (length < 4)
return 0;
// If name ends in ".tga" try with a ".jpg" extension and vice versa
if (u_fncmp(&shader.name[length - 4], ".tga") == 0) {
u_strcpy(&shader.name[length - 3], "jpg");
if (pak.file_exists(shader.name))
return num_shaders++;
} else if (u_fncmp(&shader.name[length - 4], ".jpg") == 0) {
u_strcpy(&shader.name[length - 3], "tga");
if (pak.file_exists(shader.name))
return num_shaders++;
}
// That didnt work, try just adding the tga extension
shader.name += ".tga";
if (pak.file_exists(shader.name))
return num_shaders++;
// That didnt work, try just adding the jpg extension
shader.name[length] = '\0';
shader.name += ".jpg";
if (pak.file_exists(shaders[num_shaders].name))
return num_shaders++;
// No such shader, just fail it
if (!parsing || *verbose_shader_parsing)
console.printf("Texture not found: %s\n", name);
return 0;
}
htexture_t
d3d_t::get_texture(const char* name)
// Return the texture handle of 0 if the texture has not yet been defined. This
// is an internal method and only returns ST_TEXTURE shader handles
{
// Check the exact name
for (int i = 0; i < num_shaders; ++i)
if ((shaders[i].type == STYPE_TEXTURE) && shader_name_cmp(name, shaders[i].name))
return i;
return 0;
}
void
d3d_t::ensure_loaded(htexture_t texture)
{
if (texture >= NUM_RESERVED_SHADERS && shaders[texture].texture == 0)
load_texture(texture);
}
hshader_t
d3d_t::get_shader(const char* name, bool retain)
// Return the handle to the named shader
{
hshader_t handle = 0;
// Search for a shader with that name
for (int i = 0; i < num_shaders && handle == 0; ++i)
if (shaders[i].type == STYPE_SHADER && shader_name_cmp(name, shaders[i].name))
handle = i;
// Define a texture with that name if no texture found
if (handle == 0)
handle = define_texture(name, false);
if (handle) {
int flags = retain ? SF_RETAIN | SF_PRECACHE : SF_PRECACHE;
shader_t& shader = shaders[handle];
if (!(shader.flags & SF_CACHED)) {
shader.flags |= flags;
if (shader.type == STYPE_SHADER) {
for (int p = 0; p < shader.num_passes; ++p) {
shader_pass_t& pass = passes[shader.first_pass + p];
for (int m = 0; m < pass.num_maps; ++m) {
shader_t& map = shaders[pass.maps[m]];
if (!(map.flags & SF_CACHED))
map.flags |= flags;
}
}
}
}
} else {
console.printf("get_shader: shader not found %s\n", name);
}
return handle;
}
void
d3d_t::begin_shader(hshader_t shader, htexture_t lightmap)
{
u_assert(shader < num_shaders);
u_assert(lightmap < num_shaders);
// console.printf("begin_shader %s %s\n", shaders[shader].name.c_str(), shaders[lightmap].name.c_str());
if (shaders[shader].flags & SF_CULLFRONT)
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
else if (!(shaders[shader].flags & SF_CULLBACK))
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
}
void
d3d_t::begin_pass(hshader_t shader, htexture_t lightmap, int passno)
{
color_t modulate(color_t::identity);
// console.printf(" begin_pass %s %s %d\n", shaders[shader].name.c_str(), shaders[lightmap].name.c_str(), passno);
if (shaders[shader].type == STYPE_SHADER) {
const shader_pass_t& pass = passes[shaders[shader].first_pass + passno];
if (pass.flags & PF_ALPHABLEND) {
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_SRCBLEND, pass.src_blend);
d3ddev->SetRenderState(D3DRS_DESTBLEND, pass.dest_blend);
}
if (pass.flags & PF_ALPHATEST) {
d3ddev->SetRenderState(D3DRS_ALPHAFUNC, pass.alpha_func);
d3ddev->SetRenderState(D3DRS_ALPHAREF, pass.alpha_ref);
d3ddev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
}
if (pass.flags & PF_CLAMP) {
d3ddev->SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
d3ddev->SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
}
if (pass.flags & PF_NOZWRITE)
d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
if (pass.flags & PF_USETC1)
d3ddev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 1);
if (pass.depth_func != D3DCMP_LESSEQUAL)
d3ddev->SetRenderState(D3DRS_ZFUNC, pass.depth_func);
if (pass.alphagen != ALPHAGEN_IDENTITY) {
d3ddev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
if (pass.alphagen == ALPHAGEN_WAVE) {
d3ddev->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR);
modulate.set_a(pass.alphagen_wave.clamp_value(timer.time(TID_APP)));
}
}
if (pass.rgbgen != RGBGEN_IDENTITY) {
d3ddev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
if (pass.rgbgen == RGBGEN_WAVE) {
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
modulate.set_r(pass.rgbgen_wave.clamp_value(timer.time(TID_APP)));
modulate.g = modulate.r;
modulate.b = modulate.r;
}
if (pass.rgbgen == RGBGEN_IDENTITYLIGHTING) {
d3ddev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
modulate.r = 128;
modulate.g = modulate.r;
modulate.b = modulate.r;
}
}
if (pass.rgbgen == RGBGEN_WAVE || pass.rgbgen == RGBGEN_IDENTITYLIGHTING || pass.alphagen == ALPHAGEN_WAVE)
d3ddev->SetRenderState(D3DRS_TEXTUREFACTOR, modulate);
matrix_t mat(matrix_t::identity);
if (pass.num_tcmods) {
for (int i = 0; i < pass.num_tcmods; ++i) {
matrix_t temp(matrix_t::identity);
float magnitude;
matrix_t m1(matrix_t::identity), m2(matrix_t::identity), m3(matrix_t::identity);
switch (pass.tcmods[i].type) {
case TCMOD_ROTATE:
// translate(-0.5, -0.5) * rotate(angle) * translate(0.5, 0.5)
temp._00 = m_cos(m_deg2rad(pass.tcmods[i].angle * timer.time(TID_APP)));
temp._01 = m_sin(m_deg2rad(pass.tcmods[i].angle * timer.time(TID_APP)));
temp._10 = -temp._01;
temp._11 = temp._00;
temp._20 = 0.5f * (temp._01 - temp._00 + 1.0f);
temp._21 = 0.5f * (temp._10 - temp._00 + 1.0f);
break;
case TCMOD_SCALE:
temp._00 = pass.tcmods[i].x;
temp._11 = pass.tcmods[i].y;
// temp._20 = (pass.tcmods[i].x + 1.0f) * -0.5f;
// temp._21 = (pass.tcmods[i].y + 1.0f) * -0.5f;
break;
case TCMOD_SCROLL:
temp._20 = pass.tcmods[i].x * timer.time(TID_APP);
temp._21 = pass.tcmods[i].y * timer.time(TID_APP);
break;
case TCMOD_STRETCH:
magnitude = pass.tcmods[i].wave.value(timer.time(TID_APP));
m1._20 = -0.5;
m1._21 = -0.5;
m2._00 = magnitude;
m2._11 = magnitude;
m3._20 = 0.5;
m3._21 = 0.5;
temp = m1 * m2 * m3;
break;
}
mat *= temp;
}
d3ddev->SetTransform(D3DTS_TEXTURE0, reinterpret_cast<const D3DXMATRIX*>(&mat));
d3ddev->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
}
if (pass.flags & PF_ENVIRONMENT) {
mat._00 = 0.5f;
mat._01 = 0.0f;
mat._10 = 0.0f;
mat._11 = 0.5f;
mat[2] = vec4_t(0.0f, 0.0f, 1.0f, 0.0f);
mat[3] = vec4_t(0.0f, 0.0f, 0.0f, 1.0f);
d3ddev->SetTransform(D3DTS_TEXTURE0, reinterpret_cast<const D3DXMATRIX*>(&(mat)));
d3ddev->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
d3ddev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR);
}
// Set the texture
htexture_t map = pass.map();
ensure_loaded(map);
if (map == HT_LIGHTMAP)
d3ddev->SetTexture(0, shaders[lightmap].texture);
else
d3ddev->SetTexture(0, shaders[map].texture);
} else { // (shaders[shader].type == STYPE_TEXTURE)
// The one and only pass for textures
ensure_loaded(shader);
d3ddev->SetTexture(0, shaders[shader].texture);
if (lightmap) {
d3ddev->SetTexture(1, shaders[lightmap].texture);
d3ddev->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
}
}
}
void
d3d_t::end_pass(hshader_t shader, htexture_t lightmap, int passno)
{
// console.printf(" end_pass %s %s %d\n", shaders[shader].name.c_str(), shaders[lightmap].name.c_str(), passno);
if (shaders[shader].type == STYPE_SHADER) {
const shader_pass_t& pass = passes[shaders[shader].first_pass + passno];